@qualcomm-ui/mdx-vite 2.8.0 → 2.10.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/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/angular-demo-plugin/angular-demo-plugin.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/mdx-utils.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-frontmatter-description.ts", "../src/docs-plugin/remark/remark-self-link-headings.ts", "../src/docs-plugin/remark/remark-spoilers.ts", "../src/docs-plugin/shiki/utils.ts", "../src/docs-plugin/shiki/shiki-transformer-code-attribute.ts", "../src/docs-plugin/shiki/shiki-transformer-hidden.ts", "../src/docs-plugin/shiki/shiki-transformer-preview-block.ts", "../src/docs-plugin/shiki/internal/shiki-transformer-tailwind.ts", "../src/react-demo-plugin/demo-plugin-constants.ts", "../src/react-demo-plugin/demo-plugin-utils.ts", "../src/react-demo-plugin/react-demo-plugin.ts"],
4
- "sourcesContent": ["// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\nimport chalk from \"chalk\"\nimport {type FSWatcher, watch} from \"chokidar\"\nimport {glob} from \"glob\"\nimport {existsSync} from \"node:fs\"\nimport {readFile, stat} from \"node:fs/promises\"\nimport {basename, dirname, join, relative, resolve} from \"node:path\"\nimport {\n createHighlighter,\n type Highlighter,\n type ThemeRegistration,\n type ThemeRegistrationRaw,\n type ThemeRegistrationResolved,\n} from \"shiki\"\nimport * as ts from \"typescript\"\nimport type {Plugin, ViteDevServer} from \"vite\"\n\nimport {\n type AngularDemoInfo,\n quiCustomDarkTheme,\n type SourceCodeData,\n} from \"@qualcomm-ui/mdx-common\"\nimport {dedent} from \"@qualcomm-ui/utils/dedent\"\n\nimport {getShikiTransformers} from \"../docs-plugin\"\nimport {\n extractPreviewFromHighlightedHtml,\n transformerCodeAttribute,\n transformerPreviewBlock,\n} from \"../docs-plugin/shiki\"\nimport {createShikiTailwindTransformer} from \"../docs-plugin/shiki/internal\"\n\nexport interface AngularDemoPluginOptions {\n demoPattern?: string | string[]\n /**\n * A mapping of <demoId, initialHtml>, which will be used for the initial\n * serverside render of each demo to prevent FOUC.\n */\n initialHtml?: Record<string, string>\n routesDir?: string\n theme?: {\n dark:\n | ThemeRegistrationRaw\n | ThemeRegistration\n | ThemeRegistrationResolved\n | string\n light:\n | ThemeRegistrationRaw\n | ThemeRegistration\n | ThemeRegistrationResolved\n | string\n }\n /**\n * When enabled, transforms Tailwind class names to inline styles in the\n * highlighted code. Non-inlineable classes (hover:, sm:, etc.) are kept as\n * className and their CSS rules are aggregated into a residual-css entry.\n */\n transformTailwindStyles?: boolean\n}\n\ninterface RelativeImport {\n resolvedPath: string\n source: string\n}\n\ninterface PathAlias {\n pattern: RegExp\n replacement: string\n}\n\ninterface HighlightCodeResult {\n full: string\n preview?: string | null\n}\n\nconst VIRTUAL_MODULE_ID = \"\\0virtual:angular-demo-registry\"\nconst LOG_PREFIX = \"[angular-demo]\"\n\nlet hasWatcherInitialized = false\n\nfunction logDev(...args: any[]) {\n if (!hasWatcherInitialized) {\n return\n }\n console.log(...args)\n}\n\nlet demoDimensionsCache: Record<string, DOMRect> = {}\nlet highlighter: Highlighter | null = null\nlet initCount = 0\nconst demoRegistry = new Map<string, AngularDemoInfo>()\nlet hotUpdateDemoIds: string[] = []\n\nexport function angularDemoPlugin({\n demoPattern = \"src/routes/**/demos/*.ts\",\n initialHtml,\n routesDir = \"src/routes\",\n theme = {\n dark: quiCustomDarkTheme,\n light: \"github-light-high-contrast\",\n },\n transformTailwindStyles,\n}: AngularDemoPluginOptions = {}): Plugin {\n let watcher: FSWatcher | null = null\n let devServer: ViteDevServer | null = null\n\n const defaultShikiOptions = {\n defaultColor: \"light-dark()\",\n themes: {\n dark: theme.dark,\n light: theme.light,\n },\n }\n\n return {\n async buildEnd() {\n if (watcher) {\n await watcher.close()\n watcher = null\n hasWatcherInitialized = false\n }\n },\n async buildStart() {\n if (initCount === 0) {\n initCount++\n return\n }\n\n if (!highlighter) {\n try {\n highlighter = await createHighlighter({\n langs: [\"angular-ts\", \"angular-html\", \"css\"],\n themes: [theme.dark, theme.light],\n })\n logDev(`${chalk.blue.bold(LOG_PREFIX)} Shiki highlighter initialized`)\n } catch (error) {\n console.warn(\n `${chalk.blue.bold(LOG_PREFIX)} Failed to initialize highlighter:`,\n error,\n )\n }\n }\n\n logDev(`${chalk.blue.bold(LOG_PREFIX)} Initializing Angular demo scanner`)\n await collectAngularDemos()\n\n if (process.env.NODE_ENV === \"development\") {\n if (!hasWatcherInitialized) {\n hasWatcherInitialized = true\n await setupAngularWatcher()\n } else {\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} Watcher already initialized by another instance`,\n )\n }\n }\n },\n configureServer(server) {\n devServer = server\n let dimensionUpdateTimeout: NodeJS.Timeout | null = null\n\n server.ws.on(\n \"custom:store-demo-dimensions\",\n (data: {demoId: string; dimensions: DOMRect}) => {\n const demoId = data.demoId\n demoDimensionsCache[demoId] = data.dimensions\n\n if (dimensionUpdateTimeout) {\n clearTimeout(dimensionUpdateTimeout)\n }\n\n dimensionUpdateTimeout = setTimeout(() => {\n const module = server.moduleGraph.getModuleById(VIRTUAL_MODULE_ID)\n if (module) {\n server.moduleGraph.invalidateModule(module)\n }\n }, 50)\n },\n )\n\n server.ws.on(\"custom:reset-demo-dimensions\", () => {\n demoDimensionsCache = {}\n const module = server.moduleGraph.getModuleById(VIRTUAL_MODULE_ID)\n if (module) {\n server.moduleGraph.invalidateModule(module)\n server.reloadModule(module)\n }\n })\n },\n async handleHotUpdate({file, modules, server}) {\n if (!isAngularDemoFile(file)) {\n if (isCssAsset(file)) {\n return modules\n }\n\n if (file.endsWith(\"main.js\")) {\n const ids = [...hotUpdateDemoIds]\n server.ws.send({\n data: {\n demoInfo: ids.reduce(\n (acc: Record<string, AngularDemoInfo | undefined>, current) => {\n acc[current] = demoRegistry.get(current)\n return acc\n },\n {},\n ),\n },\n event: \"demo-bundle-updated\",\n type: \"custom\",\n })\n }\n\n return []\n }\n\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} Processing Angular demo change: ${chalk.cyan(file)}`,\n )\n\n const code = await readFile(file, \"utf-8\")\n const demoInfo = await parseAngularDemo(file, code)\n\n if (!demoInfo || !isAngularDemoEntrypoint(file)) {\n // might be an imported file\n const affectedDemos: AngularDemoInfo[] =\n await scanDemosForFileImport(file)\n\n if (affectedDemos.length > 0) {\n hotUpdateDemoIds = []\n for (const demo of affectedDemos) {\n hotUpdateDemoIds.push(demo.id)\n }\n }\n\n server.ws.send({\n data: {\n ids: [...hotUpdateDemoIds],\n },\n event: \"demo-bundle-updating\",\n type: \"custom\",\n })\n\n return\n }\n\n delete demoDimensionsCache[demoInfo.id]\n demoRegistry.set(demoInfo.id, demoInfo)\n hotUpdateDemoIds = [demoInfo.id]\n\n server.ws.send({\n data: {\n ids: [...hotUpdateDemoIds],\n },\n event: \"demo-bundle-updating\",\n type: \"custom\",\n })\n\n const mainModule = server.moduleGraph.getModuleById(VIRTUAL_MODULE_ID)\n if (mainModule) {\n server.moduleGraph.invalidateModule(mainModule)\n }\n\n const demoModule = server.moduleGraph.getModuleById(file)\n if (demoModule) {\n server.moduleGraph.invalidateModule(demoModule)\n }\n\n return []\n },\n async load(id) {\n if (id === VIRTUAL_MODULE_ID) {\n return generateRegistryModule()\n }\n },\n name: \"angular-demo-plugin\",\n resolveId(id) {\n if (id === \"virtual:angular-demo-registry\") {\n return VIRTUAL_MODULE_ID\n }\n },\n writeBundle() {\n console.log(\n `${chalk.blue.bold(LOG_PREFIX)} Successfully integrated ${chalk.green(demoRegistry.size)} component demos`,\n )\n },\n }\n\n async function collectAngularDemos() {\n if (demoRegistry.size) {\n logDev(\n `${chalk.magenta.bold(LOG_PREFIX)} Using cached ${chalk.cyanBright.bold(demoRegistry.size)} demos`,\n )\n return\n }\n\n const demoFiles = await glob(demoPattern)\n demoRegistry.clear()\n\n for (const filePath of demoFiles) {\n const code = await readFile(filePath, \"utf-8\")\n const demoInfo = await parseAngularDemo(filePath, code)\n if (demoInfo) {\n demoRegistry.set(demoInfo.id, demoInfo)\n }\n }\n }\n\n async function scanDemosForFileImport(\n file: string,\n ): Promise<AngularDemoInfo[]> {\n const affectedDemos: AngularDemoInfo[] = []\n\n for (const [demoId, demo] of demoRegistry.entries()) {\n if (demo.sourceCode.find((entry) => entry.filePath === file)) {\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} Reloading demo ${chalk.cyan(demoId)} due to imported file change: ${chalk.yellow(file)}`,\n )\n\n const code = await readFile(demo.filePath, \"utf-8\")\n const updatedDemo = await parseAngularDemo(demo.filePath, code)\n\n if (updatedDemo) {\n delete demoDimensionsCache[updatedDemo.id]\n demoRegistry.set(updatedDemo.id, updatedDemo)\n affectedDemos.push(updatedDemo)\n hotUpdateDemoIds.push(updatedDemo.id)\n }\n }\n }\n\n return affectedDemos\n }\n\n async function highlightCode(\n code: string,\n language: \"angular-ts\" | \"angular-html\" | \"css\" = \"angular-ts\",\n options: {\n onClassesDetected?: (detected: boolean) => void\n onResidualCss?: (rules: Map<string, string>) => void\n } = {},\n ): Promise<HighlightCodeResult> {\n const {onClassesDetected, onResidualCss} = options\n\n if (!highlighter) {\n return {full: code}\n }\n\n let previewCode: string | null = null\n\n const tailwindTransformers = []\n if (transformTailwindStyles && onResidualCss) {\n const transformer = await createShikiTailwindTransformer({\n onClassesDetected: (detected) => {\n onClassesDetected?.(detected)\n },\n onResidualCss,\n styleFormat: \"html\",\n styles: dedent`\n @layer theme, base, components, utilities;\n @import \"tailwindcss/theme.css\" layer(theme);\n @import \"tailwindcss/utilities.css\" layer(utilities);\n @import \"@qualcomm-ui/tailwind-plugin/qui-strict.css\";\n `,\n })\n tailwindTransformers.push(transformer)\n }\n\n try {\n const highlightedCode = highlighter.codeToHtml(code, {\n ...defaultShikiOptions,\n lang: language,\n transformers: [\n ...getShikiTransformers(),\n ...tailwindTransformers,\n transformerPreviewBlock({\n attributeName: \"data-preview\",\n onComplete: (extractedPreview) => {\n previewCode = extractedPreview\n },\n }),\n transformerCodeAttribute({\n attributeName: \"data-code\",\n }),\n {\n enforce: \"post\",\n name: \"shiki-transformer-trim\",\n preprocess(inner) {\n return inner.trim()\n },\n },\n ],\n })\n\n return {\n full: highlightedCode,\n preview: previewCode\n ? extractPreviewFromHighlightedHtml(highlightedCode)\n : null,\n }\n } catch (error) {\n console.warn(\n `${chalk.blue.bold(LOG_PREFIX)} Failed to highlight code with ${language} language:`,\n error,\n )\n return {full: code}\n }\n }\n\n async function extractRelativeImports(\n filePath: string,\n ): Promise<RelativeImport[]> {\n try {\n const content = await readFile(filePath, \"utf-8\")\n\n const sourceFile = ts.createSourceFile(\n filePath,\n content,\n ts.ScriptTarget.Latest,\n true,\n ts.ScriptKind.TS,\n )\n\n const relativeImports: RelativeImport[] = []\n\n function visit(node: ts.Node) {\n if (ts.isImportDeclaration(node)) {\n const moduleSpecifier = node.moduleSpecifier\n\n if (ts.isStringLiteral(moduleSpecifier)) {\n const source = moduleSpecifier.text\n\n if (isRelativeImport(source)) {\n const resolvedPath = resolveRelativeImport(source, filePath)\n relativeImports.push({resolvedPath, source})\n } else if (!isNodeBuiltin(source)) {\n const pathAliases = loadTsConfigPaths(filePath)\n\n if (isPathAliasImport(source, pathAliases)) {\n const resolvedPath = resolvePathAlias(source, pathAliases)\n if (resolvedPath) {\n relativeImports.push({resolvedPath, source})\n }\n }\n }\n }\n }\n\n ts.forEachChild(node, visit)\n }\n\n visit(sourceFile)\n\n return relativeImports\n } catch (error) {\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} ${chalk.yellowBright(\"Failed to extract imports from\")} ${chalk.cyan(filePath)}:`,\n error,\n )\n return []\n }\n }\n\n async function collectAllImports(\n filePath: string,\n visited = new Set<string>(),\n ): Promise<string[]> {\n if (visited.has(filePath)) {\n return []\n }\n\n visited.add(filePath)\n\n const directImports = await extractRelativeImports(filePath)\n\n for (const {resolvedPath} of directImports) {\n await collectAllImports(resolvedPath, visited)\n }\n\n return Array.from(visited).slice(1)\n }\n\n function stripImports(code: string, fileName: string): string[] {\n try {\n const sourceFile = ts.createSourceFile(\n fileName,\n code,\n ts.ScriptTarget.Latest,\n true,\n ts.ScriptKind.TS,\n )\n\n const importRanges: Array<{end: number; start: number}> = []\n\n function visit(node: ts.Node) {\n if (ts.isImportDeclaration(node)) {\n importRanges.push({\n end: node.getEnd(),\n start: node.getFullStart(),\n })\n }\n\n ts.forEachChild(node, visit)\n }\n\n visit(sourceFile)\n\n return importRanges.map((range) => {\n let endPos = range.end\n if (code[endPos] === \"\\n\") {\n endPos++\n }\n return code.slice(range.start, endPos).trim()\n })\n } catch (error) {\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} ${chalk.redBright(\"Failed to strip imports from\")} ${chalk.cyan(fileName)}:`,\n error,\n )\n return []\n }\n }\n\n async function parseAngularDemo(\n filePath: string,\n code: string,\n ): Promise<AngularDemoInfo | null> {\n try {\n const {\n componentClass,\n hasDefaultExport,\n isStandalone,\n selector,\n templateUrl,\n } = parseAngularComponentMeta(filePath, code)\n\n if (!componentClass || !selector) {\n return null\n }\n\n const demoId = componentClass\n const importPath = relative(process.cwd(), filePath).replace(/\\\\/g, \"/\")\n const fileName = basename(filePath)\n const importsWithoutStrip = stripImports(code, filePath)\n\n const sourceCode: SourceCodeData[] = []\n // Use Map for deduplication across all files in this demo\n const aggregatedRules = new Map<string, string>()\n\n const mainSourceEntry = await buildAngularSourceEntry({\n code,\n fileName,\n filePath,\n language: \"angular-ts\",\n })\n sourceCode.push(mainSourceEntry.sourceCodeData)\n if (mainSourceEntry.residualRules) {\n for (const [className, rule] of mainSourceEntry.residualRules) {\n aggregatedRules.set(className, rule)\n }\n }\n\n if (templateUrl) {\n const templateEntry = await maybeBuildTemplateSourceEntry(\n templateUrl,\n filePath,\n )\n if (templateEntry) {\n sourceCode.push(templateEntry.sourceCodeData)\n if (templateEntry.residualRules) {\n for (const [className, rule] of templateEntry.residualRules) {\n aggregatedRules.set(className, rule)\n }\n }\n }\n }\n\n const importedEntries = await buildImportedSourceEntries(filePath)\n for (const entry of importedEntries) {\n sourceCode.push(entry.sourceCodeData)\n if (entry.residualRules) {\n for (const [className, rule] of entry.residualRules) {\n aggregatedRules.set(className, rule)\n }\n }\n }\n\n // Convert aggregated rules to CSS string\n const aggregatedResidualCss =\n aggregatedRules.size > 0\n ? [...aggregatedRules.values()].join(\"\\n\\n\")\n : undefined\n\n if (aggregatedResidualCss) {\n const cssHighlighted = await highlightCode(aggregatedResidualCss, \"css\")\n sourceCode.push({\n fileName: \"styles.css\",\n highlighted: cssHighlighted,\n type: \"residual-css\",\n })\n }\n\n return {\n componentClass,\n filePath: importPath.startsWith(\".\") ? importPath : `./${importPath}`,\n hasDefaultExport,\n id: demoId,\n imports: importsWithoutStrip,\n initialHtml: initialHtml?.[demoId] || undefined,\n isStandalone,\n lastModified: Date.now(),\n selector,\n sourceCode,\n }\n } catch (error) {\n console.error(\n `${chalk.blue.bold(LOG_PREFIX)} Failed to parse Angular demo ${filePath}:`,\n error,\n )\n return null\n }\n }\n\n function parseAngularComponentMeta(\n filePath: string,\n source: string,\n ): {\n componentClass: string\n hasDefaultExport: boolean\n importsFromAst: string[]\n isStandalone: boolean\n selector: string\n templateUrl: string | null\n } {\n const sourceFile = ts.createSourceFile(\n filePath,\n source,\n ts.ScriptTarget.Latest,\n true,\n ts.ScriptKind.TS,\n )\n\n let componentClass = \"\"\n let selector = \"\"\n let isStandalone = true\n let templateUrl: string | null = null\n let hasDefaultExport = false\n const importsFromAst: string[] = []\n\n function visit(node: ts.Node) {\n if (ts.isImportDeclaration(node)) {\n importsFromAst.push(node.getFullText(sourceFile).trim())\n }\n\n if (ts.isClassDeclaration(node)) {\n const decorators = node.modifiers?.filter(ts.isDecorator)\n const componentDecorator = decorators?.find((decorator) => {\n if (!ts.isCallExpression(decorator.expression)) {\n return false\n }\n const expression = decorator.expression.expression\n return ts.isIdentifier(expression) && expression.text === \"Component\"\n })\n\n if (componentDecorator && node.name) {\n componentClass = node.name.text\n\n if (\n ts.isCallExpression(componentDecorator.expression) &&\n componentDecorator.expression.arguments[0] &&\n ts.isObjectLiteralExpression(\n componentDecorator.expression.arguments[0],\n )\n ) {\n const properties =\n componentDecorator.expression.arguments[0].properties\n\n const selectorProp = properties.find(\n (prop) =>\n ts.isPropertyAssignment(prop) &&\n ts.isIdentifier(prop.name) &&\n prop.name.text === \"selector\",\n ) as ts.PropertyAssignment | undefined\n\n if (selectorProp && ts.isStringLiteral(selectorProp.initializer)) {\n selector = selectorProp.initializer.text\n }\n\n const templateUrlProp = properties.find(\n (prop) =>\n ts.isPropertyAssignment(prop) &&\n ts.isIdentifier(prop.name) &&\n prop.name.text === \"templateUrl\",\n ) as ts.PropertyAssignment | undefined\n\n if (templateUrlProp) {\n const init = templateUrlProp.initializer\n if (ts.isStringLiteral(init)) {\n templateUrl = init.text\n } else if (ts.isNoSubstitutionTemplateLiteral(init)) {\n templateUrl = init.text\n }\n }\n\n const standaloneProp = properties.find(\n (prop) =>\n ts.isPropertyAssignment(prop) &&\n ts.isIdentifier(prop.name) &&\n prop.name.text === \"standalone\",\n ) as ts.PropertyAssignment | undefined\n\n if (\n standaloneProp &&\n standaloneProp.initializer.kind === ts.SyntaxKind.FalseKeyword\n ) {\n isStandalone = false\n }\n }\n }\n }\n\n if (ts.isExportAssignment(node) && !node.isExportEquals) {\n hasDefaultExport = true\n }\n\n ts.forEachChild(node, visit)\n }\n\n visit(sourceFile)\n\n return {\n componentClass,\n hasDefaultExport,\n importsFromAst,\n isStandalone,\n selector,\n templateUrl,\n }\n }\n\n interface BuildAngularSourceEntryParams {\n code: string\n fileName: string\n filePath: string\n language: \"angular-ts\" | \"angular-html\"\n }\n\n interface ExtractedSourceCode {\n residualRules?: Map<string, string>\n sourceCodeData: SourceCodeData\n }\n\n async function buildAngularSourceEntry(\n params: BuildAngularSourceEntryParams,\n ): Promise<ExtractedSourceCode> {\n const {code, fileName, filePath, language} = params\n\n const baseResult = await highlightCode(code, language)\n\n let inlineResult: HighlightCodeResult | undefined\n let classesDetected = false\n let residualRules: Map<string, string> | undefined\n\n if (transformTailwindStyles) {\n inlineResult = await highlightCode(code, language, {\n onClassesDetected: (detected) => {\n classesDetected = detected\n },\n onResidualCss: (rules) => {\n residualRules = rules\n },\n })\n }\n\n return {\n residualRules,\n sourceCodeData: {\n fileName,\n filePath,\n highlighted: {\n full: baseResult.full,\n preview: baseResult.preview,\n },\n highlightedInline:\n classesDetected && inlineResult\n ? {\n full: inlineResult.full,\n preview: inlineResult.preview,\n }\n : undefined,\n type: \"file\",\n },\n }\n }\n\n async function maybeBuildTemplateSourceEntry(\n templateUrl: string,\n fromFilePath: string,\n ): Promise<ExtractedSourceCode | null> {\n const templatePath = resolveTemplateFile(templateUrl, fromFilePath)\n if (!existsSync(templatePath)) {\n return null\n }\n\n try {\n const templateCode = await readFile(templatePath, \"utf-8\")\n\n return buildAngularSourceEntry({\n code: templateCode,\n fileName: basename(templatePath),\n filePath: templatePath,\n language: \"angular-html\",\n })\n } catch (error) {\n console.log(\n `${chalk.blue.bold(LOG_PREFIX)} ${chalk.redBright(\"Failed to read template file:\")} ${chalk.cyan(templatePath)}`,\n error,\n )\n return null\n }\n }\n\n async function buildImportedSourceEntries(\n fromFilePath: string,\n ): Promise<ExtractedSourceCode[]> {\n const entries: ExtractedSourceCode[] = []\n const relativeImports = await collectAllImports(fromFilePath)\n\n for (const resolvedPath of relativeImports) {\n try {\n const importedCode = await readFile(resolvedPath, \"utf-8\")\n\n const entry = await buildAngularSourceEntry({\n code: importedCode,\n fileName: basename(resolvedPath),\n filePath: resolvedPath,\n language: \"angular-ts\",\n })\n\n entries.push(entry)\n } catch (error) {\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} ${chalk.yellowBright(\"Failed to process relative import:\")} ${chalk.cyan(resolvedPath)}`,\n )\n }\n }\n\n return entries\n }\n\n function generateRegistryModule(): string {\n const demos = Array.from(demoRegistry.values())\n\n return `// Auto-generated Angular demo registry\nexport const ANGULAR_DEMOS = {\n${demos\n .map(\n (demo) =>\n ` \"${demo.id}\": ${JSON.stringify(\n {\n componentClass: demo.componentClass,\n dimensions: demoDimensionsCache[demo.id],\n filePath: demo.filePath,\n hasDefaultExport: demo.hasDefaultExport,\n id: demo.id,\n imports: demo.imports,\n initialHtml: demo.initialHtml,\n isStandalone: demo.isStandalone,\n lastModified: demo.lastModified,\n selector: demo.selector,\n sourceCode: demo.sourceCode,\n },\n null,\n 4,\n )}`,\n )\n .join(\",\\n\")}\n}\n\nexport function getAngularDemoInfo(demoId) {\n return ANGULAR_DEMOS[demoId] || null\n}`\n }\n\n function isAngularDemoFile(filePath: string): boolean {\n return (\n filePath.includes(\"/demos/\") &&\n (filePath.endsWith(\".ts\") || filePath.endsWith(\"html\"))\n )\n }\n\n function isAngularDemoEntrypoint(filePath: string): boolean {\n return filePath.endsWith(\"-demo.ts\") || filePath.endsWith(\"-demo.html\")\n }\n\n function isCssAsset(filePath: string) {\n return filePath.endsWith(\".css\")\n }\n\n function isRelativeImport(source: string): boolean {\n return source.startsWith(\"./\") || source.startsWith(\"../\")\n }\n\n function isNodeBuiltin(source: string): boolean {\n const NODE_BUILTINS = [\n \"assert\",\n \"buffer\",\n \"child_process\",\n \"cluster\",\n \"crypto\",\n \"dgram\",\n \"dns\",\n \"domain\",\n \"events\",\n \"fs\",\n \"http\",\n \"https\",\n \"net\",\n \"os\",\n \"path\",\n \"punycode\",\n \"querystring\",\n \"readline\",\n \"stream\",\n \"string_decoder\",\n \"timers\",\n \"tls\",\n \"tty\",\n \"url\",\n \"util\",\n \"v8\",\n \"vm\",\n \"zlib\",\n ]\n\n return source.startsWith(\"node:\") || NODE_BUILTINS.includes(source)\n }\n\n function resolveRelativeImport(source: string, fromFile: string): string {\n const fromDir = dirname(fromFile)\n const resolved = resolve(fromDir, source)\n const extensions = [\".ts\", \".js\"]\n\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\n function 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\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\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\n const pattern = new RegExp(\n `^${alias\n .replace(\"*\", \"(.*)\")\n .replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(\"\\\\(\\\\*\\\\)\", \"(.*)\")}$`,\n )\n\n const replacement = resolve(\n resolvedBaseUrl,\n target.replace(\"*\", \"$1\"),\n )\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\n currentDir = dirname(currentDir)\n }\n\n return pathAliases\n }\n\n async function setupAngularWatcher() {\n watcher = watch(routesDir, {\n ignoreInitial: true,\n persistent: true,\n })\n\n watcher.on(\"ready\", () => {\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} Registered ${chalk.green(demoRegistry.size)} demo files. Watching for file changes...`,\n )\n })\n\n watcher.on(\"add\", async (filePath: string) => {\n const fileStats = await stat(filePath).catch(() => undefined)\n if (!fileStats || fileStats.size === 0) {\n console.debug(\"Failed to read file stats\", filePath)\n return\n }\n\n if (isAngularDemoFile(filePath)) {\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} New Angular demo: ${chalk.green(filePath)}`,\n )\n await handleAngularDemoUpdate(filePath)\n triggerRegistryUpdate()\n }\n })\n\n watcher.on(\"unlink\", (filePath: string) => {\n if (isAngularDemoFile(filePath)) {\n const demoEntry = Array.from(demoRegistry.entries()).find(\n ([, info]) => info.filePath === filePath,\n )\n\n if (demoEntry) {\n const [demoId] = demoEntry\n demoRegistry.delete(demoId)\n\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} Removed demo: ${chalk.red(demoId)}`,\n )\n\n triggerRegistryUpdate()\n }\n }\n })\n }\n\n async function handleAngularDemoUpdate(filePath: string) {\n const code = await readFile(filePath, \"utf-8\")\n const demoInfo = await parseAngularDemo(filePath, code)\n\n if (demoInfo) {\n demoRegistry.set(demoInfo.id, demoInfo)\n }\n }\n\n function triggerRegistryUpdate() {\n if (!devServer) {\n return\n }\n\n const mainModule = devServer.moduleGraph.getModuleById(VIRTUAL_MODULE_ID)\n if (mainModule) {\n devServer.moduleGraph.invalidateModule(mainModule)\n mainModule.lastHMRTimestamp = Date.now()\n devServer.reloadModule(mainModule)\n }\n }\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\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\n const pattern = new RegExp(\n `^${alias\n .replace(\"*\", \"(.*)\")\n .replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(\"\\\\(\\\\*\\\\)\", \"(.*)\")}$`,\n )\n\n const replacement = resolve(\n resolvedBaseUrl,\n target.replace(\"*\", \"$1\"),\n )\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\n if (!resolvedExtends.endsWith(\".json\")) {\n resolvedExtends += \".json\"\n }\n\n if (existsSync(resolvedExtends)) {\n const extendedAliases = loadTsConfigPathsFromFile(resolvedExtends)\n pathAliases.push(...extendedAliases)\n }\n }\n } catch {\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\", \".js\"]\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\n return null\n}\n\nfunction resolveTemplateFile(templateUrl: string, fromFile: string): string {\n const fromDir = dirname(fromFile)\n const resolved = resolve(fromDir, templateUrl)\n\n if (existsSync(resolved)) {\n return resolved\n }\n\n if (!resolved.endsWith(\".html\")) {\n const withHtml = `${resolved}.html`\n if (existsSync(withHtml)) {\n return withHtml\n }\n }\n\n return resolved\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 {PageDocProps, SiteData} from \"@qualcomm-ui/mdx-common\"\nimport type {QuiPropTypes} from \"@qualcomm-ui/typedoc-common\"\n\nimport {\n type CompiledMdxFile,\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 get siteData(): SiteData {\n return {\n navItems: state.indexer.navItems,\n pageDocProps: state.indexer.pageDocProps as unknown as PageDocProps,\n pageMap: state.indexer.pageMap,\n searchIndex: state.indexer.searchIndex,\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): CompiledMdxFile[] {\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 const compiledMdxFiles = 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 return compiledMdxFiles\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 onComplete: () => {\n this.servers.forEach((server) =>\n server.ws.send({type: \"full-reload\"}),\n )\n },\n })\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 apply(config, env) {\n return (\n (env.mode === \"development\" && env.command === \"serve\") ||\n (env.mode === \"production\" && env.command === \"build\")\n )\n },\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 if (updateFile.endsWith(\".css\")) {\n return modules\n }\n const file = fixPath(updateFile)\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 if (updateFile.endsWith(\".mdx\")) {\n const files = state.buildIndex(true)\n\n const moduleByFile = server.moduleGraph.getModulesByFile(updateFile)\n if (!moduleByFile?.size) {\n console.debug(\"no module found for file, returning\", updateFile)\n return []\n }\n\n const virtualModule =\n server.moduleGraph.getModuleById(VIRTUAL_MODULE_ID)\n if (virtualModule) {\n // invalidate the module so that it gets re-evaluated on next refresh\n server.moduleGraph.invalidateModule(virtualModule)\n\n // Send the updated site data to the site so that it has the latest\n // state.\n server.ws.send({\n data: state.siteData,\n event: \"qui-docs-plugin:refresh-site-data\",\n type: \"custom\",\n })\n }\n if (files.some((file) => file.metadata.changed.frontmatter)) {\n console.debug(\n \"Frontmatter changed, reloading plugin to reflect changes in the page configuration\",\n )\n if (virtualModule) {\n server.moduleGraph.invalidateModule(virtualModule)\n }\n server.ws.send({type: \"full-reload\"})\n return []\n }\n return virtualModule ? [virtualModule] : []\n }\n }\n return []\n },\n load: (id): string | undefined => {\n if (id === VIRTUAL_MODULE_ID) {\n return `export const siteData = ${JSON.stringify(state.siteData)}`\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 {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 KnowledgeConfig,\n KnowledgeExtraFile,\n KnowledgeIntegrationConfig,\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\nconst knowledgeExtraFileSchema = implement<KnowledgeExtraFile>().with({\n contents: z.string(),\n id: z.string(),\n title: z.string(),\n})\n\nconst knowledgeIntegrationSchema = implement<KnowledgeIntegrationConfig>().with(\n {\n baseUrl: z.string().optional(),\n description: z.string().optional(),\n exclude: z.array(z.string()).optional(),\n extraFiles: z.array(knowledgeExtraFileSchema).optional(),\n metadata: z.record(z.string(), z.string()).optional(),\n name: z.string().optional(),\n outputMode: z\n .union([z.literal(\"per-page\"), z.literal(\"aggregated\")])\n .optional(),\n outputPath: z.string().optional(),\n pageTitlePrefix: z.string().optional(),\n },\n)\n\nconst knowledgeConfigSchema = implement<KnowledgeConfig>().with({\n global: knowledgeIntegrationSchema.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 knowledge: knowledgeConfigSchema.optional(),\n navConfig: z.array(z.union([routeMetaSchema, navMetaSchema])).optional(),\n pageDirectory: z.string().optional(),\n pageTimestampMetadata: z\n .union([\n z.literal(\"off\"),\n z.literal(\"timestamp\"),\n z.literal(\"user-and-timestamp\"),\n ])\n .optional(),\n routingStrategy: z.union([z.literal(\"vite-generouted\"), z.any()]).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.ZodNullable<z.ZodOptional<z.ZodType<Model[key]>>>\n : z.ZodOptional<z.ZodType<Model[key]>>\n : null extends Model[key]\n ? z.ZodNullable<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 description: z.string().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 updatedBy: z.string().optional(),\n updatedOn: z.string().optional(),\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 type CompiledMdxFile,\n type CompiledMdxFileMetadata,\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 this.config.pageTimestampMetadata,\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 description: frontmatter.description,\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 updatedBy: frontmatter.updatedBy,\n updatedOn: frontmatter.updatedOn,\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): CompiledMdxFile {\n const {cached, fileContents, frontmatter} =\n this.fileCache.readFile(filePath)\n\n const metadata: CompiledMdxFileMetadata = {\n changed: {},\n filePath,\n }\n\n let previousPage: IndexedPage | undefined = undefined\n\n if (!cached) {\n const previousData = this.fileCache.readCache(filePath)\n if (previousData) {\n const cachedFm = JSON.stringify(previousData.frontmatter)\n const currentFm = JSON.stringify(frontmatter)\n previousPage = previousData.page\n if (cachedFm !== currentFm) {\n metadata.changed.frontmatter = true\n }\n }\n }\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 {metadata, pageSections: [defaultSection]}\n }\n\n const {sections, toc} = indexedPage\n\n if (previousPage) {\n for (let i = 0; i < toc.length; i++) {\n const previousHeading = previousPage.toc[i]\n const currentHeading = toc[i]\n if (previousHeading?.id !== currentHeading.id) {\n metadata.changed.toc = true\n break\n }\n }\n }\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 if (!cached) {\n this.fileCache.updateCache(filePath, fileContents, {\n frontmatter,\n page: indexedPage,\n pageDocProps: docProps,\n pageDocPropSections: docPropSections,\n })\n }\n\n // omit entries from pages that are explicitly omitted from the index.\n if (frontmatter.hideFromSearch) {\n return {metadata, pageSections: [defaultSection]}\n }\n\n if (!sections.length && !docPropSections.length) {\n return {metadata, pageSections: [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 {metadata, pageSections: 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(\n inputFileGlob: string[],\n logWarnings: boolean = true,\n ): CompiledMdxFile[] {\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 compiledFiles = mdxFileGlob.map((file) => this.compileMdxFile(file))\n\n const mdxIndex = compiledFiles\n .map((fileData) => fileData.pageSections)\n .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 return compiledFiles\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\"\nimport {extractNamesFromAttribute} from \"../mdx-utils\"\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 /**\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 ? extractNamesFromAttribute(omitFromAttr)\n : undefined\n\n if (nameAttr) {\n const names = 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 type {MdxJsxAttribute} from \"mdast-util-mdx-jsx\"\n\nexport function 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 (element?.type === \"Literal\" && typeof element.value === \"string\") {\n names.push(element.value)\n }\n }\n return names\n }\n\n // Handle single string expression\n if (expression.type === \"Literal\" && typeof expression.value === \"string\") {\n return [expression.value]\n }\n }\n\n return []\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 {execSync} from \"node:child_process\"\nimport {createHash} from \"node:crypto\"\nimport {readFileSync} from \"node:fs\"\nimport {relative} 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 {PageFrontmatter} from \"@qualcomm-ui/mdx-common\"\nimport type {QuiPropTypes} from \"@qualcomm-ui/typedoc-common\"\n\nimport type {PageTimestampMetadataMode} from \"../../../types\"\nimport {frontmatterSchema} from \"../../utils\"\n\nimport type {IndexedPage, IndexedSection} from \"./markdown.types\"\n\nexport interface GitMetadata {\n updatedBy?: string\n updatedOn?: string\n}\n\nfunction getRepoRoot(): string {\n return execSync(\"git rev-parse --show-toplevel\", {\n encoding: \"utf-8\",\n }).trim()\n}\n\n/**\n * Gets the last git commit metadata for a file.\n * Returns undefined values if the file is not tracked by git or if git is\n * unavailable.\n */\nexport function getGitMetadata(\n filePath: string,\n mode: PageTimestampMetadataMode,\n): GitMetadata {\n if (mode === \"off\") {\n return {}\n }\n\n try {\n const repoRoot = getRepoRoot()\n const relativePath = relative(repoRoot, filePath)\n const format = mode === \"user-and-timestamp\" ? \"%cI%n%aN\" : \"%cI\"\n const result = execSync(\n `git log -1 --format=${format} -- \"${relativePath}\"`,\n {\n encoding: \"utf-8\",\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n },\n ).trim()\n\n if (!result) {\n return {}\n }\n\n if (mode === \"user-and-timestamp\") {\n const [updatedOn, updatedBy] = result.split(\"\\n\")\n return {updatedBy, updatedOn}\n }\n\n return {updatedOn: result}\n } catch {\n return {}\n }\n}\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(\n public enabled: boolean,\n public pageTimestampMetadata: PageTimestampMetadataMode = \"off\",\n ) {}\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 readCache(filePath: string): PageCache | null {\n return this.mdxCache[filePath] || null\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 // In dev mode, only fetch git metadata for new files (not in cache).\n // For file updates, reuse cached git metadata to avoid repeated git calls.\n // In production mode, always fetch fresh git metadata.\n const existingCache = this.mdxCache[filepath]\n const shouldFetchGitMetadata = !this.enabled || !existingCache\n\n if (shouldFetchGitMetadata) {\n const gitMetadata = getGitMetadata(filepath, this.pageTimestampMetadata)\n if (!frontmatter.updatedOn && gitMetadata.updatedOn) {\n frontmatter.updatedOn = gitMetadata.updatedOn\n }\n if (!frontmatter.updatedBy && gitMetadata.updatedBy) {\n frontmatter.updatedBy = gitMetadata.updatedBy\n }\n } else if (!cached && existingCache) {\n // Dev mode cache miss (file updated) - reuse git metadata from previous cache\n if (!frontmatter.updatedOn && existingCache.frontmatter.updatedOn) {\n frontmatter.updatedOn = existingCache.frontmatter.updatedOn\n }\n if (!frontmatter.updatedBy && existingCache.frontmatter.updatedBy) {\n frontmatter.updatedBy = existingCache.frontmatter.updatedBy\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 {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\"\nimport {capitalCase} from \"@qualcomm-ui/utils/change-case\"\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 {join} from \"node:path\"\n\nimport {capitalCase} from \"@qualcomm-ui/utils/change-case\"\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 {\n transformerNotationDiff,\n transformerNotationErrorLevel,\n transformerNotationFocus,\n transformerNotationHighlight,\n transformerNotationWordHighlight,\n transformerRemoveNotationEscape,\n transformerRenderIndentGuides,\n} from \"@shikijs/transformers\"\nimport {merge} from \"lodash-es\"\nimport type {ShikiTransformer} from \"shiki\"\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 {\n remarkAlerts,\n remarkCodeTabs,\n remarkFrontmatterDescription,\n remarkSpoilers,\n} from \"./remark\"\nimport {transformerCodeAttribute, transformerNotationHidden} from \"./shiki\"\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\nexport function getShikiTransformers(): ShikiTransformer[] {\n return [\n transformerNotationDiff(),\n transformerNotationFocus(),\n transformerNotationHighlight(),\n transformerNotationWordHighlight(),\n transformerNotationErrorLevel(),\n transformerNotationHidden(),\n transformerRenderIndentGuides(),\n transformerRemoveNotationEscape(),\n ]\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, {enforce: \"pre\"}],\n [\n rehypeSlug,\n {allowedHeadings: config.headings} satisfies RehypeSlugOptions,\n ],\n rehypeSectionize,\n [\n rehypeShiki,\n merge(\n {\n defaultColor: \"light-dark()\",\n themes: {\n dark: quiCustomDarkTheme,\n light: \"github-light-high-contrast\",\n },\n transformers: [...getShikiTransformers(), transformerCodeAttribute()],\n } satisfies RehypeShikiOptions,\n options.rehypeShikiOptions,\n ),\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 remarkFrontmatterDescription,\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 *\n * @example\n * ```angular-html tabs=\"demo\" label=\"HTML\"\n * <div class=\"w-72\" q-text-input [invalid]=\"!value()\" [(ngModel)]=\"value\">\n * <label q-text-input-label>Label</label>\n * <input placeholder=\"Enter a value\" q-text-input-input />\n * <div q-text-input-error-text>You must enter a value</div>\n * </div>\n * ```\n *\n * ```angular-ts tabs=\"demo\" label=\"TS\"\n * @Component()\n * export class DemoComponent {\n * readonly value = signal(\"\")\n * }\n * ```\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 {Parent, Root} from \"mdast\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\ninterface MdxFlowExpression {\n type: \"mdxFlowExpression\"\n value: string\n}\n\n/**\n * Wraps standalone `{frontmatter.description}` expressions in a\n * `<p class=\"mdx\">` element for styling purposes.\n */\nexport const remarkFrontmatterDescription: Plugin<[], Root> = () => {\n return (tree) => {\n visit(\n tree,\n \"mdxFlowExpression\",\n (\n node: MdxFlowExpression,\n index: number | undefined,\n parent: Parent | undefined,\n ) => {\n if (\n node.value.trim() !== \"frontmatter.description\" ||\n index === undefined ||\n !parent\n ) {\n return\n }\n\n const wrappedNode = {\n attributes: [\n {\n name: \"className\",\n type: \"mdxJsxAttribute\",\n value: \"mdx\",\n },\n ],\n children: [node],\n name: \"p\",\n type: \"mdxJsxFlowElement\",\n }\n\n parent.children[index] = wrappedNode as any\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\nexport function removeCodeAnnotations(code: string): string {\n const hideAnnotationRegex = /\\/\\/\\s*\\[!code\\s+hide(?::\\d+)?\\]/\n const lineAnnotationRegex = /\\/\\/\\s*\\[!code\\s*(?:\\S.*)?\\]/\n const jsxBlockAnnotationRegex = /\\{\\s*\\/\\*\\s*\\[!code(?:\\s+\\S+)?\\]\\s*\\*\\/\\s*\\}/\n const htmlAnnotationRegex = /<!--\\s*\\[!code(?:\\s+\\S+)?\\]\\s*-->/\n const blockAnnotationRegex = /\\/\\*\\s*\\[!code(?:\\s+\\S+)?\\]\\s*\\*\\/\\s*/\n const inlineIncrementRegex = /(?:\\/\\/\\s*)?\\[!code \\+\\+\\]/\n\n function stripAnnotations(line: string): {\n hasHideAnnotation: boolean\n processed: string\n touched: boolean\n } {\n let processed = line\n let touched = false\n const hasHideAnnotation = hideAnnotationRegex.test(line)\n\n const patterns = [\n inlineIncrementRegex,\n jsxBlockAnnotationRegex,\n htmlAnnotationRegex,\n blockAnnotationRegex,\n lineAnnotationRegex,\n ]\n\n for (const pattern of patterns) {\n const next = processed.replace(pattern, \"\")\n if (next !== processed) {\n touched = true\n processed = next\n }\n }\n\n return {hasHideAnnotation, processed, touched}\n }\n\n return code\n .split(\"\\n\")\n .map(stripAnnotations)\n .filter(({hasHideAnnotation, processed, touched}) => {\n if (hasHideAnnotation) {\n return false\n }\n\n const processedIsBlank = !processed.trim()\n if (touched && processedIsBlank) {\n return false\n }\n\n return true\n })\n .map(({processed}) => processed)\n .join(\"\\n\")\n}\n\nexport function extractPreviewFromHighlightedHtml(\n highlightedHtml: string,\n): string | null {\n const preMatch = highlightedHtml.match(/<pre((?:\\s+[\\w-]+=\"[^\"]*\")*)>/)\n const codeMatch = highlightedHtml.match(/<code([^>]*)>(.*?)<\\/code>/s)\n\n if (!preMatch || !codeMatch) {\n return null\n }\n const codeContent = codeMatch[2]\n const parts = codeContent.split(/<span class=\"line/)\n const previewLineParts = parts\n .slice(1)\n .filter((part) => part.includes('data-preview-line=\"true\"'))\n\n // strip indentation\n const indents = previewLineParts.map((part) => {\n const indentMatches =\n part.match(/<span class=\"indent\">(.+?)<\\/span>/g) || []\n let total = 0\n for (const match of indentMatches) {\n const content = match.match(/<span class=\"indent\">(.+?)<\\/span>/)\n if (content) {\n total += content[1].length\n } else {\n break\n }\n }\n return total\n })\n\n const minIndent = Math.min(...indents.filter((n) => n > 0))\n const previewLines = previewLineParts.map((part) => {\n let processed = `<span class=\"line${part}`\n let remaining = minIndent\n while (remaining > 0 && processed.includes('<span class=\"indent\">')) {\n const before = processed\n processed = processed.replace(\n /<span class=\"indent\">(.+?)<\\/span>/,\n (match, spaces) => {\n if (spaces.length <= remaining) {\n remaining -= spaces.length\n return \"\"\n } else {\n const kept = spaces.substring(remaining)\n remaining = 0\n return `<span class=\"indent\">${kept}</span>`\n }\n },\n )\n if (before === processed) {\n break\n }\n }\n return processed\n })\n return `<pre${preMatch[1]}><code${codeMatch[1]}>${previewLines.join(\"\")}</code></pre>`\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {ShikiTransformer} from \"shiki\"\n\nimport {removeCodeAnnotations} from \"./utils\"\n\nexport interface TransformerCodeAttributeOptions {\n /**\n * The name of the attribute to add to the pre element. Supply as `null` to\n * disable.\n *\n * @default 'data-code'\n */\n attributeName?: string | null\n\n /**\n * Custom formatter for the source code.\n */\n formatter?: (code: string) => string\n\n /**\n * Callback fired when file processing is complete.\n */\n onComplete?: (codeWithoutSnippets: string) => void\n}\n\n/**\n * Adds a `data-code` attribute to the `<pre>` element with the code contents,\n * removing any code annotations and unused lines from transformers like\n * `transformerNotationDiff`.\n */\nexport function transformerCodeAttribute(\n opts: TransformerCodeAttributeOptions = {attributeName: \"data-code\"},\n): ShikiTransformer {\n return {\n enforce: \"post\",\n name: \"shiki-transformer-code-attribute\",\n pre(node) {\n const strippedSource = removeCodeAnnotations(this.source)\n const formattedSource = opts.formatter?.(strippedSource) ?? strippedSource\n if (opts.attributeName !== null) {\n node.properties[opts.attributeName ?? \"data-code\"] = formattedSource\n }\n opts.onComplete?.(formattedSource)\n },\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {ShikiTransformer} from \"shiki\"\n\n/**\n * Use `[!code hide]` notation in code to mark lines as hidden.\n */\nexport function transformerNotationHidden(): ShikiTransformer {\n return {\n name: \"shiki-transformer-notation-hidden\",\n preprocess(code) {\n const lines = code.split(\"\\n\")\n const resultLines: string[] = []\n let hideNextCount = 0\n\n for (const rawLine of lines) {\n const line = rawLine\n const match = line.match(/\\[!code\\s+hide(?::(\\d+))?\\]/)\n\n if (match) {\n const before = line.slice(0, match.index ?? 0)\n const after = line.slice((match.index ?? 0) + match[0].length)\n\n const count = match[1] ? Number(match[1]) : 1\n const validCount = Number.isFinite(count) && count > 0 ? count : 0\n\n const beforeIsOnlyCommentOrWhitespace =\n before.trim() === \"\" || /^[\\s/]*$/.test(before)\n const afterIsEmpty = after.trim() === \"\"\n\n const markerIsStandalone =\n beforeIsOnlyCommentOrWhitespace && afterIsEmpty\n\n if (markerIsStandalone) {\n hideNextCount += validCount\n continue\n }\n\n // inline marker \u2192 hide this line only\n continue\n }\n\n if (hideNextCount > 0) {\n hideNextCount -= 1\n continue\n }\n\n resultLines.push(line)\n }\n\n return resultLines.join(\"\\n\").trim()\n },\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {ShikiTransformer} from \"shiki\"\n\nimport {dedent} from \"@qualcomm-ui/utils/dedent\"\n\nimport {removeCodeAnnotations} from \"./utils\"\n\nexport type PreviewDisplayMode = \"only-preview\" | \"full-code\"\n\nexport interface PreviewBlockTransformerOptions {\n /**\n * The name of the attribute to add to the pre element. Supply as `null` to\n * disable.\n *\n * @default 'data-preview'\n */\n attributeName?: string | null\n\n /**\n * @option 'full-code': keep the full code (with preview markers removed) as the rendered snippet.\n * @option 'preview-only': render only the extracted preview block as the snippet\n *\n * In all cases the preview block is extracted and attached to `data-preview`.\n *\n * @default 'full-code'\n */\n displayMode?: PreviewDisplayMode\n\n /**\n * Callback fired when file processing is complete.\n */\n onComplete?: (extractedPreview: string | null) => void\n}\n\nexport function 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\nexport function transformerPreviewBlock(\n options: PreviewBlockTransformerOptions = {\n displayMode: \"full-code\",\n },\n): ShikiTransformer {\n let previewContent: string | null = null\n let previewStartLine = -1\n let previewEndLine = -1\n let currentLine = 0\n\n return {\n enforce: \"post\",\n line(node) {\n if (currentLine >= previewStartLine && currentLine <= previewEndLine) {\n node.properties[\"data-preview-line\"] = \"true\"\n }\n currentLine++\n },\n name: \"transformer-preview-block\",\n pre(node) {\n const content = previewContent\n ? removeCodeAnnotations(previewContent)\n : null\n if (content && options.attributeName != null) {\n node.properties[options.attributeName] = content\n }\n options.onComplete?.(content || null)\n },\n preprocess(code) {\n previewContent = null\n currentLine = 0\n previewStartLine = -1\n previewEndLine = -1\n\n const lines = code.split(\"\\n\")\n const resultLines: string[] = []\n const previewLines: string[] = []\n let inPreview = false\n let foundPreview = false\n let outputLineIndex = 0\n\n for (const line of lines) {\n const trimmed = line.trim()\n if (isPreviewLine(trimmed)) {\n if (!inPreview) {\n inPreview = true\n foundPreview = true\n previewStartLine = outputLineIndex\n } else {\n inPreview = false\n previewEndLine = outputLineIndex - 1\n }\n continue\n }\n resultLines.push(line)\n if (inPreview) {\n previewLines.push(line)\n }\n outputLineIndex++\n }\n\n if (foundPreview) {\n previewContent = dedent(previewLines.join(\"\\n\").trim())\n if (options.displayMode === \"only-preview\") {\n return previewContent\n }\n }\n return resultLines.join(\"\\n\").trim()\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, Root, Text} from \"hast\"\nimport {fromHtml} from \"hast-util-from-html\"\nimport {toHtml} from \"hast-util-to-html\"\nimport {readFile} from \"node:fs/promises\"\nimport postcss, {type Rule} from \"postcss\"\nimport selectorParser from \"postcss-selector-parser\"\nimport type {ShikiTransformer} from \"shiki\"\nimport {compile} from \"tailwindcss\"\nimport {visit} from \"unist-util-visit\"\n\nimport {camelCase} from \"@qualcomm-ui/utils/change-case\"\n\ndeclare const createRequire: NodeRequire\n\nasync function loadStylesheetContent(id: string): Promise<string> {\n const resolveId = id === \"tailwindcss\" ? \"tailwindcss/index.css\" : id\n\n let resolvedPath: string\n if (typeof createRequire !== \"undefined\") {\n resolvedPath = createRequire(import.meta.url).resolve(resolveId)\n } else {\n const createRequire = await import(\"node:module\").then(\n (module) => module.createRequire,\n )\n resolvedPath = createRequire(import.meta.url).resolve(resolveId)\n }\n return readFile(resolvedPath, \"utf-8\")\n}\n\nfunction getClassValue(node: Element): string | null {\n const val = node.properties?.className ?? node.properties?.class\n if (!val) {\n return null\n }\n return Array.isArray(val) ? val.join(\" \") : String(val)\n}\n\n/**\n * Extract class names from the text content of a HAST tree.\n * Looks for string literals that could be Tailwind class names.\n */\nexport function extractClassesFromHast(tree: Root): string[] {\n const classes = new Set<string>()\n const stringLiteralPattern = /[\"'`]([^\"'`]+)[\"'`]/g\n\n visit(tree, \"text\", (node: Text) => {\n const text = node.value\n let match\n while ((match = stringLiteralPattern.exec(text)) !== null) {\n const content = match[1]\n const tokens = content.split(/\\s+/).filter(Boolean)\n for (const token of tokens) {\n classes.add(token)\n }\n }\n })\n\n return [...classes]\n}\n\nexport function extractClasses(source: string): string[] {\n const tree = fromHtml(source, {fragment: true})\n const classes = new Set<string>()\n\n visit(tree, \"element\", (node: Element) => {\n const value = getClassValue(node)\n if (value) {\n classes.add(value)\n }\n })\n\n return classes\n .values()\n .toArray()\n .map((value) => value.split(\" \"))\n .flat()\n}\n\n/**\n * Create a fresh Tailwind compiler for each transformation.\n * Note: Tailwind v4's compiler.build() is incremental and accumulates\n * all candidates across calls. We must create a fresh compiler each time\n * to avoid CSS from one demo leaking into another.\n */\nasync function createCompiler(styles: string) {\n return compile(styles, {\n loadStylesheet: async (id: string, base: string) => {\n const content = await loadStylesheetContent(id)\n return {\n base,\n content,\n path: `virtual:${id}`,\n }\n },\n })\n}\n\n/**\n * Extract CSS custom property definitions from compiled CSS.\n * Looks in :root and :host selectors within @layer theme.\n */\nfunction extractCssVariables(css: string): Map<string, string> {\n const variables = new Map<string, string>()\n const root = postcss.parse(css)\n\n root.walkAtRules(\"layer\", (atRule) => {\n if (atRule.params !== \"theme\") {\n return\n }\n\n atRule.walkRules(\":root, :host\", (rule) => {\n rule.walkDecls((decl) => {\n if (decl.prop.startsWith(\"--\")) {\n variables.set(decl.prop, decl.value)\n }\n })\n })\n })\n\n return variables\n}\n\n/**\n * Evaluate a calc() expression with resolved numeric values.\n * Handles expressions like \"0.25rem * 4\" -> \"1rem\" or \"1.25 / 0.875\" -> \"1.4286\"\n */\nfunction evaluateCalc(expression: string): string | null {\n const expr = expression.trim()\n\n // Pattern 1: number+unit operator number (e.g., \"0.25rem * 4\")\n const withUnitFirst = expr.match(\n /^([\\d.]+)(rem|px|em|%|vh|vw)\\s*([*/+-])\\s*([\\d.]+)$/,\n )\n if (withUnitFirst) {\n const [, num1, unit, op, num2] = withUnitFirst\n const result = evaluateOperation(parseFloat(num1), op, parseFloat(num2))\n if (!Number.isFinite(result)) {\n return null\n }\n return formatNumber(result) + unit\n }\n\n // Pattern 2: number operator number+unit (e.g., \"4 * 0.25rem\")\n const withUnitSecond = expr.match(\n /^([\\d.]+)\\s*([*/+-])\\s*([\\d.]+)(rem|px|em|%|vh|vw)$/,\n )\n if (withUnitSecond) {\n const [, num1, op, num2, unit] = withUnitSecond\n const result = evaluateOperation(parseFloat(num1), op, parseFloat(num2))\n if (!Number.isFinite(result)) {\n return null\n }\n return formatNumber(result) + unit\n }\n\n // Pattern 3: unitless (e.g., \"1.25 / 0.875\")\n const unitless = expr.match(/^([\\d.]+)\\s*([*/+-])\\s*([\\d.]+)$/)\n if (unitless) {\n const [, num1, op, num2] = unitless\n const result = evaluateOperation(parseFloat(num1), op, parseFloat(num2))\n if (!Number.isFinite(result)) {\n return null\n }\n return formatNumber(result)\n }\n\n return null\n}\n\nfunction evaluateOperation(a: number, op: string, b: number): number {\n switch (op) {\n case \"*\":\n return a * b\n case \"/\":\n return a / b\n case \"+\":\n return a + b\n case \"-\":\n return a - b\n default:\n return NaN\n }\n}\n\nfunction formatNumber(num: number): string {\n // Avoid floating point artifacts like 0.30000000000000004\n const rounded = Math.round(num * 10000) / 10000\n return String(rounded)\n}\n\n/**\n * Convert rem values to pixels (assuming 1rem = 16px).\n */\nfunction remToPx(value: string): string {\n return value.replace(/([\\d.]+)rem/g, (_, num) => {\n const px = parseFloat(num) * 16\n return `${formatNumber(px)}px`\n })\n}\n\n/**\n * Find the matching closing parenthesis for a var() call.\n * Handles nested parentheses in fallback values.\n */\nfunction findVarEnd(str: string, start: number): number {\n let depth = 0\n for (let i = start; i < str.length; i++) {\n if (str[i] === \"(\") {\n depth++\n } else if (str[i] === \")\") {\n depth--\n if (depth === 0) {\n return i\n }\n }\n }\n return -1\n}\n\n/**\n * Parse a var() expression and return its parts.\n */\nfunction parseVar(\n str: string,\n startIndex: number,\n): {end: number; fallback: string | null; varName: string} | null {\n // Find \"var(\" starting position\n const varStart = str.indexOf(\"var(\", startIndex)\n if (varStart === -1) {\n return null\n }\n\n const contentStart = varStart + 4 // After \"var(\"\n const end = findVarEnd(str, varStart)\n if (end === -1) {\n return null\n }\n\n const content = str.slice(contentStart, end)\n\n // Find comma separating variable name from fallback\n let commaIndex = -1\n let depth = 0\n for (let i = 0; i < content.length; i++) {\n if (content[i] === \"(\") {\n depth++\n } else if (content[i] === \")\") {\n depth--\n } else if (content[i] === \",\" && depth === 0) {\n commaIndex = i\n break\n }\n }\n\n if (commaIndex === -1) {\n return {\n end,\n fallback: null,\n varName: content.trim(),\n }\n }\n\n return {\n end,\n fallback: content.slice(commaIndex + 1).trim(),\n varName: content.slice(0, commaIndex).trim(),\n }\n}\n\n/**\n * Resolve CSS var() references and evaluate calc() expressions.\n * Recursively resolves nested var() calls.\n */\nfunction resolveCssValue(\n value: string,\n variables: Map<string, string>,\n depth = 0,\n): string {\n if (depth > 10) {\n return value // Prevent infinite recursion\n }\n\n let resolved = value\n let searchStart = 0\n\n // Process var() calls iteratively to handle nested var() in fallbacks\n while (true) {\n const parsed = parseVar(resolved, searchStart)\n if (!parsed) {\n break\n }\n\n const {end, fallback, varName} = parsed\n const varStart = resolved.indexOf(\"var(\", searchStart)\n\n let replacement: string\n const varValue = variables.get(varName)\n if (varValue !== undefined) {\n replacement = resolveCssValue(varValue, variables, depth + 1)\n } else if (fallback) {\n replacement = resolveCssValue(fallback, variables, depth + 1)\n } else {\n // Keep original if unresolved, move past it\n searchStart = end + 1\n continue\n }\n\n resolved =\n resolved.slice(0, varStart) + replacement + resolved.slice(end + 1)\n }\n\n // Evaluate calc() expressions after var() resolution\n resolved = resolved.replace(\n /calc\\(([^)]+)\\)/g,\n (match, expression: string) => {\n const evaluated = evaluateCalc(expression)\n return evaluated ?? match\n },\n )\n\n // Convert rem to px (1rem = 16px)\n resolved = remToPx(resolved)\n\n return resolved\n}\n\ninterface SelectorAnalysis {\n /** The class name if it's a simple class selector */\n className: string | null\n /** Whether this selector can be inlined (single class, no pseudo/combinators) */\n inlineable: boolean\n}\n\n/**\n * Analyze a CSS selector using postcss-selector-parser AST.\n * Returns whether it can be inlined and extracts the class name.\n */\nfunction analyzeSelector(selector: string): SelectorAnalysis {\n let inlineable = true\n let className: string | null = null\n\n const processor = selectorParser((selectors) => {\n if (selectors.nodes.length !== 1) {\n inlineable = false\n return\n }\n\n const selectorNode = selectors.nodes[0]\n if (selectorNode.nodes.length !== 1) {\n inlineable = false\n return\n }\n\n const node = selectorNode.nodes[0]\n if (node.type !== \"class\") {\n inlineable = false\n return\n }\n\n className = node.value\n\n selectorNode.walk((n) => {\n if (\n n.type === \"pseudo\" ||\n n.type === \"combinator\" ||\n n.type === \"nesting\" ||\n n.type === \"attribute\"\n ) {\n inlineable = false\n }\n })\n })\n\n processor.processSync(selector)\n\n return {className, inlineable}\n}\n\ninterface ParsedRule {\n className: string\n declarations: string\n inlineable: boolean\n originalRule: string\n}\n\n/**\n * Parse compiled CSS and extract rules with their inlineability status.\n * CSS variables are resolved and calc() expressions are evaluated.\n */\nfunction parseCompiledCss(css: string): ParsedRule[] {\n const rules: ParsedRule[] = []\n const root = postcss.parse(css)\n const variables = extractCssVariables(css)\n\n function processRule(rule: Rule, insideAtRule: boolean) {\n const {className, inlineable} = analyzeSelector(rule.selector)\n\n if (!className) {\n return\n }\n\n let hasNestedAtRule = false\n rule.walkAtRules(() => {\n hasNestedAtRule = true\n })\n\n const declarations: string[] = []\n rule.each((node) => {\n if (node.type === \"decl\") {\n const resolvedValue = resolveCssValue(node.value, variables)\n declarations.push(`${node.prop}: ${resolvedValue}`)\n }\n })\n\n if (declarations.length === 0 && !hasNestedAtRule) {\n return\n }\n\n rules.push({\n className,\n declarations: declarations.join(\"; \"),\n inlineable: inlineable && !insideAtRule && !hasNestedAtRule,\n originalRule: rule.toString(),\n })\n }\n\n root.walkAtRules(\"layer\", (atRule) => {\n atRule.walkRules((rule) => {\n const parent = rule.parent\n const insideNestedAtRule =\n parent?.type === \"atrule\" && (parent as postcss.AtRule).name !== \"layer\"\n processRule(rule, insideNestedAtRule)\n })\n\n atRule.walkAtRules((nested) => {\n if (nested.name !== \"layer\") {\n nested.walkRules((rule) => {\n processRule(rule, true)\n })\n }\n })\n })\n\n root.walkRules((rule) => {\n if (rule.parent?.type === \"root\") {\n processRule(rule, false)\n }\n })\n\n return rules\n}\n\n/**\n * Build residual CSS from non-inlineable rules, stripping @layer wrappers.\n */\nfunction buildResidualCss(css: string, inlineableClasses: Set<string>): string {\n const root = postcss.parse(css)\n const residualRules: string[] = []\n\n function shouldKeepRule(rule: Rule): boolean {\n const {className} = analyzeSelector(rule.selector)\n return className !== null && !inlineableClasses.has(className)\n }\n\n root.walkAtRules(\"layer\", (atRule) => {\n if (atRule.params !== \"utilities\") {\n return\n }\n\n atRule.each((node) => {\n if (node.type === \"rule\") {\n const rule = node\n if (shouldKeepRule(rule)) {\n residualRules.push(rule.toString())\n }\n }\n })\n })\n\n return residualRules.join(\"\\n\\n\")\n}\n\nexport interface TransformResult {\n /** CSS for non-inlineable rules without @layer wrappers */\n css: string\n /** HTML with inline styles applied */\n html: string\n}\n\n/**\n * Transform HTML by inlining Tailwind styles where possible.\n * Non-inlineable styles (pseudo-classes, media queries, etc.) are returned as CSS.\n */\nexport async function transformWithInlineStyles(\n html: string,\n styles: string,\n): Promise<TransformResult> {\n const compiler = await createCompiler(styles)\n const allClasses = extractClasses(html)\n const compiledCss = compiler.build(allClasses)\n const parsedRules = parseCompiledCss(compiledCss)\n\n const inlineableStyles = new Map<string, string>()\n const inlineableClasses = new Set<string>()\n\n for (const rule of parsedRules) {\n if (rule.inlineable) {\n inlineableStyles.set(rule.className, rule.declarations)\n inlineableClasses.add(rule.className)\n }\n }\n\n const residualCss = buildResidualCss(compiledCss, inlineableClasses)\n const tree = fromHtml(html, {fragment: true})\n\n visit(tree, \"element\", (node: Element) => {\n const classValue = getClassValue(node)\n if (!classValue) {\n return\n }\n\n const classes = classValue.split(/\\s+/)\n const inlineStyles: string[] = []\n const remainingClasses: string[] = []\n\n for (const cls of classes) {\n const style = inlineableStyles.get(cls)\n if (style) {\n inlineStyles.push(style)\n } else {\n remainingClasses.push(cls)\n }\n }\n\n if (inlineStyles.length > 0) {\n const existingStyle = node.properties?.style as string | undefined\n const newStyle = inlineStyles.join(\"; \")\n node.properties = node.properties ?? {}\n node.properties.style = existingStyle\n ? `${existingStyle}; ${newStyle}`\n : newStyle\n }\n\n if (remainingClasses.length > 0) {\n node.properties = node.properties ?? {}\n node.properties.className = remainingClasses\n } else if (node.properties) {\n delete node.properties.className\n delete node.properties.class\n }\n })\n\n return {\n css: residualCss,\n html: toHtml(tree),\n }\n}\n\nexport interface ShikiTailwindTransformerOptions {\n /**\n * Callback invoked after transformation indicating whether any className/class\n * attributes were detected in the code. Useful for conditionally applying\n * the transformation or showing/hiding UI elements.\n */\n onClassesDetected?: (detected: boolean) => void\n /**\n * Callback invoked with CSS rules for non-inlineable classes (hover:, sm:, etc.).\n * Receives a Map where keys are class names and values are the CSS rule strings.\n * This allows for deduplication when aggregating CSS from multiple files.\n */\n onResidualCss?: (rules: Map<string, string>) => void\n /**\n * Output format for inline styles.\n * - \"html\": `style=\"display: flex\"` (HTML string syntax)\n * - \"jsx\": `style={{ display: 'flex' }}` (JSX object syntax)\n * @default \"html\"\n */\n styleFormat?: \"html\" | \"jsx\"\n /** Tailwind CSS styles to compile against */\n styles: string\n}\n\ninterface CompileClassesResult {\n inlineStyles: string[]\n remainingClasses: string[]\n residualRules: Map<string, string>\n}\n\n/**\n * Compile classes and return inline styles, remaining classes, and residual CSS\n * rules.\n */\nfunction compileClasses(\n classes: string[],\n compiler: {build(candidates: string[]): string},\n): CompileClassesResult {\n const compiledCss = compiler.build(classes)\n const parsedRules = parseCompiledCss(compiledCss)\n\n const inlineableStyles = new Map<string, string>()\n const residualRules = new Map<string, string>()\n\n for (const rule of parsedRules) {\n if (rule.inlineable) {\n inlineableStyles.set(rule.className, rule.declarations)\n } else {\n residualRules.set(rule.className, rule.originalRule)\n }\n }\n\n const inlineStyles: string[] = []\n const remainingClasses: string[] = []\n\n for (const cls of classes) {\n const style = inlineableStyles.get(cls)\n if (style) {\n inlineStyles.push(style)\n } else {\n remainingClasses.push(cls)\n }\n }\n\n return {inlineStyles, remainingClasses, residualRules}\n}\n\n/**\n * Convert CSS declarations to JSX object syntax.\n * `\"display: flex; align-items: center\"` -> `\"{ display: 'flex', alignItems:\n * 'center'}\"`\n */\nfunction cssToJsxObject(cssDeclarations: string[]): string {\n const props = cssDeclarations\n .flatMap((decl) => {\n return decl\n .split(\";\")\n .map((d) => d.trim())\n .filter(Boolean)\n })\n .map((declaration) => {\n const colonIndex = declaration.indexOf(\":\")\n if (colonIndex === -1) {\n return null\n }\n const prop = declaration.slice(0, colonIndex).trim()\n const value = declaration.slice(colonIndex + 1).trim()\n const camelProp = camelCase(prop)\n return `${camelProp}: '${value}'`\n })\n .filter(Boolean)\n\n return `{ ${props.join(\", \")} }`\n}\n\ninterface LineReplacementsResult {\n replacements: Map<string, string>\n residualRules: Map<string, string>\n}\n\n/**\n * Transform className attributes to style attributes in a line's text.\n * Returns replacements and residual CSS rules for non-inlineable classes.\n */\nfunction computeLineReplacements(\n lineText: string,\n compiler: {build(candidates: string[]): string},\n styleFormat: \"html\" | \"jsx\" = \"html\",\n): LineReplacementsResult {\n const replacements = new Map<string, string>()\n const allResidualRules = new Map<string, string>()\n const classAttrPattern = /(className|class)=([\"'`])([^\"'`]*)\\2/g\n let match\n\n while ((match = classAttrPattern.exec(lineText)) !== null) {\n const fullMatch = match[0]\n const attrName = match[1]\n const quote = match[2]\n const classValue = match[3]\n\n const classes = classValue.split(/\\s+/).filter(Boolean)\n if (classes.length === 0) {\n continue\n }\n\n const {inlineStyles, remainingClasses, residualRules} = compileClasses(\n classes,\n compiler,\n )\n\n for (const [className, rule] of residualRules) {\n allResidualRules.set(className, rule)\n }\n\n if (inlineStyles.length === 0) {\n continue\n }\n\n let replacement: string\n if (styleFormat === \"jsx\") {\n const jsxStyleObj = cssToJsxObject(inlineStyles)\n replacement = `style={${jsxStyleObj}}`\n } else {\n replacement = `style=${quote}${inlineStyles.join(\"; \")}${quote}`\n }\n\n if (remainingClasses.length > 0) {\n replacement += ` ${attrName}=${quote}${remainingClasses.join(\" \")}${quote}`\n }\n\n replacements.set(fullMatch, replacement)\n }\n\n return {replacements, residualRules: allResidualRules}\n}\n\ninterface TransformSourceResult {\n /** Whether any className/class attributes were detected in the code */\n classesDetected: boolean\n /** CSS rules for non-inlineable classes */\n residualRules: Map<string, string>\n /** Transformed source code */\n source: string\n}\n\n/**\n * Transform className/class attributes to inline styles in source code.\n * This runs BEFORE Shiki tokenization to preserve proper syntax highlighting.\n */\nfunction transformSourceCode(\n source: string,\n compiler: {build(candidates: string[]): string},\n styleFormat: \"html\" | \"jsx\" = \"html\",\n): TransformSourceResult {\n const allResidualRules = new Map<string, string>()\n let classesDetected = false\n\n const {replacements, residualRules} = computeLineReplacements(\n source,\n compiler,\n styleFormat,\n )\n\n if (replacements.size > 0 || residualRules.size > 0) {\n classesDetected = true\n }\n\n for (const [cls, rule] of residualRules) {\n allResidualRules.set(cls, rule)\n }\n\n // Apply all replacements to the source\n let transformed = source\n for (const [original, replacement] of replacements) {\n transformed = transformed.replaceAll(original, replacement)\n }\n\n return {\n classesDetected,\n residualRules: allResidualRules,\n source: transformed,\n }\n}\n\n/**\n * Create a Shiki transformer that inlines Tailwind styles.\n * Uses preprocess to transform source code BEFORE tokenization,\n * ensuring proper syntax highlighting of the transformed output.\n * Must be called with `await` before using the transformer.\n */\nexport async function createShikiTailwindTransformer(\n options: ShikiTailwindTransformerOptions,\n): Promise<ShikiTransformer> {\n const {\n onClassesDetected,\n onResidualCss,\n styleFormat = \"html\",\n styles,\n } = options\n const compiler = await createCompiler(styles)\n\n return {\n name: \"shiki-transformer-tailwind-to-inline\",\n preprocess(code) {\n const {classesDetected, residualRules, source} = transformSourceCode(\n code,\n compiler,\n styleFormat,\n )\n\n onClassesDetected?.(classesDetected)\n\n if (onResidualCss && residualRules.size > 0) {\n onResidualCss(residualRules)\n }\n\n return source\n },\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nexport const VIRTUAL_MODULE_IDS = {\n AUTO: \"\\0virtual:qui-demo-scope/auto\",\n CONFIG: \"\\0virtual:qui-demo-scope/config\",\n PAGE_PREFIX: \"\\0virtual:qui-demo-scope/page:\",\n} as const\n\nexport const LOG_PREFIX = \"@qualcomm-ui/mdx-vite/react-demo-plugin:\"\n\nexport const REACT_IMPORTS: string[] = [\n \"useState\",\n \"useEffect\",\n \"useMemo\",\n \"useCallback\",\n \"useRef\",\n \"useContext\",\n \"createContext\",\n \"forwardRef\",\n \"memo\",\n \"lazy\",\n \"Suspense\",\n \"Fragment\",\n] as const\n\nexport const NODE_BUILTINS: string[] = [\n \"fs\",\n \"path\",\n \"url\",\n \"util\",\n \"os\",\n \"crypto\",\n \"events\",\n \"stream\",\n \"buffer\",\n] as const\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 chalk from \"chalk\"\nimport {glob} from \"glob\"\nimport {readFile} from \"node:fs/promises\"\nimport {basename, resolve} from \"node:path\"\nimport {createHighlighter, type Highlighter, type ShikiTransformer} from \"shiki\"\nimport * as ts from \"typescript\"\nimport type {Plugin} from \"vite\"\n\nimport {\n quiCustomDarkTheme,\n type ReactDemoData,\n type SourceCodeData,\n} from \"@qualcomm-ui/mdx-common\"\nimport {dedent} from \"@qualcomm-ui/utils/dedent\"\n\nimport {getShikiTransformers} from \"../docs-plugin\"\nimport {\n extractPreviewFromHighlightedHtml,\n transformerCodeAttribute,\n transformerPreviewBlock,\n} from \"../docs-plugin/shiki\"\nimport {createShikiTailwindTransformer} from \"../docs-plugin/shiki/internal\"\n\nimport {LOG_PREFIX, VIRTUAL_MODULE_IDS} from \"./demo-plugin-constants\"\nimport type {QuiDemoPluginOptions} from \"./demo-plugin-types\"\nimport {\n createDemoName,\n extractFileImports,\n extractPageId,\n getScriptKind,\n isCssAsset,\n isDemoFile,\n} from \"./demo-plugin-utils\"\n\ninterface HandleUpdateOptions {\n demoName?: string\n filePath: string\n}\n\ninterface HighlightCodeResult {\n full: string\n preview?: string | null\n}\n\ninterface ExtractedSourceCode {\n residualRules?: Map<string, string>\n sourceCodeData: SourceCodeData\n}\n\nlet highlighter: Highlighter | null = null\nlet initializingHighlighter = false\n\nconst demoRegistry = new Map<string, ReactDemoData>()\nconst pageFiles = new Map<string, string[]>()\nconst relativeImportDependents = new Map<string, Set<string>>()\n\n/**\n * Generates virtual modules for React demo components. Virtual modules contain\n * highlighted source code and metadata about each demo.\n */\nexport function reactDemoPlugin({\n demoPattern = \"src/routes/**/demos/*.tsx\",\n routesDir = \"src/routes\",\n theme = {\n dark: quiCustomDarkTheme,\n light: \"github-light-high-contrast\",\n },\n transformers = [],\n transformLine,\n transformTailwindStyles,\n}: QuiDemoPluginOptions = {}): Plugin {\n const defaultShikiOptions = {\n defaultColor: \"light-dark()\",\n lang: \"tsx\",\n themes: {\n dark: theme.dark,\n light: theme.light,\n },\n }\n\n return {\n apply(config, env) {\n return (\n (env.mode === \"development\" && env.command === \"serve\") ||\n (env.mode === \"production\" && env.command === \"build\")\n )\n },\n async buildStart() {\n if (!highlighter && !initializingHighlighter) {\n initializingHighlighter = true\n try {\n highlighter = await createHighlighter({\n langs: [\"tsx\", \"typescript\", \"css\"],\n themes: [theme.dark, theme.light],\n })\n console.log(\n `${chalk.magenta.bold(LOG_PREFIX)} Shiki highlighter initialized`,\n )\n } catch (error) {\n console.warn(\n `${chalk.magenta.bold(LOG_PREFIX)} Failed to initialize highlighter:`,\n error,\n )\n } finally {\n initializingHighlighter = false\n }\n }\n\n await collectReactDemos()\n },\n\n async handleHotUpdate({file, modules, server}) {\n if (isCssAsset(file)) {\n return modules\n }\n\n if (file.endsWith(\".mdx\")) {\n return []\n }\n\n if (isDemoFile(file)) {\n await handleDemoAdditionOrUpdate({filePath: file})\n } else {\n const normalizedFile = resolve(file)\n const dependentDemos = relativeImportDependents.get(normalizedFile)\n if (!dependentDemos?.size) {\n return []\n }\n for (const demoName of Array.from(dependentDemos)) {\n const demo = demoRegistry.get(demoName)\n if (demo) {\n await handleDemoAdditionOrUpdate({\n filePath: demo.filePath,\n })\n }\n }\n }\n\n const autoModule = server.moduleGraph.getModuleById(\n VIRTUAL_MODULE_IDS.AUTO,\n )\n if (autoModule) {\n server.moduleGraph.invalidateModule(autoModule)\n await server.reloadModule(autoModule)\n }\n return []\n },\n\n async load(id) {\n if (id === VIRTUAL_MODULE_IDS.AUTO) {\n return generateAutoScopeModule()\n }\n },\n\n name: \"auto-demo-scope\",\n\n resolveId(id) {\n if (id === \"virtual:qui-demo-scope/auto\") {\n return VIRTUAL_MODULE_IDS.AUTO\n }\n },\n\n writeBundle() {\n console.log(\n `${chalk.blue.bold(LOG_PREFIX)} Successfully integrated ${chalk.green(demoRegistry.size)} component demos`,\n )\n },\n }\n\n async function handleDemoAdditionOrUpdate({\n filePath,\n }: HandleUpdateOptions): Promise<void> {\n const pageId = extractPageId(filePath, routesDir)\n const demoName = createDemoName(filePath)\n\n const existingFiles = pageFiles.get(pageId) ?? []\n if (!existingFiles.includes(filePath)) {\n existingFiles.push(filePath)\n pageFiles.set(pageId, existingFiles)\n }\n\n const fileData = await extractFileData(filePath)\n if (fileData) {\n demoRegistry.set(demoName, {\n ...fileData,\n demoName,\n pageId,\n })\n\n const fileImports = await extractFileImports(filePath)\n if (fileImports) {\n for (const relativeImport of fileImports.relativeImports) {\n const dependents =\n relativeImportDependents.get(relativeImport.resolvedPath) ??\n new Set()\n dependents.add(demoName)\n relativeImportDependents.set(relativeImport.resolvedPath, dependents)\n }\n }\n }\n }\n\n async function highlightCode(\n code: string,\n options: {\n extraTransformers?: ShikiTransformer[]\n onClassesDetected?: (detected: boolean) => void\n onResidualCss?: (rules: Map<string, string>) => void\n } = {},\n ): Promise<HighlightCodeResult> {\n const {extraTransformers = [], onResidualCss} = options\n\n if (!highlighter) {\n return {full: code}\n }\n let previewCode: string | null = null\n\n const tailwindTransformers: ShikiTransformer[] = []\n if (transformTailwindStyles && onResidualCss) {\n const transformer = await createShikiTailwindTransformer({\n onClassesDetected: (detected) => {\n options.onClassesDetected?.(detected)\n },\n onResidualCss,\n styleFormat: \"jsx\",\n styles: dedent`\n @layer theme, base, components, utilities;\n @import \"tailwindcss/theme.css\" layer(theme);\n @import \"tailwindcss/utilities.css\" layer(utilities);\n @import \"@qualcomm-ui/tailwind-plugin/qui-strict.css\";\n `,\n })\n tailwindTransformers.push(transformer)\n } else if (extraTransformers.length > 0) {\n tailwindTransformers.push(...extraTransformers)\n }\n\n try {\n const highlightedCode = highlighter.codeToHtml(code, {\n ...defaultShikiOptions,\n transformers: [\n ...getShikiTransformers(),\n ...transformers,\n ...tailwindTransformers,\n transformerPreviewBlock({\n attributeName: \"data-preview\",\n onComplete: (extractedPreview) => {\n previewCode = extractedPreview\n },\n }),\n transformerCodeAttribute({\n attributeName: \"data-code\",\n }),\n {\n enforce: \"post\",\n name: \"shiki-transformer-trim\",\n preprocess(code) {\n return code.trim()\n },\n },\n ...transformers,\n ],\n })\n\n return {\n full: highlightedCode,\n preview: previewCode\n ? extractPreviewFromHighlightedHtml(highlightedCode)\n : null,\n }\n } catch (error) {\n console.warn(\n `${chalk.magenta.bold(LOG_PREFIX)} Failed to highlight code:`,\n error,\n )\n return {full: code}\n }\n }\n\n async function collectReactDemos() {\n if (demoRegistry.size) {\n return\n }\n\n const demoFiles = (await glob(demoPattern)).filter(isDemoFile)\n\n for (const filePath of demoFiles) {\n const pageId = extractPageId(filePath, routesDir)\n const existingFiles = pageFiles.get(pageId) ?? []\n existingFiles.push(filePath)\n pageFiles.set(pageId, existingFiles)\n\n const fileData = await extractFileData(filePath)\n if (fileData) {\n const demoName = createDemoName(filePath)\n demoRegistry.set(demoName, {\n ...fileData,\n pageId,\n })\n }\n\n const fileImports = await extractFileImports(filePath)\n if (fileImports) {\n for (const relativeImport of fileImports.relativeImports) {\n const demoName = createDemoName(filePath)\n const dependents =\n relativeImportDependents.get(relativeImport.resolvedPath) ??\n new Set()\n dependents.add(demoName)\n relativeImportDependents.set(relativeImport.resolvedPath, dependents)\n }\n }\n }\n }\n\n function generateAutoScopeModule(): string {\n const registryCode = generateDemoRegistry(demoRegistry)\n return [\n \"// Auto-generated demo scope resolver (PROD MODE)\",\n registryCode,\n generateExportedFunctions(),\n ].join(\"\\n\\n\")\n }\n\n function transformLines(code: string): string {\n if (!transformLine) {\n return code\n }\n const result: string[] = []\n for (const line of code.split(\"\\n\")) {\n if (line.trim()) {\n const transformed = transformLine(line)\n if (transformed) {\n result.push(transformed)\n }\n } else {\n // include all empty lines\n result.push(line)\n }\n }\n return result.join(\"\\n\")\n }\n\n async function extractHighlightedCode(\n filePath: string,\n code: string,\n ): Promise<ExtractedSourceCode | null> {\n try {\n const fileName = basename(filePath)\n\n const baseResult = await highlightCode(code)\n\n let inlineResult: HighlightCodeResult | undefined\n let classesDetected: boolean = false\n let residualRules: Map<string, string> | undefined\n\n if (transformTailwindStyles) {\n inlineResult = await highlightCode(code, {\n onClassesDetected: (detected) => {\n classesDetected = detected\n },\n onResidualCss: (rules) => {\n residualRules = rules\n },\n })\n }\n\n return {\n residualRules,\n sourceCodeData: {\n fileName,\n filePath,\n highlighted: {\n full: baseResult.full,\n preview: baseResult.preview,\n },\n highlightedInline:\n classesDetected && inlineResult\n ? {\n full: inlineResult.full,\n preview: inlineResult.preview,\n }\n : undefined,\n type: \"file\",\n },\n }\n } catch {\n return null\n }\n }\n\n async function extractFileData(\n filePath: string,\n ): Promise<Omit<ReactDemoData, \"pageId\"> | null> {\n try {\n const code = await readFile(filePath, \"utf-8\").then(transformLines)\n const imports = stripImports(code, filePath)\n\n const sourceCode: SourceCodeData[] = []\n // Use Map for deduplication across all files in this demo\n const aggregatedRules = new Map<string, string>()\n\n const extractedMain = await extractHighlightedCode(filePath, code)\n\n if (extractedMain) {\n sourceCode.push(extractedMain.sourceCodeData)\n if (extractedMain.residualRules) {\n for (const [className, rule] of extractedMain.residualRules) {\n aggregatedRules.set(className, rule)\n }\n }\n }\n\n const fileImports = await extractFileImports(filePath)\n if (fileImports) {\n for (const relativeImport of fileImports.relativeImports) {\n try {\n const importedCode = await readFile(\n relativeImport.resolvedPath,\n \"utf-8\",\n ).then(transformLines)\n\n const extracted = await extractHighlightedCode(\n relativeImport.resolvedPath,\n importedCode,\n )\n\n if (extracted) {\n sourceCode.push(extracted.sourceCodeData)\n if (extracted.residualRules) {\n for (const [className, rule] of extracted.residualRules) {\n aggregatedRules.set(className, rule)\n }\n }\n }\n } catch {\n console.debug(\"Failed to process file\", relativeImport.resolvedPath)\n }\n }\n }\n\n // Convert aggregated rules to CSS string\n const aggregatedResidualCss =\n aggregatedRules.size > 0\n ? [...aggregatedRules.values()].join(\"\\n\\n\")\n : undefined\n\n if (aggregatedResidualCss) {\n sourceCode.push({\n fileName: \"styles.css\",\n highlighted: await highlightCode(aggregatedResidualCss),\n type: \"residual-css\",\n })\n }\n\n return {\n demoName: createDemoName(filePath),\n fileName: extractedMain?.sourceCodeData.fileName || basename(filePath),\n filePath,\n imports,\n sourceCode,\n }\n } catch {\n return null\n }\n }\n\n function stripImports(code: string, fileName: string): string[] {\n try {\n const sourceFile = ts.createSourceFile(\n fileName,\n code,\n ts.ScriptTarget.Latest,\n true,\n getScriptKind(fileName),\n )\n\n const importRanges: Array<{end: number; start: number}> = []\n\n function visit(node: ts.Node) {\n if (ts.isImportDeclaration(node)) {\n importRanges.push({\n end: node.getEnd(),\n start: node.getFullStart(),\n })\n }\n ts.forEachChild(node, visit)\n }\n\n visit(sourceFile)\n\n return importRanges.map((range) => {\n let endPos = range.end\n if (code[endPos] === \"\\n\") {\n endPos++\n }\n return code.slice(range.start, endPos).trim()\n })\n } catch (error) {\n return []\n }\n }\n\n function generateDemoRegistry(registry: Map<string, ReactDemoData>): string {\n const entries = Array.from(registry.entries())\n .map(([demoName, {fileName, imports, pageId, sourceCode}]) => {\n return ` [\"${demoName}\", { fileName: \"${fileName}\", imports: ${JSON.stringify(imports)}, pageId: \"${pageId}\", sourceCode: ${JSON.stringify(sourceCode)}, demoName: \"${demoName}\" }]`\n })\n .join(\",\\n\")\n return `const demoRegistry = new Map([\\n${entries}\\n])`\n }\n\n function generateExportedFunctions(): string {\n return dedent`\n export function getDemo(demoName) {\n const demo = demoRegistry.get(demoName)\n if (!demo) {\n return {\n fileName: \"\",\n imports: [],\n errorMessage: \\`Demo \"\\${demoName}\" not found.\\`,\n pageId: \"\",\n sourceCode: [],\n }\n }\n return demo\n }\n `\n }\n}\n"],
5
- "mappings": ";;;AAEA,OAAOA,YAAW;AAClB,SAAwB,aAAY;AACpC,SAAQ,QAAAC,aAAW;AACnB,SAAQ,kBAAiB;AACzB,SAAQ,YAAAC,WAAU,YAAW;AAC7B,SAAQ,UAAU,SAAS,QAAAC,OAAM,YAAAC,WAAU,WAAAC,gBAAc;AACzD;AAAA,EACE;AAAA,OAKK;AACP,YAAY,QAAQ;AAGpB;AAAA,EAEE,sBAAAC;AAAA,OAEK;AACP,SAAQ,UAAAC,eAAa;;;ACpBrB,OAAOC,YAAW;AAClB,OAAO,cAAc;AACrB,SAAQ,YAAW;AACnB,SAAQ,gBAAAC,qBAAmB;AAC3B,SAAQ,eAAc;AACtB,OAAO,wBAAwB;;;ACL/B,SAA6C,uBAAsB;;;ACAnE,SAAQ,KAAAC,UAAwC;;;ACAhD,SAAQ,SAAQ;AAYT,SAAS,YAA2B;AACzC,SAAO;AAAA,IACL,MAAM,CAKJ,WACG,EAAE,OAAO,MAAM;AAAA,EACtB;AACF;;;ADRO,IAAM,gBAA+B,UAAmB,EAAE,KAAK;AAAA,EACpE,IAAIC,GAAE,MAAM,EAAE,SAA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A,UAC3B,CAAC;AAAA,QACH;AACA,QAAG,iBAAa,MAAMA,OAAK;AAAA,MAC7B;AARS,UAAAA;AAVT,YAAM,aAAgB;AAAA,QACpB;AAAA,QACA;AAAA,QACG,iBAAa;AAAA,QAChB;AAAA,QACA,cAAc,QAAQ;AAAA,MACxB;AAEA,YAAM,eAAoD,CAAC;AAY3D,MAAAA,QAAM,UAAU;AAEhB,aAAO,aAAa,IAAI,CAAC,UAAU;AACjC,YAAI,SAAS,MAAM;AACnB,YAAI,KAAK,MAAM,MAAM,MAAM;AACzB;AAAA,QACF;AACA,eAAO,KAAK,MAAM,MAAM,OAAO,MAAM,EAAE,KAAK;AAAA,MAC9C,CAAC;AAAA,IACH,SAAS,OAAO;AACd,aAAO,CAAC;AAAA,IACV;AAAA,EACF;AAEA,WAAS,qBAAqB,UAA8C;AAC1E,UAAM,UAAU,MAAM,KAAK,SAAS,QAAQ,CAAC,EAC1C,IAAI,CAAC,CAAC,UAAU,EAAC,UAAU,SAAS,QAAQ,WAAU,CAAC,MAAM;AAC5D,aAAO,OAAO,QAAQ,mBAAmB,QAAQ,eAAe,KAAK,UAAU,OAAO,CAAC,cAAc,MAAM,kBAAkB,KAAK,UAAU,UAAU,CAAC,gBAAgB,QAAQ;AAAA,IACjL,CAAC,EACA,KAAK,KAAK;AACb,WAAO;AAAA,EAAmC,OAAO;AAAA;AAAA,EACnD;AAEA,WAAS,4BAAoC;AAC3C,WAAOL;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAeT;AACF;",
6
- "names": ["chalk", "glob", "readFile", "join", "relative", "resolve", "quiCustomDarkTheme", "dedent", "chalk", "readFileSync", "z", "z", "z", "z", "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", "chalk", "readFileSync", "chalk", "config", "file", "remarkFrontmatter", "remarkGfm", "headingRank", "visit", "visit", "toString", "visit", "emptyOptions", "visit", "remarkFrontmatter", "remarkGfm", "fromHtml", "visit", "createRequire", "VIRTUAL_MODULE_ID", "quiCustomDarkTheme", "chalk", "isCssAsset", "readFile", "glob", "dedent", "visit", "isRelativeImport", "resolveRelativeImport", "isNodeBuiltin", "loadTsConfigPaths", "relative", "NODE_BUILTINS", "resolve", "join", "LOG_PREFIX", "chalk", "existsSync", "readFileSync", "readFile", "dirname", "join", "relative", "resolve", "ts", "readFile", "chalk", "LOG_PREFIX", "visit", "isPathAliasImport", "resolvePathAlias", "dirname", "resolve", "existsSync", "join", "loadTsConfigPathsFromFile", "relative", "readFileSync", "chalk", "glob", "readFile", "basename", "resolve", "createHighlighter", "ts", "quiCustomDarkTheme", "dedent", "highlighter", "demoRegistry", "quiCustomDarkTheme", "createHighlighter", "chalk", "LOG_PREFIX", "resolve", "dedent", "code", "glob", "basename", "readFile", "visit"]
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", "../src/angular-demo-plugin/angular-demo-plugin.ts", "../src/docs-plugin/docs-plugin.ts", "../../../../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/generate-knowledge.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/mdx-utils.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/remark/remark-frontmatter-interpolation.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/common.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-frontmatter-description.ts", "../src/docs-plugin/remark/remark-frontmatter-title.ts", "../src/docs-plugin/remark/remark-self-link-headings.ts", "../src/docs-plugin/remark/remark-spoilers.ts", "../src/docs-plugin/shiki/utils.ts", "../src/docs-plugin/shiki/shiki-transformer-code-attribute.ts", "../src/docs-plugin/shiki/shiki-transformer-hidden.ts", "../src/docs-plugin/shiki/shiki-transformer-preview-block.ts", "../src/docs-plugin/shiki/internal/shiki-transformer-tailwind.ts", "../src/react-demo-plugin/demo-plugin-constants.ts", "../src/react-demo-plugin/demo-plugin-utils.ts", "../src/react-demo-plugin/react-demo-plugin.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", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\nimport chalk from \"chalk\"\nimport {type FSWatcher, watch} from \"chokidar\"\nimport {glob} from \"glob\"\nimport {existsSync} from \"node:fs\"\nimport {readFile, stat} from \"node:fs/promises\"\nimport {basename, dirname, join, relative, resolve} from \"node:path\"\nimport {\n createHighlighter,\n type Highlighter,\n type ThemeRegistration,\n type ThemeRegistrationRaw,\n type ThemeRegistrationResolved,\n} from \"shiki\"\nimport * as ts from \"typescript\"\nimport type {Plugin, ViteDevServer} from \"vite\"\n\nimport {\n type AngularDemoInfo,\n quiCustomDarkTheme,\n type SourceCodeData,\n} from \"@qualcomm-ui/mdx-common\"\nimport {dedent} from \"@qualcomm-ui/utils/dedent\"\n\nimport {getShikiTransformers} from \"../docs-plugin\"\nimport {\n extractPreviewFromHighlightedHtml,\n transformerCodeAttribute,\n transformerPreviewBlock,\n} from \"../docs-plugin/shiki\"\nimport {createShikiTailwindTransformer} from \"../docs-plugin/shiki/internal\"\n\nexport interface AngularDemoPluginOptions {\n demoPattern?: string | string[]\n /**\n * A mapping of <demoId, initialHtml>, which will be used for the initial\n * serverside render of each demo to prevent FOUC.\n */\n initialHtml?: Record<string, string>\n routesDir?: string\n theme?: {\n dark:\n | ThemeRegistrationRaw\n | ThemeRegistration\n | ThemeRegistrationResolved\n | string\n light:\n | ThemeRegistrationRaw\n | ThemeRegistration\n | ThemeRegistrationResolved\n | string\n }\n /**\n * When enabled, transforms Tailwind class names to inline styles in the\n * highlighted code. Non-inlineable classes (hover:, sm:, etc.) are kept as\n * className and their CSS rules are aggregated into a residual-css entry.\n */\n transformTailwindStyles?: boolean\n}\n\ninterface RelativeImport {\n resolvedPath: string\n source: string\n}\n\ninterface PathAlias {\n pattern: RegExp\n replacement: string\n}\n\ninterface HighlightCodeResult {\n full: string\n preview?: string | null\n}\n\nconst VIRTUAL_MODULE_ID = \"\\0virtual:angular-demo-registry\"\nconst LOG_PREFIX = \"[angular-demo]\"\n\nlet hasWatcherInitialized = false\n\nfunction logDev(...args: any[]) {\n if (!hasWatcherInitialized) {\n return\n }\n console.log(...args)\n}\n\nlet demoDimensionsCache: Record<string, DOMRect> = {}\nlet highlighter: Highlighter | null = null\nlet initCount = 0\nconst demoRegistry = new Map<string, AngularDemoInfo>()\nlet hotUpdateDemoIds: string[] = []\n\nexport function angularDemoPlugin({\n demoPattern = \"src/routes/**/demos/*.ts\",\n initialHtml,\n routesDir = \"src/routes\",\n theme = {\n dark: quiCustomDarkTheme,\n light: \"github-light-high-contrast\",\n },\n transformTailwindStyles,\n}: AngularDemoPluginOptions = {}): Plugin {\n let watcher: FSWatcher | null = null\n let devServer: ViteDevServer | null = null\n\n const defaultShikiOptions = {\n defaultColor: \"light-dark()\",\n themes: {\n dark: theme.dark,\n light: theme.light,\n },\n }\n\n return {\n async buildEnd() {\n if (watcher) {\n await watcher.close()\n watcher = null\n hasWatcherInitialized = false\n }\n },\n async buildStart() {\n if (initCount === 0) {\n initCount++\n return\n }\n\n if (!highlighter) {\n try {\n highlighter = await createHighlighter({\n langs: [\"angular-ts\", \"angular-html\", \"css\"],\n themes: [theme.dark, theme.light],\n })\n logDev(`${chalk.blue.bold(LOG_PREFIX)} Shiki highlighter initialized`)\n } catch (error) {\n console.warn(\n `${chalk.blue.bold(LOG_PREFIX)} Failed to initialize highlighter:`,\n error,\n )\n }\n }\n\n logDev(`${chalk.blue.bold(LOG_PREFIX)} Initializing Angular demo scanner`)\n await collectAngularDemos()\n\n if (process.env.NODE_ENV === \"development\") {\n if (!hasWatcherInitialized) {\n hasWatcherInitialized = true\n await setupAngularWatcher()\n } else {\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} Watcher already initialized by another instance`,\n )\n }\n }\n },\n configureServer(server) {\n devServer = server\n let dimensionUpdateTimeout: NodeJS.Timeout | null = null\n\n server.ws.on(\n \"custom:store-demo-dimensions\",\n (data: {demoId: string; dimensions: DOMRect}) => {\n const demoId = data.demoId\n demoDimensionsCache[demoId] = data.dimensions\n\n if (dimensionUpdateTimeout) {\n clearTimeout(dimensionUpdateTimeout)\n }\n\n dimensionUpdateTimeout = setTimeout(() => {\n const module = server.moduleGraph.getModuleById(VIRTUAL_MODULE_ID)\n if (module) {\n server.moduleGraph.invalidateModule(module)\n }\n }, 50)\n },\n )\n\n server.ws.on(\"custom:reset-demo-dimensions\", () => {\n demoDimensionsCache = {}\n const module = server.moduleGraph.getModuleById(VIRTUAL_MODULE_ID)\n if (module) {\n server.moduleGraph.invalidateModule(module)\n server.reloadModule(module)\n }\n })\n },\n async handleHotUpdate({file, modules, server}) {\n if (!isAngularDemoFile(file)) {\n if (isCssAsset(file)) {\n return modules\n }\n\n if (file.endsWith(\"main.js\")) {\n const ids = [...hotUpdateDemoIds]\n server.ws.send({\n data: {\n demoInfo: ids.reduce(\n (acc: Record<string, AngularDemoInfo | undefined>, current) => {\n acc[current] = demoRegistry.get(current)\n return acc\n },\n {},\n ),\n },\n event: \"demo-bundle-updated\",\n type: \"custom\",\n })\n }\n\n return []\n }\n\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} Processing Angular demo change: ${chalk.cyan(file)}`,\n )\n\n const code = await readFile(file, \"utf-8\")\n const demoInfo = await parseAngularDemo(file, code)\n\n if (!demoInfo || !isAngularDemoEntrypoint(file)) {\n // might be an imported file\n const affectedDemos: AngularDemoInfo[] =\n await scanDemosForFileImport(file)\n\n if (affectedDemos.length > 0) {\n hotUpdateDemoIds = []\n for (const demo of affectedDemos) {\n hotUpdateDemoIds.push(demo.id)\n }\n }\n\n server.ws.send({\n data: {\n ids: [...hotUpdateDemoIds],\n },\n event: \"demo-bundle-updating\",\n type: \"custom\",\n })\n\n return\n }\n\n delete demoDimensionsCache[demoInfo.id]\n demoRegistry.set(demoInfo.id, demoInfo)\n hotUpdateDemoIds = [demoInfo.id]\n\n server.ws.send({\n data: {\n ids: [...hotUpdateDemoIds],\n },\n event: \"demo-bundle-updating\",\n type: \"custom\",\n })\n\n const mainModule = server.moduleGraph.getModuleById(VIRTUAL_MODULE_ID)\n if (mainModule) {\n server.moduleGraph.invalidateModule(mainModule)\n }\n\n const demoModule = server.moduleGraph.getModuleById(file)\n if (demoModule) {\n server.moduleGraph.invalidateModule(demoModule)\n }\n\n return []\n },\n async load(id) {\n if (id === VIRTUAL_MODULE_ID) {\n return generateRegistryModule()\n }\n },\n name: \"angular-demo-plugin\",\n resolveId(id) {\n if (id === \"virtual:angular-demo-registry\") {\n return VIRTUAL_MODULE_ID\n }\n },\n writeBundle() {\n console.log(\n `${chalk.blue.bold(LOG_PREFIX)} Successfully integrated ${chalk.green(demoRegistry.size)} component demos`,\n )\n },\n }\n\n async function collectAngularDemos() {\n if (demoRegistry.size) {\n logDev(\n `${chalk.magenta.bold(LOG_PREFIX)} Using cached ${chalk.cyanBright.bold(demoRegistry.size)} demos`,\n )\n return\n }\n\n const demoFiles = await glob(demoPattern)\n demoRegistry.clear()\n\n for (const filePath of demoFiles) {\n const code = await readFile(filePath, \"utf-8\")\n const demoInfo = await parseAngularDemo(filePath, code)\n if (demoInfo) {\n demoRegistry.set(demoInfo.id, demoInfo)\n }\n }\n }\n\n async function scanDemosForFileImport(\n file: string,\n ): Promise<AngularDemoInfo[]> {\n const affectedDemos: AngularDemoInfo[] = []\n\n for (const [demoId, demo] of demoRegistry.entries()) {\n if (demo.sourceCode.find((entry) => entry.filePath === file)) {\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} Reloading demo ${chalk.cyan(demoId)} due to imported file change: ${chalk.yellow(file)}`,\n )\n\n const code = await readFile(demo.filePath, \"utf-8\")\n const updatedDemo = await parseAngularDemo(demo.filePath, code)\n\n if (updatedDemo) {\n delete demoDimensionsCache[updatedDemo.id]\n demoRegistry.set(updatedDemo.id, updatedDemo)\n affectedDemos.push(updatedDemo)\n hotUpdateDemoIds.push(updatedDemo.id)\n }\n }\n }\n\n return affectedDemos\n }\n\n async function highlightCode(\n code: string,\n language: \"angular-ts\" | \"angular-html\" | \"css\" = \"angular-ts\",\n options: {\n onClassesDetected?: (detected: boolean) => void\n onResidualCss?: (rules: Map<string, string>) => void\n } = {},\n ): Promise<HighlightCodeResult> {\n const {onClassesDetected, onResidualCss} = options\n\n if (!highlighter) {\n return {full: code}\n }\n\n let previewCode: string | null = null\n\n const tailwindTransformers = []\n if (transformTailwindStyles && onResidualCss) {\n const transformer = await createShikiTailwindTransformer({\n onClassesDetected: (detected) => {\n onClassesDetected?.(detected)\n },\n onResidualCss,\n styleFormat: \"html\",\n styles: dedent`\n @layer theme, base, components, utilities;\n @import \"tailwindcss/theme.css\" layer(theme);\n @import \"tailwindcss/utilities.css\" layer(utilities);\n @import \"@qualcomm-ui/tailwind-plugin/qui-strict.css\";\n `,\n })\n tailwindTransformers.push(transformer)\n }\n\n try {\n const highlightedCode = highlighter.codeToHtml(code, {\n ...defaultShikiOptions,\n lang: language,\n transformers: [\n ...getShikiTransformers(),\n ...tailwindTransformers,\n transformerPreviewBlock({\n attributeName: \"data-preview\",\n onComplete: (extractedPreview) => {\n previewCode = extractedPreview\n },\n }),\n transformerCodeAttribute({\n attributeName: \"data-code\",\n }),\n {\n enforce: \"post\",\n name: \"shiki-transformer-trim\",\n preprocess(inner) {\n return inner.trim()\n },\n },\n ],\n })\n\n return {\n full: highlightedCode,\n preview: previewCode\n ? extractPreviewFromHighlightedHtml(highlightedCode)\n : null,\n }\n } catch (error) {\n console.warn(\n `${chalk.blue.bold(LOG_PREFIX)} Failed to highlight code with ${language} language:`,\n error,\n )\n return {full: code}\n }\n }\n\n async function extractRelativeImports(\n filePath: string,\n ): Promise<RelativeImport[]> {\n try {\n const content = await readFile(filePath, \"utf-8\")\n\n const sourceFile = ts.createSourceFile(\n filePath,\n content,\n ts.ScriptTarget.Latest,\n true,\n ts.ScriptKind.TS,\n )\n\n const relativeImports: RelativeImport[] = []\n\n function visit(node: ts.Node) {\n if (ts.isImportDeclaration(node)) {\n const moduleSpecifier = node.moduleSpecifier\n\n if (ts.isStringLiteral(moduleSpecifier)) {\n const source = moduleSpecifier.text\n\n if (isRelativeImport(source)) {\n const resolvedPath = resolveRelativeImport(source, filePath)\n relativeImports.push({resolvedPath, source})\n } else if (!isNodeBuiltin(source)) {\n const pathAliases = loadTsConfigPaths(filePath)\n\n if (isPathAliasImport(source, pathAliases)) {\n const resolvedPath = resolvePathAlias(source, pathAliases)\n if (resolvedPath) {\n relativeImports.push({resolvedPath, source})\n }\n }\n }\n }\n }\n\n ts.forEachChild(node, visit)\n }\n\n visit(sourceFile)\n\n return relativeImports\n } catch (error) {\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} ${chalk.yellowBright(\"Failed to extract imports from\")} ${chalk.cyan(filePath)}:`,\n error,\n )\n return []\n }\n }\n\n async function collectAllImports(\n filePath: string,\n visited = new Set<string>(),\n ): Promise<string[]> {\n if (visited.has(filePath)) {\n return []\n }\n\n visited.add(filePath)\n\n const directImports = await extractRelativeImports(filePath)\n\n for (const {resolvedPath} of directImports) {\n await collectAllImports(resolvedPath, visited)\n }\n\n return Array.from(visited).slice(1)\n }\n\n function stripImports(code: string, fileName: string): string[] {\n try {\n const sourceFile = ts.createSourceFile(\n fileName,\n code,\n ts.ScriptTarget.Latest,\n true,\n ts.ScriptKind.TS,\n )\n\n const importRanges: Array<{end: number; start: number}> = []\n\n function visit(node: ts.Node) {\n if (ts.isImportDeclaration(node)) {\n importRanges.push({\n end: node.getEnd(),\n start: node.getFullStart(),\n })\n }\n\n ts.forEachChild(node, visit)\n }\n\n visit(sourceFile)\n\n return importRanges.map((range) => {\n let endPos = range.end\n if (code[endPos] === \"\\n\") {\n endPos++\n }\n return code.slice(range.start, endPos).trim()\n })\n } catch (error) {\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} ${chalk.redBright(\"Failed to strip imports from\")} ${chalk.cyan(fileName)}:`,\n error,\n )\n return []\n }\n }\n\n async function parseAngularDemo(\n filePath: string,\n code: string,\n ): Promise<AngularDemoInfo | null> {\n try {\n const {\n componentClass,\n hasDefaultExport,\n isStandalone,\n selector,\n templateUrl,\n } = parseAngularComponentMeta(filePath, code)\n\n if (!componentClass || !selector) {\n return null\n }\n\n const demoId = componentClass\n const importPath = relative(process.cwd(), filePath).replace(/\\\\/g, \"/\")\n const fileName = basename(filePath)\n const importsWithoutStrip = stripImports(code, filePath)\n\n const sourceCode: SourceCodeData[] = []\n // Use Map for deduplication across all files in this demo\n const aggregatedRules = new Map<string, string>()\n\n const mainSourceEntry = await buildAngularSourceEntry({\n code,\n fileName,\n filePath,\n language: \"angular-ts\",\n })\n sourceCode.push(mainSourceEntry.sourceCodeData)\n if (mainSourceEntry.residualRules) {\n for (const [className, rule] of mainSourceEntry.residualRules) {\n aggregatedRules.set(className, rule)\n }\n }\n\n if (templateUrl) {\n const templateEntry = await maybeBuildTemplateSourceEntry(\n templateUrl,\n filePath,\n )\n if (templateEntry) {\n sourceCode.push(templateEntry.sourceCodeData)\n if (templateEntry.residualRules) {\n for (const [className, rule] of templateEntry.residualRules) {\n aggregatedRules.set(className, rule)\n }\n }\n }\n }\n\n const importedEntries = await buildImportedSourceEntries(filePath)\n for (const entry of importedEntries) {\n sourceCode.push(entry.sourceCodeData)\n if (entry.residualRules) {\n for (const [className, rule] of entry.residualRules) {\n aggregatedRules.set(className, rule)\n }\n }\n }\n\n // Convert aggregated rules to CSS string\n const aggregatedResidualCss =\n aggregatedRules.size > 0\n ? [...aggregatedRules.values()].join(\"\\n\\n\")\n : undefined\n\n if (aggregatedResidualCss) {\n const cssHighlighted = await highlightCode(aggregatedResidualCss, \"css\")\n sourceCode.push({\n fileName: \"styles.css\",\n highlighted: cssHighlighted,\n type: \"residual-css\",\n })\n }\n\n return {\n componentClass,\n filePath: importPath.startsWith(\".\") ? importPath : `./${importPath}`,\n hasDefaultExport,\n id: demoId,\n imports: importsWithoutStrip,\n initialHtml: initialHtml?.[demoId] || undefined,\n isStandalone,\n lastModified: Date.now(),\n selector,\n sourceCode,\n }\n } catch (error) {\n console.error(\n `${chalk.blue.bold(LOG_PREFIX)} Failed to parse Angular demo ${filePath}:`,\n error,\n )\n return null\n }\n }\n\n function parseAngularComponentMeta(\n filePath: string,\n source: string,\n ): {\n componentClass: string\n hasDefaultExport: boolean\n importsFromAst: string[]\n isStandalone: boolean\n selector: string\n templateUrl: string | null\n } {\n const sourceFile = ts.createSourceFile(\n filePath,\n source,\n ts.ScriptTarget.Latest,\n true,\n ts.ScriptKind.TS,\n )\n\n let componentClass = \"\"\n let selector = \"\"\n let isStandalone = true\n let templateUrl: string | null = null\n let hasDefaultExport = false\n const importsFromAst: string[] = []\n\n function visit(node: ts.Node) {\n if (ts.isImportDeclaration(node)) {\n importsFromAst.push(node.getFullText(sourceFile).trim())\n }\n\n if (ts.isClassDeclaration(node)) {\n const decorators = node.modifiers?.filter(ts.isDecorator)\n const componentDecorator = decorators?.find((decorator) => {\n if (!ts.isCallExpression(decorator.expression)) {\n return false\n }\n const expression = decorator.expression.expression\n return ts.isIdentifier(expression) && expression.text === \"Component\"\n })\n\n if (componentDecorator && node.name) {\n componentClass = node.name.text\n\n if (\n ts.isCallExpression(componentDecorator.expression) &&\n componentDecorator.expression.arguments[0] &&\n ts.isObjectLiteralExpression(\n componentDecorator.expression.arguments[0],\n )\n ) {\n const properties =\n componentDecorator.expression.arguments[0].properties\n\n const selectorProp = properties.find(\n (prop) =>\n ts.isPropertyAssignment(prop) &&\n ts.isIdentifier(prop.name) &&\n prop.name.text === \"selector\",\n ) as ts.PropertyAssignment | undefined\n\n if (selectorProp && ts.isStringLiteral(selectorProp.initializer)) {\n selector = selectorProp.initializer.text\n }\n\n const templateUrlProp = properties.find(\n (prop) =>\n ts.isPropertyAssignment(prop) &&\n ts.isIdentifier(prop.name) &&\n prop.name.text === \"templateUrl\",\n ) as ts.PropertyAssignment | undefined\n\n if (templateUrlProp) {\n const init = templateUrlProp.initializer\n if (ts.isStringLiteral(init)) {\n templateUrl = init.text\n } else if (ts.isNoSubstitutionTemplateLiteral(init)) {\n templateUrl = init.text\n }\n }\n\n const standaloneProp = properties.find(\n (prop) =>\n ts.isPropertyAssignment(prop) &&\n ts.isIdentifier(prop.name) &&\n prop.name.text === \"standalone\",\n ) as ts.PropertyAssignment | undefined\n\n if (\n standaloneProp &&\n standaloneProp.initializer.kind === ts.SyntaxKind.FalseKeyword\n ) {\n isStandalone = false\n }\n }\n }\n }\n\n if (ts.isExportAssignment(node) && !node.isExportEquals) {\n hasDefaultExport = true\n }\n\n ts.forEachChild(node, visit)\n }\n\n visit(sourceFile)\n\n return {\n componentClass,\n hasDefaultExport,\n importsFromAst,\n isStandalone,\n selector,\n templateUrl,\n }\n }\n\n interface BuildAngularSourceEntryParams {\n code: string\n fileName: string\n filePath: string\n language: \"angular-ts\" | \"angular-html\"\n }\n\n interface ExtractedSourceCode {\n residualRules?: Map<string, string>\n sourceCodeData: SourceCodeData\n }\n\n async function buildAngularSourceEntry(\n params: BuildAngularSourceEntryParams,\n ): Promise<ExtractedSourceCode> {\n const {code, fileName, filePath, language} = params\n\n const baseResult = await highlightCode(code, language)\n\n let inlineResult: HighlightCodeResult | undefined\n let classesDetected = false\n let residualRules: Map<string, string> | undefined\n\n if (transformTailwindStyles) {\n inlineResult = await highlightCode(code, language, {\n onClassesDetected: (detected) => {\n classesDetected = detected\n },\n onResidualCss: (rules) => {\n residualRules = rules\n },\n })\n }\n\n return {\n residualRules,\n sourceCodeData: {\n fileName,\n filePath,\n highlighted: {\n full: baseResult.full,\n preview: baseResult.preview,\n },\n highlightedInline:\n classesDetected && inlineResult\n ? {\n full: inlineResult.full,\n preview: inlineResult.preview,\n }\n : undefined,\n type: \"file\",\n },\n }\n }\n\n async function maybeBuildTemplateSourceEntry(\n templateUrl: string,\n fromFilePath: string,\n ): Promise<ExtractedSourceCode | null> {\n const templatePath = resolveTemplateFile(templateUrl, fromFilePath)\n if (!existsSync(templatePath)) {\n return null\n }\n\n try {\n const templateCode = await readFile(templatePath, \"utf-8\")\n\n return buildAngularSourceEntry({\n code: templateCode,\n fileName: basename(templatePath),\n filePath: templatePath,\n language: \"angular-html\",\n })\n } catch (error) {\n console.log(\n `${chalk.blue.bold(LOG_PREFIX)} ${chalk.redBright(\"Failed to read template file:\")} ${chalk.cyan(templatePath)}`,\n error,\n )\n return null\n }\n }\n\n async function buildImportedSourceEntries(\n fromFilePath: string,\n ): Promise<ExtractedSourceCode[]> {\n const entries: ExtractedSourceCode[] = []\n const relativeImports = await collectAllImports(fromFilePath)\n\n for (const resolvedPath of relativeImports) {\n try {\n const importedCode = await readFile(resolvedPath, \"utf-8\")\n\n const entry = await buildAngularSourceEntry({\n code: importedCode,\n fileName: basename(resolvedPath),\n filePath: resolvedPath,\n language: \"angular-ts\",\n })\n\n entries.push(entry)\n } catch (error) {\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} ${chalk.yellowBright(\"Failed to process relative import:\")} ${chalk.cyan(resolvedPath)}`,\n )\n }\n }\n\n return entries\n }\n\n function generateRegistryModule(): string {\n const demos = Array.from(demoRegistry.values())\n\n return `// Auto-generated Angular demo registry\nexport const ANGULAR_DEMOS = {\n${demos\n .map(\n (demo) =>\n ` \"${demo.id}\": ${JSON.stringify(\n {\n componentClass: demo.componentClass,\n dimensions: demoDimensionsCache[demo.id],\n filePath: demo.filePath,\n hasDefaultExport: demo.hasDefaultExport,\n id: demo.id,\n imports: demo.imports,\n initialHtml: demo.initialHtml,\n isStandalone: demo.isStandalone,\n lastModified: demo.lastModified,\n selector: demo.selector,\n sourceCode: demo.sourceCode,\n },\n null,\n 4,\n )}`,\n )\n .join(\",\\n\")}\n}\n\nexport function getAngularDemoInfo(demoId) {\n return ANGULAR_DEMOS[demoId] || null\n}`\n }\n\n function isAngularDemoFile(filePath: string): boolean {\n return (\n filePath.includes(\"/demos/\") &&\n (filePath.endsWith(\".ts\") || filePath.endsWith(\"html\"))\n )\n }\n\n function isAngularDemoEntrypoint(filePath: string): boolean {\n return filePath.endsWith(\"-demo.ts\") || filePath.endsWith(\"-demo.html\")\n }\n\n function isCssAsset(filePath: string) {\n return filePath.endsWith(\".css\")\n }\n\n function isRelativeImport(source: string): boolean {\n return source.startsWith(\"./\") || source.startsWith(\"../\")\n }\n\n function isNodeBuiltin(source: string): boolean {\n const NODE_BUILTINS = [\n \"assert\",\n \"buffer\",\n \"child_process\",\n \"cluster\",\n \"crypto\",\n \"dgram\",\n \"dns\",\n \"domain\",\n \"events\",\n \"fs\",\n \"http\",\n \"https\",\n \"net\",\n \"os\",\n \"path\",\n \"punycode\",\n \"querystring\",\n \"readline\",\n \"stream\",\n \"string_decoder\",\n \"timers\",\n \"tls\",\n \"tty\",\n \"url\",\n \"util\",\n \"v8\",\n \"vm\",\n \"zlib\",\n ]\n\n return source.startsWith(\"node:\") || NODE_BUILTINS.includes(source)\n }\n\n function resolveRelativeImport(source: string, fromFile: string): string {\n const fromDir = dirname(fromFile)\n const resolved = resolve(fromDir, source)\n const extensions = [\".ts\", \".js\"]\n\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\n function 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\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\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\n const pattern = new RegExp(\n `^${alias\n .replace(\"*\", \"(.*)\")\n .replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(\"\\\\(\\\\*\\\\)\", \"(.*)\")}$`,\n )\n\n const replacement = resolve(\n resolvedBaseUrl,\n target.replace(\"*\", \"$1\"),\n )\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\n currentDir = dirname(currentDir)\n }\n\n return pathAliases\n }\n\n async function setupAngularWatcher() {\n watcher = watch(routesDir, {\n ignoreInitial: true,\n persistent: true,\n })\n\n watcher.on(\"ready\", () => {\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} Registered ${chalk.green(demoRegistry.size)} demo files. Watching for file changes...`,\n )\n })\n\n watcher.on(\"add\", async (filePath: string) => {\n const fileStats = await stat(filePath).catch(() => undefined)\n if (!fileStats || fileStats.size === 0) {\n console.debug(\"Failed to read file stats\", filePath)\n return\n }\n\n if (isAngularDemoFile(filePath)) {\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} New Angular demo: ${chalk.green(filePath)}`,\n )\n await handleAngularDemoUpdate(filePath)\n triggerRegistryUpdate()\n }\n })\n\n watcher.on(\"unlink\", (filePath: string) => {\n if (isAngularDemoFile(filePath)) {\n const demoEntry = Array.from(demoRegistry.entries()).find(\n ([, info]) => info.filePath === filePath,\n )\n\n if (demoEntry) {\n const [demoId] = demoEntry\n demoRegistry.delete(demoId)\n\n logDev(\n `${chalk.blue.bold(LOG_PREFIX)} Removed demo: ${chalk.red(demoId)}`,\n )\n\n triggerRegistryUpdate()\n }\n }\n })\n }\n\n async function handleAngularDemoUpdate(filePath: string) {\n const code = await readFile(filePath, \"utf-8\")\n const demoInfo = await parseAngularDemo(filePath, code)\n\n if (demoInfo) {\n demoRegistry.set(demoInfo.id, demoInfo)\n }\n }\n\n function triggerRegistryUpdate() {\n if (!devServer) {\n return\n }\n\n const mainModule = devServer.moduleGraph.getModuleById(VIRTUAL_MODULE_ID)\n if (mainModule) {\n devServer.moduleGraph.invalidateModule(mainModule)\n mainModule.lastHMRTimestamp = Date.now()\n devServer.reloadModule(mainModule)\n }\n }\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\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\n const pattern = new RegExp(\n `^${alias\n .replace(\"*\", \"(.*)\")\n .replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(\"\\\\(\\\\*\\\\)\", \"(.*)\")}$`,\n )\n\n const replacement = resolve(\n resolvedBaseUrl,\n target.replace(\"*\", \"$1\"),\n )\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\n if (!resolvedExtends.endsWith(\".json\")) {\n resolvedExtends += \".json\"\n }\n\n if (existsSync(resolvedExtends)) {\n const extendedAliases = loadTsConfigPathsFromFile(resolvedExtends)\n pathAliases.push(...extendedAliases)\n }\n }\n } catch {\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\", \".js\"]\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\n return null\n}\n\nfunction resolveTemplateFile(templateUrl: string, fromFile: string): string {\n const fromDir = dirname(fromFile)\n const resolved = resolve(fromDir, templateUrl)\n\n if (existsSync(resolved)) {\n return resolved\n }\n\n if (!resolved.endsWith(\".html\")) {\n const withHtml = `${resolved}.html`\n if (existsSync(withHtml)) {\n return withHtml\n }\n }\n\n return resolved\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 {join, resolve} from \"node:path\"\nimport prettyMilliseconds from \"pretty-ms\"\nimport type {PluginOption, ResolvedConfig, ViteDevServer} from \"vite\"\n\nimport type {\n KnowledgePageData,\n PageDocProps,\n SiteData,\n} from \"@qualcomm-ui/mdx-common\"\nimport type {QuiPropTypes} from \"@qualcomm-ui/typedoc-common\"\n\nimport {generate} from \"../open-web-ui-knowledge/generate-knowledge\"\n\nimport {\n type CompiledMdxFile,\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\ninterface ExportsState {\n basePath: string\n enabled: boolean\n pages: KnowledgePageData[]\n}\n\n/**\n * TODO: adjust when https://github.com/vitejs/vite/discussions/16358 lands.\n */\nclass PluginState {\n buildCount: number = 0\n config: ResolvedQuiDocsConfig | null = null\n configFilePath: string = \"\"\n docPropsFilePath: string = \"\"\n exports: ExportsState = {basePath: \"\", enabled: false, pages: []}\n indexer!: SearchIndexer\n configLoader: ConfigLoader | null = null\n knowledgeConfig: ResolvedQuiDocsConfig[\"knowledge\"] = undefined\n routesDir!: string\n servers: ViteDevServer[] = []\n timeout: ReturnType<typeof setTimeout> | undefined = undefined\n exportsTimeout: 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 getCwd() {\n return this.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 get siteData(): SiteData & {\n config: Omit<ResolvedQuiDocsConfig, \"filePath\">\n exports: ExportsState\n } {\n const {filePath: _filePath, ...config} =\n this.config ?? ({} as ResolvedQuiDocsConfig)\n return {\n config,\n exports: this.exports,\n navItems: state.indexer.navItems,\n pageDocProps: state.indexer.pageDocProps as unknown as PageDocProps,\n pageMap: state.indexer.pageMap,\n searchIndex: state.indexer.searchIndex,\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.config = config\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.knowledgeConfig = config.knowledge\n this.indexer = new SearchIndexer({\n ...config,\n srcDir: fixPath(resolve(this.cwd, config.appDirectory)),\n typeDocProps: this.resolveDocProps(),\n })\n\n const exportsConfig = config.knowledge?.global?.exports\n const exportsEnabled = exportsConfig?.enabled ?? false\n const exportsPath = exportsConfig?.staticPath ?? \"exports/md\"\n this.exports = {\n basePath: exportsEnabled ? `/${exportsPath}` : \"\",\n enabled: exportsEnabled,\n pages: [],\n }\n }\n\n buildIndex(shouldLog: boolean): CompiledMdxFile[] {\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 const compiledMdxFiles = 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 return compiledMdxFiles\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 onComplete: () => {\n this.servers.forEach((server) =>\n server.ws.send({type: \"full-reload\"}),\n )\n },\n })\n })\n }\n\n async generateExports(publicDir: string): Promise<void> {\n if (!this.exports.enabled || !this.knowledgeConfig?.global) {\n return\n }\n\n const globalConfig = this.knowledgeConfig.global\n const exportsConfig = globalConfig.exports ?? {}\n const exportsPath = exportsConfig.staticPath ?? \"exports/md\"\n const outputPath = join(publicDir, exportsPath)\n\n const startTime = Date.now()\n\n const pageIds = await generate({\n baseUrl: globalConfig.baseUrl,\n clean: true,\n docPropsPath: this.docPropsFilePath || undefined,\n exclude: exportsConfig.exclude ?? globalConfig.exclude,\n extraFiles: exportsConfig.extraFiles ?? globalConfig.extraFiles,\n metadata: exportsConfig.metadata ?? globalConfig.metadata,\n outputMode: \"per-page\",\n outputPath,\n pageTitlePrefix:\n exportsConfig.pageTitlePrefix ?? globalConfig.pageTitlePrefix,\n routeDir: this.routesDir,\n })\n\n this.exports.pages = pageIds\n\n console.debug(\n `${chalk.magenta.bold(`@qualcomm-ui/mdx-vite/docs-plugin:`)} Generated Markdown exports in: ${chalk.blueBright.bold(prettyMilliseconds(Date.now() - startTime))}`,\n )\n }\n\n debouncedGenerateExports(publicDir: string): void {\n if (!this.exports.enabled) {\n return\n }\n clearTimeout(this.exportsTimeout)\n this.exportsTimeout = setTimeout(() => {\n void this.generateExports(publicDir)\n }, 500)\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 let viteConfig: ResolvedConfig\n\n return {\n apply(config, env) {\n return (\n (env.mode === \"development\" && env.command === \"serve\") ||\n (env.mode === \"production\" && env.command === \"build\")\n )\n },\n buildStart: async () => {\n state.buildIndex(state.buildCount > 0)\n state.buildCount++\n\n if (!isDev && state.exports.enabled) {\n const publicDir = viteConfig.publicDir || join(state.getCwd(), \"public\")\n await state.generateExports(publicDir)\n }\n },\n configResolved(resolved) {\n viteConfig = resolved\n },\n configureServer: async (server) => {\n if (!isDev) {\n return\n }\n state.initWatchers(opts?.configFile)\n\n if (state.exports.enabled) {\n const publicDir = join(state.getCwd(), \"public\")\n await state.generateExports(publicDir)\n }\n\n server.watcher.on(\"add\", (path: string) => {\n if (path.endsWith(\".mdx\")) {\n const publicDir = join(state.getCwd(), \"public\")\n state.handleChange({\n onComplete: () => {\n server.ws.send({type: \"full-reload\"})\n state.debouncedGenerateExports(publicDir)\n },\n })\n }\n })\n server.watcher.on(\"unlink\", (path: string) => {\n if (path.endsWith(\".mdx\")) {\n const publicDir = join(state.getCwd(), \"public\")\n state.handleChange({\n onComplete: () => {\n server.ws.send({type: \"full-reload\"})\n state.debouncedGenerateExports(publicDir)\n },\n })\n }\n })\n state.servers.push(server)\n },\n handleHotUpdate: async ({file: updateFile, modules, server}) => {\n if (updateFile.endsWith(\".css\")) {\n return modules\n }\n const file = fixPath(updateFile)\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 if (updateFile.endsWith(\".mdx\")) {\n const files = state.buildIndex(true)\n\n const moduleByFile = server.moduleGraph.getModulesByFile(updateFile)\n if (!moduleByFile?.size) {\n console.debug(\"no module found for file, returning\", updateFile)\n return []\n }\n\n const virtualModule =\n server.moduleGraph.getModuleById(VIRTUAL_MODULE_ID)\n if (virtualModule) {\n // invalidate the module so that it gets re-evaluated on next refresh\n server.moduleGraph.invalidateModule(virtualModule)\n\n // Send the updated site data to the site so that it has the latest\n // state.\n server.ws.send({\n data: state.siteData,\n event: \"qui-docs-plugin:refresh-site-data\",\n type: \"custom\",\n })\n }\n if (files.some((file) => file.metadata.changed.frontmatter)) {\n console.debug(\n \"Frontmatter changed, reloading plugin to reflect changes in the page configuration\",\n )\n if (virtualModule) {\n server.moduleGraph.invalidateModule(virtualModule)\n }\n server.ws.send({type: \"full-reload\"})\n return []\n }\n return virtualModule ? [virtualModule] : []\n }\n }\n return []\n },\n load: (id): string | undefined => {\n if (id === VIRTUAL_MODULE_ID) {\n return `export const siteData = ${JSON.stringify(state.siteData)}`\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", "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 type {Link, Parent} from \"mdast\"\nimport type {MdxJsxAttribute, MdxJsxFlowElement} from \"mdast-util-mdx-jsx\"\nimport {minimatch} from \"minimatch\"\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, relative, resolve} from \"node:path\"\nimport remarkFrontmatter from \"remark-frontmatter\"\nimport remarkMdx from \"remark-mdx\"\nimport remarkParse from \"remark-parse\"\nimport remarkParseFrontmatter from \"remark-parse-frontmatter\"\nimport remarkStringify from \"remark-stringify\"\nimport {type Plugin, unified} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nimport type {KnowledgePageData} from \"@qualcomm-ui/mdx-common\"\nimport type {\n QuiComment,\n QuiCommentDisplayPart,\n} from \"@qualcomm-ui/typedoc-common\"\nimport {kebabCase} from \"@qualcomm-ui/utils/change-case\"\n\nimport {\n getPathnameFromPathSegments,\n getPathSegmentsFromFileName,\n remarkRemoveJsx,\n} from \"../docs-plugin/internal\"\nimport {extractNamesFromAttribute} from \"../docs-plugin/internal/services/mdx-utils\"\n\nimport {loadEnv} from \"./common\"\nimport {loadKnowledgeConfigFromEnv} from \"./load-config-from-env\"\nimport type {WebUiKnowledgeConfig} from \"./types\"\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\ninterface ProcessedPage {\n content: string\n demoFiles: string[]\n frontmatter: Record<string, string>\n title: string\n url: string | undefined\n}\n\ninterface MdxFlowExpression {\n type: \"mdxFlowExpression\"\n value: string\n}\n\n// Pure utility functions (no config dependency)\n\nasync function exists(dirPath: string): Promise<boolean> {\n return access(dirPath)\n .then(() => true)\n .catch(() => false)\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\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 removePreviewLines(code: string): string {\n return code\n .split(\"\\n\")\n .filter((line) => !isPreviewLine(line.trim()))\n .join(\"\\n\")\n}\n\nfunction getIntroLines(projectName?: string, description?: string) {\n const lines: string[] = []\n\n if (projectName) {\n lines.push(`# ${projectName}`)\n }\n\n if (description) {\n lines.push(\"\")\n lines.push(`> ${description}`)\n }\n\n return lines.join(\"\\n\")\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\nfunction extractMetadata(\n metadata: Record<string, string> | undefined,\n): [string, string][] {\n return Object.entries(metadata ?? {})\n}\n\nconst replaceNpmInstallTabs: Plugin = () => {\n return (tree, _file, done) => {\n visit(tree, \"mdxJsxFlowElement\", (node: MdxJsxFlowElement) => {\n if (node?.name === \"NpmInstallTabs\") {\n const packages = node.attributes?.find(\n (attr): attr is MdxJsxAttribute =>\n attr.type === \"mdxJsxAttribute\" && attr.name === \"packages\",\n )\n const packageNames = packages ? extractNamesFromAttribute(packages) : []\n\n Object.assign(node, {\n lang: \"shell\",\n meta: null,\n type: \"code\",\n value: `npm install ${packageNames.join(\" \")}`,\n })\n }\n })\n done()\n }\n}\n\nfunction getPath(obj: Record<string, unknown>, path: string): unknown {\n return path\n .split(\".\")\n .reduce<unknown>(\n (acc, key) =>\n acc && typeof acc === \"object\"\n ? (acc as Record<string, unknown>)[key]\n : undefined,\n obj,\n )\n}\n\nfunction escapeText(value: string): string {\n return value.replace(/\\n/g, \" \")\n}\n\nfunction propsToDefinitionList(props: SimplifiedProp[]): string {\n if (props.length === 0) {\n return \"\"\n }\n\n return props\n .map((prop) => {\n const parts = [`- **${prop.name}** (\\`${escapeText(prop.type)}\\``]\n\n if (prop.defaultValue) {\n parts.push(`, default: \\`${escapeText(prop.defaultValue)}\\``)\n }\n if (prop.required) {\n parts.push(\", required\")\n }\n\n parts.push(\")\")\n\n if (prop.description) {\n parts.push(` - ${escapeText(prop.description)}`)\n }\n\n return parts.join(\"\")\n })\n .join(\"\\n\")\n}\n\nfunction themeDataToJson(data: unknown, cssPropertyName?: string): string {\n if (!data || typeof data !== \"object\") {\n return \"\"\n }\n\n if (cssPropertyName) {\n return JSON.stringify({cssProperty: cssPropertyName, data}, null, 2)\n }\n\n return JSON.stringify(data, null, 2)\n}\n\n/**\n * Generator class that encapsulates all knowledge generation logic with shared\n * config.\n */\nclass KnowledgeGenerator {\n private readonly config: WebUiKnowledgeConfig\n private docProps: DocProps | null = null\n\n constructor(config: WebUiKnowledgeConfig) {\n this.config = config\n }\n\n async run(): Promise<KnowledgePageData[]> {\n const extractedMetadata = extractMetadata(this.config.metadata)\n\n if (this.config.verbose) {\n console.log(`Scanning pages in: ${this.config.routeDir}`)\n if (this.config.exclude?.length) {\n console.log(`Excluding patterns: ${this.config.exclude.join(\", \")}`)\n }\n }\n\n const [docProps, pages] = await Promise.all([\n this.loadDocProps(),\n this.scanPages(),\n ])\n\n this.docProps = docProps\n\n if (pages.length === 0) {\n console.log(\"No pages found.\")\n return []\n }\n\n if (this.config.verbose) {\n console.log(`Found ${pages.length} page(s)`)\n }\n\n const processedPages: ProcessedPage[] = []\n for (const page of pages) {\n try {\n const processed = await this.processMdxPage(page)\n processedPages.push(processed)\n } catch (error) {\n console.error(`Failed to process page: ${page.name}`)\n process.exit(1)\n }\n }\n\n if (this.config.clean) {\n await rm(this.config.outputPath, {force: true, recursive: true}).catch(\n () => {},\n )\n }\n\n if (this.config.outputMode === \"aggregated\") {\n await this.generateAggregatedOutput(processedPages, pages)\n } else {\n await mkdir(this.config.outputPath, {recursive: true}).catch(() => {})\n await this.generatePerPageExports(\n pages,\n processedPages,\n extractedMetadata,\n )\n await this.generateExtraFiles(extractedMetadata)\n }\n\n return pages\n }\n\n private async loadDocProps(): Promise<DocProps | null> {\n const resolvedDocPropsPath = this.config.docPropsPath\n ? (await exists(this.config.docPropsPath))\n ? this.config.docPropsPath\n : resolve(process.cwd(), this.config.docPropsPath)\n : join(dirname(this.config.routeDir), \"doc-props.json\")\n\n if (!(await exists(resolvedDocPropsPath))) {\n if (this.config.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 (this.config.verbose) {\n console.log(`Loaded doc props from: ${resolvedDocPropsPath}`)\n console.log(\n `Found ${Object.keys(docProps.props).length} component types`,\n )\n }\n return docProps\n } catch (error) {\n if (this.config.verbose) {\n console.log(`Error loading doc props: ${error}`)\n }\n return null\n }\n }\n\n private async scanPages(): Promise<KnowledgePageData[]> {\n const components: KnowledgePageData[] = []\n const excludePatterns = this.config.exclude ?? []\n\n const shouldExclude = (absolutePath: string): boolean => {\n if (excludePatterns.length === 0) {\n return false\n }\n const relativePath = relative(this.config.routeDir, absolutePath)\n return excludePatterns.some((pattern) =>\n minimatch(relativePath, pattern, {matchBase: true}),\n )\n }\n\n const scanDirectory = async (dirPath: string): Promise<void> => {\n if (shouldExclude(dirPath)) {\n if (this.config.verbose) {\n console.log(\n `Excluding directory: ${relative(this.config.routeDir, dirPath)}`,\n )\n }\n return\n }\n\n const entries = await readdir(dirPath, {withFileTypes: true})\n const mdxFiles =\n entries.filter(\n (f) =>\n f.name.endsWith(\".mdx\") && !shouldExclude(join(dirPath, f.name)),\n ) ?? []\n\n for (const mdxFile of mdxFiles) {\n const demosFolder = entries.find((f) => f.name === \"demos\")\n const demosFolderPath = demosFolder\n ? join(dirPath, demosFolder.name)\n : undefined\n\n const segments = getPathSegmentsFromFileName(\n join(dirPath, mdxFile.name),\n this.config.routeDir,\n )\n const url = getPathnameFromPathSegments(segments)\n\n components.push({\n demosFolder: demosFolderPath,\n filePath: dirPath,\n id: segments.join(\"-\").trim(),\n mdxFile: join(dirPath, mdxFile.name),\n name: segments.at(-1)!,\n pathname: url,\n url: this.config.baseUrl\n ? new URL(url, this.config.baseUrl).toString()\n : undefined,\n })\n\n if (this.config.verbose) {\n console.log(`Found file: ${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(this.config.routeDir)\n return components\n }\n\n private async collectRelativeImports(\n filePath: string,\n visited: Set<string> = new Set(),\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 (this.config.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 this.collectRelativeImports(\n resolvedPath,\n visited,\n )\n modules.push(...nestedModules)\n }\n } catch (error) {\n if (this.config.verbose) {\n console.log(` Error processing ${normalizedPath}: ${error}`)\n }\n }\n return modules\n }\n\n private 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) => this.convertPropInfo(prop, isPartial)),\n )\n }\n if (props.input?.length) {\n propsInfo.push(\n ...props.input.map((prop) =>\n this.convertPropInfo(prop, isPartial, \"input\"),\n ),\n )\n }\n if (props.output?.length) {\n propsInfo.push(\n ...props.output.map((prop) =>\n this.convertPropInfo(prop, isPartial, \"output\"),\n ),\n )\n }\n\n return propsInfo\n }\n\n private formatComment(comment: QuiComment | null): string {\n if (!comment) {\n return \"\"\n }\n\n const parts: string[] = []\n\n if (comment.summary && comment.summary.length > 0) {\n const summaryText = this.formatCommentParts(comment.summary)\n if (summaryText.trim()) {\n parts.push(summaryText.trim())\n }\n }\n\n if (comment.blockTags && comment.blockTags.length > 0) {\n for (const blockTag of comment.blockTags) {\n const tagContent = this.formatCommentParts(blockTag.content)\n if (tagContent.trim()) {\n const tagName = blockTag.tag.replace(\"@\", \"\")\n\n if (tagName === \"default\" || tagName === \"defaultValue\") {\n continue\n }\n\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\n private 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 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 (codeText.includes(\"\\n\")) {\n return `\\`\\`\\`\\n${codeText}\\n\\`\\`\\``\n } else {\n return codeText\n }\n default:\n // render link text only, but remove certain text altogether\n if (\n this.config.outputMode === \"per-page\" &&\n \"tag\" in part &&\n part.tag === \"@link\" &&\n typeof part.target === \"string\"\n ) {\n if (part.text === \"Learn more\") {\n return \"\"\n }\n }\n return part.text\n }\n })\n .join(\"\")\n .replace(/\\n/g, \" \")\n .replace(/\\s+/g, \" \")\n .trim()\n }\n\n private 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: this.formatComment(propInfo.comment || null),\n propType,\n required: extractRequired(propInfo, isPartial) || undefined,\n }\n }\n\n /**\n * Creates a remark plugin that replaces theme JSX elements with\n * markdown tables containing theme data.\n */\n private async replaceThemeNodes(): Promise<Plugin> {\n let themes: any | null = null\n try {\n // may not be available since this is an optional dependency\n themes = await import(\"@qualcomm-ui/tailwind-plugin/theme\")\n } catch {\n return () => {}\n }\n\n const handlers: Record<string, (node: MdxJsxFlowElement) => unknown> = {\n ColorTable: (node) => {\n const path = this.getAttrExpression(node, \"data\")\n return path && getPath(themes, path)\n },\n FontTable: (node) => {\n const path = this.getAttrExpression(node, \"data\")\n return path && getPath(themes, path)\n },\n ThemePropertyTable: (node) => {\n const path = this.getAttrExpression(node, \"data\")\n const property = this.getAttrExpression(node, \"cssProperty\")\n const data = path && getPath(themes, path)\n return path && property ? {cssPropertyName: property, data} : undefined\n },\n }\n\n return () => (tree, _file, done) => {\n visit(tree, \"mdxJsxFlowElement\", (node: MdxJsxFlowElement) => {\n const handler = node.name && handlers[node.name]\n if (!handler) {\n return\n }\n\n const data = handler(node)\n if (!data) {\n console.warn(`No theme data for ${node.name}`)\n return\n }\n\n let markdownTable: string\n if (\n typeof data === \"object\" &&\n data !== null &&\n \"cssPropertyName\" in data &&\n \"data\" in data\n ) {\n const {cssPropertyName, data: themeData} = data as {\n cssPropertyName: string\n data: unknown\n }\n markdownTable = themeDataToJson(themeData, cssPropertyName)\n } else {\n markdownTable = themeDataToJson(data)\n }\n\n if (!markdownTable) {\n return\n }\n\n Object.assign(node, {\n lang: \"json\",\n meta: null,\n type: \"code\",\n value: markdownTable,\n })\n })\n done()\n }\n }\n\n private getAttrExpression(\n node: MdxJsxFlowElement,\n name: string,\n ): string | null {\n const attr = node.attributes?.find(\n (a): a is MdxJsxAttribute =>\n a.type === \"mdxJsxAttribute\" && a.name === name,\n )\n if (!attr?.value) {\n return null\n }\n if (typeof attr.value === \"string\") {\n return attr.value\n } else if (typeof attr.value === \"object\" && \"value\" in attr.value) {\n return attr.value.value\n }\n return null\n }\n\n /**\n * Creates a remark plugin that transforms relative URLs to absolute URLs.\n */\n private transformRelativeUrls(pageUrl?: string): Plugin {\n const baseUrl = this.config.baseUrl\n return () => (tree) => {\n if (!baseUrl || this.config.outputMode !== \"per-page\") {\n return\n }\n visit(tree, \"link\", (node: Link) => {\n if (node.url.startsWith(\"/\")) {\n node.url = `${baseUrl}${node.url}`\n } else if (node.url.startsWith(\"./#\") && pageUrl) {\n node.url = `${pageUrl}${node.url.slice(2)}`\n }\n })\n }\n }\n\n /**\n * Creates a remark plugin that replaces TypeDocProps JSX elements with\n * markdown tables containing component prop documentation.\n */\n private replaceTypeDocProps(): Plugin {\n return () => (tree, _file, done) => {\n visit(\n tree,\n \"mdxJsxFlowElement\",\n (\n node: MdxJsxFlowElement,\n index: number | undefined,\n parent: Parent | undefined,\n ) => {\n if (node?.name !== \"TypeDocProps\") {\n return\n }\n const nameAttr = node.attributes?.find(\n (attr): attr is MdxJsxAttribute =>\n attr.type === \"mdxJsxAttribute\" && attr.name === \"name\",\n )\n const isPartial = node.attributes?.some(\n (attr): attr is MdxJsxAttribute =>\n attr.type === \"mdxJsxAttribute\" && attr.name === \"partial\",\n )\n if (!this.docProps || !nameAttr) {\n if (parent && index !== undefined) {\n parent.children.splice(index, 1)\n }\n return\n }\n const propsNames = extractNamesFromAttribute(nameAttr)\n if (propsNames.length === 0) {\n if (parent && index !== undefined) {\n parent.children.splice(index, 1)\n }\n return\n }\n const propsName = propsNames[0]\n const componentProps = this.docProps.props[propsName]\n if (!componentProps) {\n if (this.config.verbose) {\n console.log(` TypeDocProps not found: ${propsName}`)\n }\n if (parent && index !== undefined) {\n parent.children.splice(index, 1)\n }\n return\n }\n const propsDoc = this.extractProps(componentProps, Boolean(isPartial))\n if (this.config.verbose) {\n console.log(\n ` Replaced TypeDocProps ${propsName} with API documentation`,\n )\n }\n\n const regularProps = propsDoc.filter((p) => p.propType === undefined)\n const inputs = propsDoc.filter((p) => p.propType === \"input\")\n const outputs = propsDoc.filter((p) => p.propType === \"output\")\n\n const sections: string[] = []\n\n if (regularProps.length > 0) {\n sections.push(propsToDefinitionList(regularProps))\n }\n\n if (inputs.length > 0) {\n sections.push(`**Inputs**\\n\\n${propsToDefinitionList(inputs)}`)\n }\n\n if (outputs.length > 0) {\n sections.push(`**Outputs**\\n\\n${propsToDefinitionList(outputs)}`)\n }\n\n const markdownContent = sections.join(\"\\n\\n\")\n\n if (!markdownContent) {\n if (parent && index !== undefined) {\n parent.children.splice(index, 1)\n }\n return\n }\n\n Object.assign(node, {\n lang: null,\n meta: null,\n type: \"code\",\n value: markdownContent,\n })\n },\n )\n done()\n }\n }\n\n /**\n * Creates a remark plugin that replaces demo JSX elements (QdsDemo, CodeDemo,\n * Demo) with code blocks containing the demo source code from the demos folder.\n */\n private replaceDemos(\n demosFolder: string | undefined,\n demoFiles: string[],\n ): Plugin {\n return () => async (tree) => {\n const promises: Promise<void>[] = []\n\n visit(\n tree,\n \"mdxJsxFlowElement\",\n (\n node: MdxJsxFlowElement,\n index: number | undefined,\n parent: Parent | undefined,\n ) => {\n if (\n !node?.name ||\n ![\"QdsDemo\", \"CodeDemo\", \"Demo\"].includes(node.name)\n ) {\n return\n }\n\n const nameAttr = node.attributes?.find(\n (attr): attr is MdxJsxAttribute =>\n attr.type === \"mdxJsxAttribute\" && attr.name === \"name\",\n )\n\n const nodeAttr = node.attributes?.find(\n (attr): attr is MdxJsxAttribute =>\n attr.type === \"mdxJsxAttribute\" && attr.name === \"node\",\n )\n\n let demoName: string | undefined\n\n if (nameAttr && typeof nameAttr.value === \"string\") {\n demoName = nameAttr.value\n } else if (nodeAttr?.value && typeof nodeAttr.value !== \"string\") {\n const estree = nodeAttr.value.data?.estree\n if (estree?.body?.[0]?.type === \"ExpressionStatement\") {\n const expression = estree.body[0].expression\n if (\n expression.type === \"MemberExpression\" &&\n expression.object.type === \"Identifier\" &&\n expression.object.name === \"Demo\" &&\n expression.property.type === \"Identifier\"\n ) {\n demoName = expression.property.name\n }\n }\n }\n\n if (!demoName) {\n if (parent && index !== undefined) {\n parent.children.splice(index, 1)\n }\n return\n }\n\n promises.push(\n (async () => {\n const kebabName = kebabCase(demoName)\n let filePath = `${kebabName}.tsx`\n\n if (!demosFolder) {\n if (this.config.verbose) {\n console.log(` No demos folder for ${demoName}`)\n }\n if (parent && index !== undefined) {\n parent.children.splice(index, 1)\n }\n return\n }\n\n let demoFilePath = join(demosFolder, filePath)\n let isAngularDemo = false\n\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 if (parent && index !== undefined) {\n parent.children.splice(index, 1)\n }\n return\n }\n }\n\n try {\n const demoCode = await readFile(demoFilePath, \"utf-8\")\n const cleanedCode = removePreviewLines(demoCode)\n\n if (this.config.verbose) {\n console.log(` Replaced demo ${demoName} with source code`)\n }\n\n demoFiles.push(demoFilePath)\n\n Object.assign(node, {\n lang: isAngularDemo ? \"angular-ts\" : \"tsx\",\n meta: null,\n type: \"code\",\n value: cleanedCode,\n })\n } catch (error) {\n if (this.config.verbose) {\n console.log(` Error reading demo ${demoName}: ${error}`)\n }\n if (parent && index !== undefined) {\n parent.children.splice(index, 1)\n }\n }\n })(),\n )\n },\n )\n\n await Promise.all(promises)\n }\n }\n\n private replaceFrontmatterExpressions(\n frontmatter: Record<string, any>,\n ): Plugin {\n return () => (tree) => {\n visit(\n tree,\n \"mdxFlowExpression\",\n (\n node: MdxFlowExpression,\n index: number | undefined,\n parent: Parent | undefined,\n ) => {\n if (\n node.value.trim() !== \"frontmatter.description\" ||\n index === undefined ||\n !parent\n ) {\n return\n }\n\n if (frontmatter.description) {\n parent.children.splice(index, 1, {\n children: [{type: \"text\", value: frontmatter.description}],\n type: \"paragraph\",\n })\n } else {\n parent.children.splice(index, 1)\n }\n },\n )\n\n const root = tree as Parent\n const h1Index = root.children.findIndex((node: any) => {\n if (node.type !== \"heading\" || node.depth !== 1) {\n return false\n }\n return node.children?.some(\n (child: any) =>\n child.type === \"mdxTextExpression\" &&\n child.value?.includes(\"frontmatter\"),\n )\n })\n if (h1Index >= 0) {\n root.children.splice(h1Index, 1)\n }\n }\n }\n\n /**\n * Processes MDX content by transforming JSX elements (TypeDocProps, demos)\n * into markdown, resolving relative links, and cleaning up formatting.\n */\n private async processMdxContent(\n mdxContent: string,\n pageUrl: string | undefined,\n demosFolder: string | undefined,\n frontmatter: Record<string, any>,\n ): Promise<{content: string; demoFiles: string[]}> {\n const demoFiles: string[] = []\n\n const processor = unified()\n .use(remarkParse)\n .use(remarkMdx)\n .use(remarkFrontmatter, [\"yaml\"])\n .use(this.replaceTypeDocProps())\n .use(this.replaceFrontmatterExpressions(frontmatter))\n .use(await this.replaceThemeNodes())\n .use(this.replaceDemos(demosFolder, demoFiles))\n .use(this.transformRelativeUrls(pageUrl))\n .use(remarkStringify)\n\n const processed = await processor.process(mdxContent)\n const processedContent = String(processed).replace(/\\n\\s*\\n\\s*\\n/g, \"\\n\\n\")\n\n return {content: processedContent, demoFiles}\n }\n\n private async processMdxPage(\n pageInfo: KnowledgePageData,\n ): Promise<ProcessedPage> {\n try {\n const mdxContent = await readFile(pageInfo.mdxFile, \"utf-8\")\n if (this.config.verbose) {\n console.log(`Processing page: ${pageInfo.name}`)\n }\n const processor = unified()\n .use(remarkParse)\n .use(remarkMdx)\n .use(replaceNpmInstallTabs)\n .use(remarkFrontmatter, [\"yaml\"])\n .use(remarkParseFrontmatter)\n .use(remarkStringify)\n const parsed = await processor.process(mdxContent)\n const frontmatter = (parsed.data as any)?.frontmatter || {}\n const {content: processedContent, demoFiles} =\n await this.processMdxContent(\n String(parsed),\n pageInfo.url,\n pageInfo.demosFolder,\n frontmatter,\n )\n const removeJsxProcessor = unified()\n .use(remarkParse)\n .use(remarkMdx)\n .use(remarkFrontmatter, [\"yaml\"])\n .use(remarkRemoveJsx)\n .use(remarkStringify)\n const removedJsx = String(\n await removeJsxProcessor.process(processedContent),\n )\n const contentWithoutFrontmatter = removedJsx\n .replace(/^---[\\s\\S]*?---\\n/, \"\")\n .replace(/(^#{1,6} .*\\\\<[^>]+)>/gm, \"$1\\\\>\")\n const title = frontmatter.title || pageInfo.name\n\n return {\n content: contentWithoutFrontmatter.trim(),\n demoFiles,\n frontmatter,\n title,\n url: pageInfo.url,\n }\n } catch (error) {\n console.error(`Error processing component ${pageInfo.name}:`, error)\n throw error\n }\n }\n\n private async generateLlmsTxt(pages: Array<ProcessedPage>): Promise<string> {\n const lines: string[] = [\n getIntroLines(this.config.name, this.config.description),\n ]\n\n lines.push(\"\")\n\n for (const page of pages) {\n const content = page.content.split(\"\\n\").map((line) => {\n if (line.startsWith(\"#\")) {\n return `#${line}`\n }\n return line\n })\n\n if (content.every((line) => !line.trim())) {\n continue\n }\n\n lines.push(`## ${page.title}`)\n lines.push(\"\")\n\n lines.push(content.join(\"\\n\"))\n lines.push(\"\")\n }\n\n return lines.join(\"\\n\")\n }\n\n private async generateAggregatedOutput(\n processedPages: ProcessedPage[],\n pages: KnowledgePageData[],\n ): Promise<void> {\n const llmsTxtContent = await this.generateLlmsTxt(processedPages)\n await mkdir(dirname(this.config.outputPath), {recursive: true}).catch(\n () => {},\n )\n await writeFile(this.config.outputPath, llmsTxtContent, \"utf-8\")\n const outputStats = await stat(this.config.outputPath)\n const outputSizeKb = (outputStats.size / 1024).toFixed(1)\n console.log(\n `Generated ${this.config.outputPath} with ${pages.length} files(s) at: ${this.config.outputPath}`,\n )\n console.log(`File size: ${outputSizeKb} KB`)\n }\n\n private async generateExtraFiles(\n metadata: [string, string][],\n ): Promise<void> {\n const extraFiles = this.config.extraFiles ?? []\n if (extraFiles.length === 0) {\n return\n }\n\n let totalSize = 0\n await Promise.all(\n extraFiles.map(async (extraFile) => {\n let contents = extraFile.contents\n if (extraFile.processAsMdx) {\n const removeJsxProcessor = unified()\n .use(remarkParse)\n .use(remarkMdx)\n .use(remarkFrontmatter, [\"yaml\"])\n .use(remarkRemoveJsx)\n .use(this.transformRelativeUrls())\n .use(remarkStringify)\n\n contents = String(await removeJsxProcessor.process(contents))\n }\n\n const lines: string[] = []\n if (metadata.length) {\n lines.push(\"---\")\n for (const [key, value] of metadata) {\n lines.push(`${key}: ${value}`)\n }\n lines.push(\"---\")\n lines.push(\"\")\n }\n\n if (extraFile.title) {\n lines.push(`# ${extraFile.title}`)\n lines.push(\"\")\n }\n lines.push(contents)\n lines.push(\"\")\n\n const outfile = `${resolve(this.config.outputPath)}/${kebabCase(extraFile.id)}.md`\n await writeFile(outfile, lines.join(\"\\n\"), \"utf-8\")\n const stats = await stat(outfile)\n totalSize += stats.size / 1024\n }),\n )\n\n console.log(\n `Generated ${extraFiles.length} extra file(s) (${totalSize.toFixed(1)} KB)`,\n )\n }\n\n private async generatePerPageExports(\n pages: KnowledgePageData[],\n processedPages: ProcessedPage[],\n metadata: [string, string][],\n ): Promise<void> {\n await mkdir(dirname(this.config.outputPath), {recursive: true}).catch(\n () => {},\n )\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 // Remove duplicate h1 if content starts with the same title\n content = content.replace(\n new RegExp(`^# ${processedPage.title}\\\\n+`, \"\"),\n \"\",\n )\n if (this.config.pageTitlePrefix) {\n content = content.replace(\n `# ${page.name}`,\n `# ${this.config.pageTitlePrefix} ${page.name}`,\n )\n page.name = `${this.config.pageTitlePrefix} ${page.name}`\n }\n lines.push(content)\n lines.push(\"\")\n\n if (processedPage.demoFiles.length > 0) {\n if (this.config.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 this.collectRelativeImports(\n demoFile,\n new Set(),\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 (this.config.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(this.config.outputPath)}/${kebabCase(page.id || 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} files(s) in ${this.config.outputPath}`)\n console.log(`Folder size: ${totalSize.toFixed(1)} KB`)\n }\n}\n\n/**\n * Generates knowledge documentation from MDX files.\n * Returns an array of pages that were generated.\n */\nexport async function generate(\n config: WebUiKnowledgeConfig,\n): Promise<KnowledgePageData[]> {\n const generator = new KnowledgeGenerator(config)\n return generator.run()\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 \"Glob patterns to exclude (e.g., **/internal/**, guide/drafts/*)\",\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 {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 KnowledgeConfig,\n KnowledgeExportsConfig,\n KnowledgeExtraFile,\n KnowledgeIntegrationConfig,\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\nconst knowledgeExtraFileSchema = implement<KnowledgeExtraFile>().with({\n contents: z.string(),\n id: z.string(),\n processAsMdx: z.boolean().optional(),\n title: z.string().optional(),\n})\n\nconst knowledgeExportsSchema = implement<KnowledgeExportsConfig>().with({\n enabled: z.boolean().optional(),\n exclude: z.array(z.string()).optional(),\n extraFiles: z.array(knowledgeExtraFileSchema).optional(),\n metadata: z.record(z.string(), z.string()).optional(),\n pageTitlePrefix: z.string().optional(),\n staticPath: z.string().optional(),\n})\n\nconst knowledgeIntegrationSchema = implement<KnowledgeIntegrationConfig>().with(\n {\n baseUrl: z.string().optional(),\n description: z.string().optional(),\n exclude: z.array(z.string()).optional(),\n exports: knowledgeExportsSchema.optional(),\n extraFiles: z.array(knowledgeExtraFileSchema).optional(),\n metadata: z.record(z.string(), z.string()).optional(),\n name: z.string().optional(),\n outputMode: z\n .union([z.literal(\"per-page\"), z.literal(\"aggregated\")])\n .optional(),\n outputPath: z.string().optional(),\n pageTitlePrefix: z.string().optional(),\n },\n)\n\nconst knowledgeConfigSchema = implement<KnowledgeConfig>().with({\n global: knowledgeIntegrationSchema.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 knowledge: knowledgeConfigSchema.optional(),\n navConfig: z.array(z.union([routeMetaSchema, navMetaSchema])).optional(),\n pageDirectory: z.string().optional(),\n pageTimestampMetadata: z\n .union([\n z.literal(\"off\"),\n z.literal(\"timestamp\"),\n z.literal(\"user-and-timestamp\"),\n ])\n .optional(),\n routingStrategy: z.union([z.literal(\"vite-generouted\"), z.any()]).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.ZodNullable<z.ZodOptional<z.ZodType<Model[key]>>>\n : z.ZodOptional<z.ZodType<Model[key]>>\n : null extends Model[key]\n ? z.ZodNullable<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 description: z.string().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 updatedBy: z.string().optional(),\n updatedOn: z.string().optional(),\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 type CompiledMdxFile,\n type CompiledMdxFileMetadata,\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 this.config.pageTimestampMetadata,\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 description: frontmatter.description,\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 updatedBy: frontmatter.updatedBy,\n updatedOn: frontmatter.updatedOn,\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): CompiledMdxFile {\n const {cached, fileContents, frontmatter} =\n this.fileCache.readFile(filePath)\n\n const metadata: CompiledMdxFileMetadata = {\n changed: {},\n filePath,\n }\n\n let previousPage: IndexedPage | undefined = undefined\n\n if (!cached) {\n const previousData = this.fileCache.readCache(filePath)\n if (previousData) {\n const cachedFm = JSON.stringify(previousData.frontmatter)\n const currentFm = JSON.stringify(frontmatter)\n previousPage = previousData.page\n if (cachedFm !== currentFm) {\n metadata.changed.frontmatter = true\n }\n }\n }\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 {metadata, pageSections: [defaultSection]}\n }\n\n const {sections, toc} = indexedPage\n\n if (previousPage) {\n for (let i = 0; i < toc.length; i++) {\n const previousHeading = previousPage.toc[i]\n const currentHeading = toc[i]\n if (previousHeading?.id !== currentHeading.id) {\n metadata.changed.toc = true\n break\n }\n }\n }\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 if (!cached) {\n this.fileCache.updateCache(filePath, fileContents, {\n frontmatter,\n page: indexedPage,\n pageDocProps: docProps,\n pageDocPropSections: docPropSections,\n })\n }\n\n // omit entries from pages that are explicitly omitted from the index.\n if (frontmatter.hideFromSearch) {\n return {metadata, pageSections: [defaultSection]}\n }\n\n if (!sections.length && !docPropSections.length) {\n return {metadata, pageSections: [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 {metadata, pageSections: 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(\n inputFileGlob: string[],\n logWarnings: boolean = true,\n ): CompiledMdxFile[] {\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 compiledFiles = mdxFileGlob.map((file) => this.compileMdxFile(file))\n\n const mdxIndex = compiledFiles\n .map((fileData) => fileData.pageSections)\n .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 return compiledFiles\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\"\nimport {extractNamesFromAttribute} from \"../mdx-utils\"\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 /**\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 ? extractNamesFromAttribute(omitFromAttr)\n : undefined\n\n if (nameAttr) {\n const names = 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 type {MdxJsxAttribute} from \"mdast-util-mdx-jsx\"\n\nexport function 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 (element?.type === \"Literal\" && typeof element.value === \"string\") {\n names.push(element.value)\n }\n }\n return names\n }\n\n // Handle single string expression\n if (expression.type === \"Literal\" && typeof expression.value === \"string\") {\n return [expression.value]\n }\n }\n\n return []\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 {execSync} from \"node:child_process\"\nimport {createHash} from \"node:crypto\"\nimport {readFileSync} from \"node:fs\"\nimport {relative} 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 {PageFrontmatter} from \"@qualcomm-ui/mdx-common\"\nimport type {QuiPropTypes} from \"@qualcomm-ui/typedoc-common\"\n\nimport type {PageTimestampMetadataMode} from \"../../../types\"\nimport {frontmatterSchema} from \"../../utils\"\n\nimport type {IndexedPage, IndexedSection} from \"./markdown.types\"\n\nexport interface GitMetadata {\n updatedBy?: string\n updatedOn?: string\n}\n\nfunction getRepoRoot(): string {\n return execSync(\"git rev-parse --show-toplevel\", {\n encoding: \"utf-8\",\n }).trim()\n}\n\n/**\n * Gets the last git commit metadata for a file.\n * Returns undefined values if the file is not tracked by git or if git is\n * unavailable.\n */\nexport function getGitMetadata(\n filePath: string,\n mode: PageTimestampMetadataMode,\n): GitMetadata {\n if (mode === \"off\") {\n return {}\n }\n\n try {\n const repoRoot = getRepoRoot()\n const relativePath = relative(repoRoot, filePath)\n const format = mode === \"user-and-timestamp\" ? \"%cI%n%aN\" : \"%cI\"\n const result = execSync(\n `git log -1 --format=${format} -- \"${relativePath}\"`,\n {\n encoding: \"utf-8\",\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n },\n ).trim()\n\n if (!result) {\n return {}\n }\n\n if (mode === \"user-and-timestamp\") {\n const [updatedOn, updatedBy] = result.split(\"\\n\")\n return {updatedBy, updatedOn}\n }\n\n return {updatedOn: result}\n } catch {\n return {}\n }\n}\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(\n public enabled: boolean,\n public pageTimestampMetadata: PageTimestampMetadataMode = \"off\",\n ) {}\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 readCache(filePath: string): PageCache | null {\n return this.mdxCache[filePath] || null\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 // In dev mode, only fetch git metadata for new files (not in cache).\n // For file updates, reuse cached git metadata to avoid repeated git calls.\n // In production mode, always fetch fresh git metadata.\n const existingCache = this.mdxCache[filepath]\n const shouldFetchGitMetadata = !this.enabled || !existingCache\n\n if (shouldFetchGitMetadata) {\n const gitMetadata = getGitMetadata(filepath, this.pageTimestampMetadata)\n if (!frontmatter.updatedOn && gitMetadata.updatedOn) {\n frontmatter.updatedOn = gitMetadata.updatedOn\n }\n if (!frontmatter.updatedBy && gitMetadata.updatedBy) {\n frontmatter.updatedBy = gitMetadata.updatedBy\n }\n } else if (!cached && existingCache) {\n // Dev mode cache miss (file updated) - reuse git metadata from previous cache\n if (!frontmatter.updatedOn && existingCache.frontmatter.updatedOn) {\n frontmatter.updatedOn = existingCache.frontmatter.updatedOn\n }\n if (!frontmatter.updatedBy && existingCache.frontmatter.updatedBy) {\n frontmatter.updatedBy = existingCache.frontmatter.updatedBy\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\"\nimport {remarkFrontmatterInterpolation} from \"../../../remark/remark-frontmatter-interpolation\"\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(remarkFrontmatterInterpolation, frontmatter)\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 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 {Parent, Root, Text} from \"mdast\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nimport type {PageFrontmatter} from \"@qualcomm-ui/mdx-common\"\n\ninterface MdxExpression {\n type: \"mdxFlowExpression\" | \"mdxTextExpression\"\n value: string\n}\n\nconst FRONTMATTER_PATTERN = /^\\s*frontmatter\\.(\\w+)\\s*$/\n\nfunction isMdxExpression(node: unknown): node is MdxExpression {\n const n = node as {type?: string; value?: unknown}\n return (\n (n.type === \"mdxFlowExpression\" || n.type === \"mdxTextExpression\") &&\n typeof n.value === \"string\"\n )\n}\n\n/**\n * Replaces `{frontmatter.*}` expressions with their actual values from the\n * frontmatter object. This is safer than string replacement as it operates\n * on the AST and won't accidentally match text in code blocks or examples.\n */\nexport const remarkFrontmatterInterpolation: Plugin<[PageFrontmatter], Root> = (\n frontmatter,\n) => {\n return (tree) => {\n visit(tree, (node, index, parent) => {\n if (!isMdxExpression(node) || index === undefined || !parent) {\n return\n }\n\n const match = node.value.match(FRONTMATTER_PATTERN)\n if (!match) {\n return\n }\n\n const key = match[1] as keyof PageFrontmatter\n const value = frontmatter[key]\n\n if (typeof value === \"string\" || typeof value === \"number\") {\n const textNode: Text = {\n type: \"text\",\n value: String(value),\n }\n ;(parent as Parent).children[index] = textNode\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 {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 {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\"\nimport {capitalCase} from \"@qualcomm-ui/utils/change-case\"\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 {join} from \"node:path\"\n\nimport {capitalCase} from \"@qualcomm-ui/utils/change-case\"\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 {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", "// 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 {\n transformerNotationDiff,\n transformerNotationErrorLevel,\n transformerNotationFocus,\n transformerNotationHighlight,\n transformerNotationWordHighlight,\n transformerRemoveNotationEscape,\n transformerRenderIndentGuides,\n} from \"@shikijs/transformers\"\nimport {merge} from \"lodash-es\"\nimport type {ShikiTransformer} from \"shiki\"\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 {\n remarkAlerts,\n remarkCodeTabs,\n remarkFrontmatterDescription,\n remarkFrontmatterTitle,\n remarkSpoilers,\n} from \"./remark\"\nimport {transformerCodeAttribute, transformerNotationHidden} from \"./shiki\"\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\nexport function getShikiTransformers(): ShikiTransformer[] {\n return [\n transformerNotationDiff(),\n transformerNotationFocus(),\n transformerNotationHighlight(),\n transformerNotationWordHighlight(),\n transformerNotationErrorLevel(),\n transformerNotationHidden(),\n transformerRenderIndentGuides(),\n transformerRemoveNotationEscape(),\n ]\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, {enforce: \"pre\"}],\n [\n rehypeSlug,\n {allowedHeadings: config.headings} satisfies RehypeSlugOptions,\n ],\n rehypeSectionize,\n [\n rehypeShiki,\n merge(\n {\n defaultColor: \"light-dark()\",\n themes: {\n dark: quiCustomDarkTheme,\n light: \"github-light-high-contrast\",\n },\n transformers: [...getShikiTransformers(), transformerCodeAttribute()],\n } satisfies RehypeShikiOptions,\n options.rehypeShikiOptions,\n ),\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 remarkFrontmatterTitle,\n remarkFrontmatterDescription,\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 *\n * @example\n * ```angular-html tabs=\"demo\" label=\"HTML\"\n * <div class=\"w-72\" q-text-input [invalid]=\"!value()\" [(ngModel)]=\"value\">\n * <label q-text-input-label>Label</label>\n * <input placeholder=\"Enter a value\" q-text-input-input />\n * <div q-text-input-error-text>You must enter a value</div>\n * </div>\n * ```\n *\n * ```angular-ts tabs=\"demo\" label=\"TS\"\n * @Component()\n * export class DemoComponent {\n * readonly value = signal(\"\")\n * }\n * ```\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 {Parent, Root} from \"mdast\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\ninterface MdxFlowExpression {\n type: \"mdxFlowExpression\"\n value: string\n}\n\n/**\n * Wraps standalone `{frontmatter.description}` expressions in a\n * `<p class=\"mdx\">` element for styling purposes.\n */\nexport const remarkFrontmatterDescription: Plugin<[], Root> = () => {\n return (tree) => {\n visit(\n tree,\n \"mdxFlowExpression\",\n (\n node: MdxFlowExpression,\n index: number | undefined,\n parent: Parent | undefined,\n ) => {\n if (\n node.value.trim() !== \"frontmatter.description\" ||\n index === undefined ||\n !parent\n ) {\n return\n }\n\n const wrappedNode = {\n attributes: [\n {\n name: \"className\",\n type: \"mdxJsxAttribute\",\n value: \"mdx qui-docs__page-description\",\n },\n ],\n children: [node],\n name: \"p\",\n type: \"mdxJsxFlowElement\",\n }\n\n parent.children[index] = wrappedNode as any\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, Parent, Root} from \"mdast\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\ninterface MdxTextExpression {\n type: \"mdxTextExpression\"\n value: string\n}\n\nfunction isMdxTextExpression(node: unknown): node is MdxTextExpression {\n const n = node as {type?: string; value?: unknown}\n return n.type === \"mdxTextExpression\" && typeof n.value === \"string\"\n}\n\n/**\n * Apply data-page-title attribute to heading elements containing\n * `{frontmatter.title}`. We use this attribute to prevent the main title from\n * rendering twice, as it's organized into a separate page heading for layout\n * purposes.\n */\nexport const remarkFrontmatterTitle: Plugin<[], Root> = () => {\n return (tree) => {\n visit(\n tree,\n \"heading\",\n (node: Heading, index, parent: Parent | undefined) => {\n if (index === undefined || !parent) {\n return\n }\n\n const hasFrontmatterTitle = node.children.some(\n (child) =>\n isMdxTextExpression(child) &&\n child.value.trim() === \"frontmatter.title\",\n )\n\n if (!hasFrontmatterTitle) {\n return\n }\n\n const wrappedNode = {\n attributes: [\n {\n name: \"data-page-title\",\n type: \"mdxJsxAttribute\",\n value: \"\",\n },\n ],\n children: node.children,\n name: `h${node.depth}`,\n type: \"mdxJsxFlowElement\",\n }\n\n parent.children[index] = wrappedNode as (typeof parent.children)[number]\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\nexport function removeCodeAnnotations(code: string): string {\n const hideAnnotationRegex = /\\/\\/\\s*\\[!code\\s+hide(?::\\d+)?\\]/\n const lineAnnotationRegex = /\\/\\/\\s*\\[!code\\s*(?:\\S.*)?\\]/\n const jsxBlockAnnotationRegex = /\\{\\s*\\/\\*\\s*\\[!code(?:\\s+\\S+)?\\]\\s*\\*\\/\\s*\\}/\n const htmlAnnotationRegex = /<!--\\s*\\[!code(?:\\s+\\S+)?\\]\\s*-->/\n const blockAnnotationRegex = /\\/\\*\\s*\\[!code(?:\\s+\\S+)?\\]\\s*\\*\\/\\s*/\n const inlineIncrementRegex = /(?:\\/\\/\\s*)?\\[!code \\+\\+\\]/\n\n function stripAnnotations(line: string): {\n hasHideAnnotation: boolean\n processed: string\n touched: boolean\n } {\n let processed = line\n let touched = false\n const hasHideAnnotation = hideAnnotationRegex.test(line)\n\n const patterns = [\n inlineIncrementRegex,\n jsxBlockAnnotationRegex,\n htmlAnnotationRegex,\n blockAnnotationRegex,\n lineAnnotationRegex,\n ]\n\n for (const pattern of patterns) {\n const next = processed.replace(pattern, \"\")\n if (next !== processed) {\n touched = true\n processed = next\n }\n }\n\n return {hasHideAnnotation, processed, touched}\n }\n\n return code\n .split(\"\\n\")\n .map(stripAnnotations)\n .filter(({hasHideAnnotation, processed, touched}) => {\n if (hasHideAnnotation) {\n return false\n }\n\n const processedIsBlank = !processed.trim()\n if (touched && processedIsBlank) {\n return false\n }\n\n return true\n })\n .map(({processed}) => processed)\n .join(\"\\n\")\n}\n\nexport function extractPreviewFromHighlightedHtml(\n highlightedHtml: string,\n): string | null {\n const preMatch = highlightedHtml.match(/<pre((?:\\s+[\\w-]+=\"[^\"]*\")*)>/)\n const codeMatch = highlightedHtml.match(/<code([^>]*)>(.*?)<\\/code>/s)\n\n if (!preMatch || !codeMatch) {\n return null\n }\n const codeContent = codeMatch[2]\n const parts = codeContent.split(/<span class=\"line/)\n const previewLineParts = parts\n .slice(1)\n .filter((part) => part.includes('data-preview-line=\"true\"'))\n\n // strip indentation\n const indents = previewLineParts.map((part) => {\n const indentMatches =\n part.match(/<span class=\"indent\">(.+?)<\\/span>/g) || []\n let total = 0\n for (const match of indentMatches) {\n const content = match.match(/<span class=\"indent\">(.+?)<\\/span>/)\n if (content) {\n total += content[1].length\n } else {\n break\n }\n }\n return total\n })\n\n const minIndent = Math.min(...indents.filter((n) => n > 0))\n const previewLines = previewLineParts.map((part) => {\n let processed = `<span class=\"line${part}`\n let remaining = minIndent\n while (remaining > 0 && processed.includes('<span class=\"indent\">')) {\n const before = processed\n processed = processed.replace(\n /<span class=\"indent\">(.+?)<\\/span>/,\n (match, spaces) => {\n if (spaces.length <= remaining) {\n remaining -= spaces.length\n return \"\"\n } else {\n const kept = spaces.substring(remaining)\n remaining = 0\n return `<span class=\"indent\">${kept}</span>`\n }\n },\n )\n if (before === processed) {\n break\n }\n }\n return processed\n })\n return `<pre${preMatch[1]}><code${codeMatch[1]}>${previewLines.join(\"\")}</code></pre>`\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {ShikiTransformer} from \"shiki\"\n\nimport {removeCodeAnnotations} from \"./utils\"\n\nexport interface TransformerCodeAttributeOptions {\n /**\n * The name of the attribute to add to the pre element. Supply as `null` to\n * disable.\n *\n * @default 'data-code'\n */\n attributeName?: string | null\n\n /**\n * Custom formatter for the source code.\n */\n formatter?: (code: string) => string\n\n /**\n * Callback fired when file processing is complete.\n */\n onComplete?: (codeWithoutSnippets: string) => void\n}\n\n/**\n * Adds a `data-code` attribute to the `<pre>` element with the code contents,\n * removing any code annotations and unused lines from transformers like\n * `transformerNotationDiff`.\n */\nexport function transformerCodeAttribute(\n opts: TransformerCodeAttributeOptions = {attributeName: \"data-code\"},\n): ShikiTransformer {\n return {\n enforce: \"post\",\n name: \"shiki-transformer-code-attribute\",\n pre(node) {\n const strippedSource = removeCodeAnnotations(this.source)\n const formattedSource = opts.formatter?.(strippedSource) ?? strippedSource\n if (opts.attributeName !== null) {\n node.properties[opts.attributeName ?? \"data-code\"] = formattedSource\n }\n opts.onComplete?.(formattedSource)\n },\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {ShikiTransformer} from \"shiki\"\n\n/**\n * Use `[!code hide]` notation in code to mark lines as hidden.\n */\nexport function transformerNotationHidden(): ShikiTransformer {\n return {\n name: \"shiki-transformer-notation-hidden\",\n preprocess(code) {\n const lines = code.split(\"\\n\")\n const resultLines: string[] = []\n let hideNextCount = 0\n\n for (const rawLine of lines) {\n const line = rawLine\n const match = line.match(/\\[!code\\s+hide(?::(\\d+))?\\]/)\n\n if (match) {\n const before = line.slice(0, match.index ?? 0)\n const after = line.slice((match.index ?? 0) + match[0].length)\n\n const count = match[1] ? Number(match[1]) : 1\n const validCount = Number.isFinite(count) && count > 0 ? count : 0\n\n const beforeIsOnlyCommentOrWhitespace =\n before.trim() === \"\" || /^[\\s/]*$/.test(before)\n const afterIsEmpty = after.trim() === \"\"\n\n const markerIsStandalone =\n beforeIsOnlyCommentOrWhitespace && afterIsEmpty\n\n if (markerIsStandalone) {\n hideNextCount += validCount\n continue\n }\n\n // inline marker \u2192 hide this line only\n continue\n }\n\n if (hideNextCount > 0) {\n hideNextCount -= 1\n continue\n }\n\n resultLines.push(line)\n }\n\n return resultLines.join(\"\\n\").trim()\n },\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {ShikiTransformer} from \"shiki\"\n\nimport {dedent} from \"@qualcomm-ui/utils/dedent\"\n\nimport {removeCodeAnnotations} from \"./utils\"\n\nexport type PreviewDisplayMode = \"only-preview\" | \"full-code\"\n\nexport interface PreviewBlockTransformerOptions {\n /**\n * The name of the attribute to add to the pre element. Supply as `null` to\n * disable.\n *\n * @default 'data-preview'\n */\n attributeName?: string | null\n\n /**\n * @option 'full-code': keep the full code (with preview markers removed) as the rendered snippet.\n * @option 'preview-only': render only the extracted preview block as the snippet\n *\n * In all cases the preview block is extracted and attached to `data-preview`.\n *\n * @default 'full-code'\n */\n displayMode?: PreviewDisplayMode\n\n /**\n * Callback fired when file processing is complete.\n */\n onComplete?: (extractedPreview: string | null) => void\n}\n\nexport function 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\nexport function transformerPreviewBlock(\n options: PreviewBlockTransformerOptions = {\n displayMode: \"full-code\",\n },\n): ShikiTransformer {\n let previewContent: string | null = null\n let previewStartLine = -1\n let previewEndLine = -1\n let currentLine = 0\n\n return {\n enforce: \"post\",\n line(node) {\n if (currentLine >= previewStartLine && currentLine <= previewEndLine) {\n node.properties[\"data-preview-line\"] = \"true\"\n }\n currentLine++\n },\n name: \"transformer-preview-block\",\n pre(node) {\n const content = previewContent\n ? removeCodeAnnotations(previewContent)\n : null\n if (content && options.attributeName != null) {\n node.properties[options.attributeName] = content\n }\n options.onComplete?.(content || null)\n },\n preprocess(code) {\n previewContent = null\n currentLine = 0\n previewStartLine = -1\n previewEndLine = -1\n\n const lines = code.split(\"\\n\")\n const resultLines: string[] = []\n const previewLines: string[] = []\n let inPreview = false\n let foundPreview = false\n let outputLineIndex = 0\n\n for (const line of lines) {\n const trimmed = line.trim()\n if (isPreviewLine(trimmed)) {\n if (!inPreview) {\n inPreview = true\n foundPreview = true\n previewStartLine = outputLineIndex\n } else {\n inPreview = false\n previewEndLine = outputLineIndex - 1\n }\n continue\n }\n resultLines.push(line)\n if (inPreview) {\n previewLines.push(line)\n }\n outputLineIndex++\n }\n\n if (foundPreview) {\n previewContent = dedent(previewLines.join(\"\\n\").trim())\n if (options.displayMode === \"only-preview\") {\n return previewContent\n }\n }\n return resultLines.join(\"\\n\").trim()\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, Root, Text} from \"hast\"\nimport {fromHtml} from \"hast-util-from-html\"\nimport {toHtml} from \"hast-util-to-html\"\nimport {readFile} from \"node:fs/promises\"\nimport postcss, {type Rule} from \"postcss\"\nimport selectorParser from \"postcss-selector-parser\"\nimport type {ShikiTransformer} from \"shiki\"\nimport {compile} from \"tailwindcss\"\nimport {visit} from \"unist-util-visit\"\n\nimport {camelCase} from \"@qualcomm-ui/utils/change-case\"\n\ndeclare const createRequire: NodeRequire\n\nasync function loadStylesheetContent(id: string): Promise<string> {\n const resolveId = id === \"tailwindcss\" ? \"tailwindcss/index.css\" : id\n\n let resolvedPath: string\n if (typeof createRequire !== \"undefined\") {\n resolvedPath = createRequire(import.meta.url).resolve(resolveId)\n } else {\n const createRequire = await import(\"node:module\").then(\n (module) => module.createRequire,\n )\n resolvedPath = createRequire(import.meta.url).resolve(resolveId)\n }\n return readFile(resolvedPath, \"utf-8\")\n}\n\nfunction getClassValue(node: Element): string | null {\n const val = node.properties?.className ?? node.properties?.class\n if (!val) {\n return null\n }\n return Array.isArray(val) ? val.join(\" \") : String(val)\n}\n\n/**\n * Extract class names from the text content of a HAST tree.\n * Looks for string literals that could be Tailwind class names.\n */\nexport function extractClassesFromHast(tree: Root): string[] {\n const classes = new Set<string>()\n const stringLiteralPattern = /[\"'`]([^\"'`]+)[\"'`]/g\n\n visit(tree, \"text\", (node: Text) => {\n const text = node.value\n let match\n while ((match = stringLiteralPattern.exec(text)) !== null) {\n const content = match[1]\n const tokens = content.split(/\\s+/).filter(Boolean)\n for (const token of tokens) {\n classes.add(token)\n }\n }\n })\n\n return [...classes]\n}\n\nexport function extractClasses(source: string): string[] {\n const tree = fromHtml(source, {fragment: true})\n const classes = new Set<string>()\n\n visit(tree, \"element\", (node: Element) => {\n const value = getClassValue(node)\n if (value) {\n classes.add(value)\n }\n })\n\n return classes\n .values()\n .toArray()\n .map((value) => value.split(\" \"))\n .flat()\n}\n\n/**\n * Create a fresh Tailwind compiler for each transformation.\n * Note: Tailwind v4's compiler.build() is incremental and accumulates\n * all candidates across calls. We must create a fresh compiler each time\n * to avoid CSS from one demo leaking into another.\n */\nasync function createCompiler(styles: string) {\n return compile(styles, {\n loadStylesheet: async (id: string, base: string) => {\n const content = await loadStylesheetContent(id)\n return {\n base,\n content,\n path: `virtual:${id}`,\n }\n },\n })\n}\n\n/**\n * Extract CSS custom property definitions from compiled CSS.\n * Looks in :root and :host selectors within @layer theme.\n */\nfunction extractCssVariables(css: string): Map<string, string> {\n const variables = new Map<string, string>()\n const root = postcss.parse(css)\n\n root.walkAtRules(\"layer\", (atRule) => {\n if (atRule.params !== \"theme\") {\n return\n }\n\n atRule.walkRules(\":root, :host\", (rule) => {\n rule.walkDecls((decl) => {\n if (decl.prop.startsWith(\"--\")) {\n variables.set(decl.prop, decl.value)\n }\n })\n })\n })\n\n return variables\n}\n\n/**\n * Evaluate a calc() expression with resolved numeric values.\n * Handles expressions like \"0.25rem * 4\" -> \"1rem\" or \"1.25 / 0.875\" -> \"1.4286\"\n */\nfunction evaluateCalc(expression: string): string | null {\n const expr = expression.trim()\n\n // Pattern 1: number+unit operator number (e.g., \"0.25rem * 4\")\n const withUnitFirst = expr.match(\n /^([\\d.]+)(rem|px|em|%|vh|vw)\\s*([*/+-])\\s*([\\d.]+)$/,\n )\n if (withUnitFirst) {\n const [, num1, unit, op, num2] = withUnitFirst\n const result = evaluateOperation(parseFloat(num1), op, parseFloat(num2))\n if (!Number.isFinite(result)) {\n return null\n }\n return formatNumber(result) + unit\n }\n\n // Pattern 2: number operator number+unit (e.g., \"4 * 0.25rem\")\n const withUnitSecond = expr.match(\n /^([\\d.]+)\\s*([*/+-])\\s*([\\d.]+)(rem|px|em|%|vh|vw)$/,\n )\n if (withUnitSecond) {\n const [, num1, op, num2, unit] = withUnitSecond\n const result = evaluateOperation(parseFloat(num1), op, parseFloat(num2))\n if (!Number.isFinite(result)) {\n return null\n }\n return formatNumber(result) + unit\n }\n\n // Pattern 3: unitless (e.g., \"1.25 / 0.875\")\n const unitless = expr.match(/^([\\d.]+)\\s*([*/+-])\\s*([\\d.]+)$/)\n if (unitless) {\n const [, num1, op, num2] = unitless\n const result = evaluateOperation(parseFloat(num1), op, parseFloat(num2))\n if (!Number.isFinite(result)) {\n return null\n }\n return formatNumber(result)\n }\n\n return null\n}\n\nfunction evaluateOperation(a: number, op: string, b: number): number {\n switch (op) {\n case \"*\":\n return a * b\n case \"/\":\n return a / b\n case \"+\":\n return a + b\n case \"-\":\n return a - b\n default:\n return NaN\n }\n}\n\nfunction formatNumber(num: number): string {\n // Avoid floating point artifacts like 0.30000000000000004\n const rounded = Math.round(num * 10000) / 10000\n return String(rounded)\n}\n\n/**\n * Convert rem values to pixels (assuming 1rem = 16px).\n */\nfunction remToPx(value: string): string {\n return value.replace(/([\\d.]+)rem/g, (_, num) => {\n const px = parseFloat(num) * 16\n return `${formatNumber(px)}px`\n })\n}\n\n/**\n * Find the matching closing parenthesis for a var() call.\n * Handles nested parentheses in fallback values.\n */\nfunction findVarEnd(str: string, start: number): number {\n let depth = 0\n for (let i = start; i < str.length; i++) {\n if (str[i] === \"(\") {\n depth++\n } else if (str[i] === \")\") {\n depth--\n if (depth === 0) {\n return i\n }\n }\n }\n return -1\n}\n\n/**\n * Parse a var() expression and return its parts.\n */\nfunction parseVar(\n str: string,\n startIndex: number,\n): {end: number; fallback: string | null; varName: string} | null {\n // Find \"var(\" starting position\n const varStart = str.indexOf(\"var(\", startIndex)\n if (varStart === -1) {\n return null\n }\n\n const contentStart = varStart + 4 // After \"var(\"\n const end = findVarEnd(str, varStart)\n if (end === -1) {\n return null\n }\n\n const content = str.slice(contentStart, end)\n\n // Find comma separating variable name from fallback\n let commaIndex = -1\n let depth = 0\n for (let i = 0; i < content.length; i++) {\n if (content[i] === \"(\") {\n depth++\n } else if (content[i] === \")\") {\n depth--\n } else if (content[i] === \",\" && depth === 0) {\n commaIndex = i\n break\n }\n }\n\n if (commaIndex === -1) {\n return {\n end,\n fallback: null,\n varName: content.trim(),\n }\n }\n\n return {\n end,\n fallback: content.slice(commaIndex + 1).trim(),\n varName: content.slice(0, commaIndex).trim(),\n }\n}\n\n/**\n * Resolve CSS var() references and evaluate calc() expressions.\n * Recursively resolves nested var() calls.\n */\nfunction resolveCssValue(\n value: string,\n variables: Map<string, string>,\n depth = 0,\n): string {\n if (depth > 10) {\n return value // Prevent infinite recursion\n }\n\n let resolved = value\n let searchStart = 0\n\n // Process var() calls iteratively to handle nested var() in fallbacks\n while (true) {\n const parsed = parseVar(resolved, searchStart)\n if (!parsed) {\n break\n }\n\n const {end, fallback, varName} = parsed\n const varStart = resolved.indexOf(\"var(\", searchStart)\n\n let replacement: string\n const varValue = variables.get(varName)\n if (varValue !== undefined) {\n replacement = resolveCssValue(varValue, variables, depth + 1)\n } else if (fallback) {\n replacement = resolveCssValue(fallback, variables, depth + 1)\n } else {\n // Keep original if unresolved, move past it\n searchStart = end + 1\n continue\n }\n\n resolved =\n resolved.slice(0, varStart) + replacement + resolved.slice(end + 1)\n }\n\n // Evaluate calc() expressions after var() resolution\n resolved = resolved.replace(\n /calc\\(([^)]+)\\)/g,\n (match, expression: string) => {\n const evaluated = evaluateCalc(expression)\n return evaluated ?? match\n },\n )\n\n // Convert rem to px (1rem = 16px)\n resolved = remToPx(resolved)\n\n return resolved\n}\n\ninterface SelectorAnalysis {\n /** The class name if it's a simple class selector */\n className: string | null\n /** Whether this selector can be inlined (single class, no pseudo/combinators) */\n inlineable: boolean\n}\n\n/**\n * Analyze a CSS selector using postcss-selector-parser AST.\n * Returns whether it can be inlined and extracts the class name.\n */\nfunction analyzeSelector(selector: string): SelectorAnalysis {\n let inlineable = true\n let className: string | null = null\n\n const processor = selectorParser((selectors) => {\n if (selectors.nodes.length !== 1) {\n inlineable = false\n return\n }\n\n const selectorNode = selectors.nodes[0]\n if (selectorNode.nodes.length !== 1) {\n inlineable = false\n return\n }\n\n const node = selectorNode.nodes[0]\n if (node.type !== \"class\") {\n inlineable = false\n return\n }\n\n className = node.value\n\n selectorNode.walk((n) => {\n if (\n n.type === \"pseudo\" ||\n n.type === \"combinator\" ||\n n.type === \"nesting\" ||\n n.type === \"attribute\"\n ) {\n inlineable = false\n }\n })\n })\n\n processor.processSync(selector)\n\n return {className, inlineable}\n}\n\ninterface ParsedRule {\n className: string\n declarations: string\n inlineable: boolean\n originalRule: string\n}\n\n/**\n * Parse compiled CSS and extract rules with their inlineability status.\n * CSS variables are resolved and calc() expressions are evaluated.\n */\nfunction parseCompiledCss(css: string): ParsedRule[] {\n const rules: ParsedRule[] = []\n const root = postcss.parse(css)\n const variables = extractCssVariables(css)\n\n function processRule(rule: Rule, insideAtRule: boolean) {\n const {className, inlineable} = analyzeSelector(rule.selector)\n\n if (!className) {\n return\n }\n\n let hasNestedAtRule = false\n rule.walkAtRules(() => {\n hasNestedAtRule = true\n })\n\n const declarations: string[] = []\n rule.each((node) => {\n if (node.type === \"decl\") {\n const resolvedValue = resolveCssValue(node.value, variables)\n declarations.push(`${node.prop}: ${resolvedValue}`)\n }\n })\n\n if (declarations.length === 0 && !hasNestedAtRule) {\n return\n }\n\n rules.push({\n className,\n declarations: declarations.join(\"; \"),\n inlineable: inlineable && !insideAtRule && !hasNestedAtRule,\n originalRule: rule.toString(),\n })\n }\n\n root.walkAtRules(\"layer\", (atRule) => {\n atRule.walkRules((rule) => {\n const parent = rule.parent\n const insideNestedAtRule =\n parent?.type === \"atrule\" && (parent as postcss.AtRule).name !== \"layer\"\n processRule(rule, insideNestedAtRule)\n })\n\n atRule.walkAtRules((nested) => {\n if (nested.name !== \"layer\") {\n nested.walkRules((rule) => {\n processRule(rule, true)\n })\n }\n })\n })\n\n root.walkRules((rule) => {\n if (rule.parent?.type === \"root\") {\n processRule(rule, false)\n }\n })\n\n return rules\n}\n\n/**\n * Build residual CSS from non-inlineable rules, stripping @layer wrappers.\n */\nfunction buildResidualCss(css: string, inlineableClasses: Set<string>): string {\n const root = postcss.parse(css)\n const residualRules: string[] = []\n\n function shouldKeepRule(rule: Rule): boolean {\n const {className} = analyzeSelector(rule.selector)\n return className !== null && !inlineableClasses.has(className)\n }\n\n root.walkAtRules(\"layer\", (atRule) => {\n if (atRule.params !== \"utilities\") {\n return\n }\n\n atRule.each((node) => {\n if (node.type === \"rule\") {\n const rule = node\n if (shouldKeepRule(rule)) {\n residualRules.push(rule.toString())\n }\n }\n })\n })\n\n return residualRules.join(\"\\n\\n\")\n}\n\nexport interface TransformResult {\n /** CSS for non-inlineable rules without @layer wrappers */\n css: string\n /** HTML with inline styles applied */\n html: string\n}\n\n/**\n * Transform HTML by inlining Tailwind styles where possible.\n * Non-inlineable styles (pseudo-classes, media queries, etc.) are returned as CSS.\n */\nexport async function transformWithInlineStyles(\n html: string,\n styles: string,\n): Promise<TransformResult> {\n const compiler = await createCompiler(styles)\n const allClasses = extractClasses(html)\n const compiledCss = compiler.build(allClasses)\n const parsedRules = parseCompiledCss(compiledCss)\n\n const inlineableStyles = new Map<string, string>()\n const inlineableClasses = new Set<string>()\n\n for (const rule of parsedRules) {\n if (rule.inlineable) {\n inlineableStyles.set(rule.className, rule.declarations)\n inlineableClasses.add(rule.className)\n }\n }\n\n const residualCss = buildResidualCss(compiledCss, inlineableClasses)\n const tree = fromHtml(html, {fragment: true})\n\n visit(tree, \"element\", (node: Element) => {\n const classValue = getClassValue(node)\n if (!classValue) {\n return\n }\n\n const classes = classValue.split(/\\s+/)\n const inlineStyles: string[] = []\n const remainingClasses: string[] = []\n\n for (const cls of classes) {\n const style = inlineableStyles.get(cls)\n if (style) {\n inlineStyles.push(style)\n } else {\n remainingClasses.push(cls)\n }\n }\n\n if (inlineStyles.length > 0) {\n const existingStyle = node.properties?.style as string | undefined\n const newStyle = inlineStyles.join(\"; \")\n node.properties = node.properties ?? {}\n node.properties.style = existingStyle\n ? `${existingStyle}; ${newStyle}`\n : newStyle\n }\n\n if (remainingClasses.length > 0) {\n node.properties = node.properties ?? {}\n node.properties.className = remainingClasses\n } else if (node.properties) {\n delete node.properties.className\n delete node.properties.class\n }\n })\n\n return {\n css: residualCss,\n html: toHtml(tree),\n }\n}\n\nexport interface ShikiTailwindTransformerOptions {\n /**\n * Callback invoked after transformation indicating whether any className/class\n * attributes were detected in the code. Useful for conditionally applying\n * the transformation or showing/hiding UI elements.\n */\n onClassesDetected?: (detected: boolean) => void\n /**\n * Callback invoked with CSS rules for non-inlineable classes (hover:, sm:, etc.).\n * Receives a Map where keys are class names and values are the CSS rule strings.\n * This allows for deduplication when aggregating CSS from multiple files.\n */\n onResidualCss?: (rules: Map<string, string>) => void\n /**\n * Output format for inline styles.\n * - \"html\": `style=\"display: flex\"` (HTML string syntax)\n * - \"jsx\": `style={{ display: 'flex' }}` (JSX object syntax)\n * @default \"html\"\n */\n styleFormat?: \"html\" | \"jsx\"\n /** Tailwind CSS styles to compile against */\n styles: string\n}\n\ninterface CompileClassesResult {\n inlineStyles: string[]\n remainingClasses: string[]\n residualRules: Map<string, string>\n}\n\n/**\n * Compile classes and return inline styles, remaining classes, and residual CSS\n * rules.\n */\nfunction compileClasses(\n classes: string[],\n compiler: {build(candidates: string[]): string},\n): CompileClassesResult {\n const compiledCss = compiler.build(classes)\n const parsedRules = parseCompiledCss(compiledCss)\n\n const inlineableStyles = new Map<string, string>()\n const residualRules = new Map<string, string>()\n\n for (const rule of parsedRules) {\n if (rule.inlineable) {\n inlineableStyles.set(rule.className, rule.declarations)\n } else {\n residualRules.set(rule.className, rule.originalRule)\n }\n }\n\n const inlineStyles: string[] = []\n const remainingClasses: string[] = []\n\n for (const cls of classes) {\n const style = inlineableStyles.get(cls)\n if (style) {\n inlineStyles.push(style)\n } else {\n remainingClasses.push(cls)\n }\n }\n\n return {inlineStyles, remainingClasses, residualRules}\n}\n\n/**\n * Convert CSS declarations to JSX object syntax.\n * `\"display: flex; align-items: center\"` -> `\"{ display: 'flex', alignItems:\n * 'center'}\"`\n */\nfunction cssToJsxObject(cssDeclarations: string[]): string {\n const props = cssDeclarations\n .flatMap((decl) => {\n return decl\n .split(\";\")\n .map((d) => d.trim())\n .filter(Boolean)\n })\n .map((declaration) => {\n const colonIndex = declaration.indexOf(\":\")\n if (colonIndex === -1) {\n return null\n }\n const prop = declaration.slice(0, colonIndex).trim()\n const value = declaration.slice(colonIndex + 1).trim()\n const camelProp = camelCase(prop)\n return `${camelProp}: '${value}'`\n })\n .filter(Boolean)\n\n return `{ ${props.join(\", \")} }`\n}\n\ninterface LineReplacementsResult {\n replacements: Map<string, string>\n residualRules: Map<string, string>\n}\n\n/**\n * Transform className attributes to style attributes in a line's text.\n * Returns replacements and residual CSS rules for non-inlineable classes.\n */\nfunction computeLineReplacements(\n lineText: string,\n compiler: {build(candidates: string[]): string},\n styleFormat: \"html\" | \"jsx\" = \"html\",\n): LineReplacementsResult {\n const replacements = new Map<string, string>()\n const allResidualRules = new Map<string, string>()\n const classAttrPattern = /(className|class)=([\"'`])([^\"'`]*)\\2/g\n let match\n\n while ((match = classAttrPattern.exec(lineText)) !== null) {\n const fullMatch = match[0]\n const attrName = match[1]\n const quote = match[2]\n const classValue = match[3]\n\n const classes = classValue.split(/\\s+/).filter(Boolean)\n if (classes.length === 0) {\n continue\n }\n\n const {inlineStyles, remainingClasses, residualRules} = compileClasses(\n classes,\n compiler,\n )\n\n for (const [className, rule] of residualRules) {\n allResidualRules.set(className, rule)\n }\n\n if (inlineStyles.length === 0) {\n continue\n }\n\n let replacement: string\n if (styleFormat === \"jsx\") {\n const jsxStyleObj = cssToJsxObject(inlineStyles)\n replacement = `style={${jsxStyleObj}}`\n } else {\n replacement = `style=${quote}${inlineStyles.join(\"; \")}${quote}`\n }\n\n if (remainingClasses.length > 0) {\n replacement += ` ${attrName}=${quote}${remainingClasses.join(\" \")}${quote}`\n }\n\n replacements.set(fullMatch, replacement)\n }\n\n return {replacements, residualRules: allResidualRules}\n}\n\ninterface TransformSourceResult {\n /** Whether any className/class attributes were detected in the code */\n classesDetected: boolean\n /** CSS rules for non-inlineable classes */\n residualRules: Map<string, string>\n /** Transformed source code */\n source: string\n}\n\n/**\n * Transform className/class attributes to inline styles in source code.\n * This runs BEFORE Shiki tokenization to preserve proper syntax highlighting.\n */\nfunction transformSourceCode(\n source: string,\n compiler: {build(candidates: string[]): string},\n styleFormat: \"html\" | \"jsx\" = \"html\",\n): TransformSourceResult {\n const allResidualRules = new Map<string, string>()\n let classesDetected = false\n\n const {replacements, residualRules} = computeLineReplacements(\n source,\n compiler,\n styleFormat,\n )\n\n if (replacements.size > 0 || residualRules.size > 0) {\n classesDetected = true\n }\n\n for (const [cls, rule] of residualRules) {\n allResidualRules.set(cls, rule)\n }\n\n // Apply all replacements to the source\n let transformed = source\n for (const [original, replacement] of replacements) {\n transformed = transformed.replaceAll(original, replacement)\n }\n\n return {\n classesDetected,\n residualRules: allResidualRules,\n source: transformed,\n }\n}\n\n/**\n * Create a Shiki transformer that inlines Tailwind styles.\n * Uses preprocess to transform source code BEFORE tokenization,\n * ensuring proper syntax highlighting of the transformed output.\n * Must be called with `await` before using the transformer.\n */\nexport async function createShikiTailwindTransformer(\n options: ShikiTailwindTransformerOptions,\n): Promise<ShikiTransformer> {\n const {\n onClassesDetected,\n onResidualCss,\n styleFormat = \"html\",\n styles,\n } = options\n const compiler = await createCompiler(styles)\n\n return {\n name: \"shiki-transformer-tailwind-to-inline\",\n preprocess(code) {\n const {classesDetected, residualRules, source} = transformSourceCode(\n code,\n compiler,\n styleFormat,\n )\n\n onClassesDetected?.(classesDetected)\n\n if (onResidualCss && residualRules.size > 0) {\n onResidualCss(residualRules)\n }\n\n return source\n },\n }\n}\n", "// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nexport const VIRTUAL_MODULE_IDS = {\n AUTO: \"\\0virtual:qui-demo-scope/auto\",\n CONFIG: \"\\0virtual:qui-demo-scope/config\",\n PAGE_PREFIX: \"\\0virtual:qui-demo-scope/page:\",\n} as const\n\nexport const LOG_PREFIX = \"@qualcomm-ui/mdx-vite/react-demo-plugin:\"\n\nexport const REACT_IMPORTS: string[] = [\n \"useState\",\n \"useEffect\",\n \"useMemo\",\n \"useCallback\",\n \"useRef\",\n \"useContext\",\n \"createContext\",\n \"forwardRef\",\n \"memo\",\n \"lazy\",\n \"Suspense\",\n \"Fragment\",\n] as const\n\nexport const NODE_BUILTINS: string[] = [\n \"fs\",\n \"path\",\n \"url\",\n \"util\",\n \"os\",\n \"crypto\",\n \"events\",\n \"stream\",\n \"buffer\",\n] as const\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 chalk from \"chalk\"\nimport {glob} from \"glob\"\nimport {readFile} from \"node:fs/promises\"\nimport {basename, resolve} from \"node:path\"\nimport {createHighlighter, type Highlighter, type ShikiTransformer} from \"shiki\"\nimport * as ts from \"typescript\"\nimport type {Plugin} from \"vite\"\n\nimport {\n quiCustomDarkTheme,\n type ReactDemoData,\n type SourceCodeData,\n} from \"@qualcomm-ui/mdx-common\"\nimport {dedent} from \"@qualcomm-ui/utils/dedent\"\n\nimport {getShikiTransformers} from \"../docs-plugin\"\nimport {\n extractPreviewFromHighlightedHtml,\n transformerCodeAttribute,\n transformerPreviewBlock,\n} from \"../docs-plugin/shiki\"\nimport {createShikiTailwindTransformer} from \"../docs-plugin/shiki/internal\"\n\nimport {LOG_PREFIX, VIRTUAL_MODULE_IDS} from \"./demo-plugin-constants\"\nimport type {QuiDemoPluginOptions} from \"./demo-plugin-types\"\nimport {\n createDemoName,\n extractFileImports,\n extractPageId,\n getScriptKind,\n isCssAsset,\n isDemoFile,\n} from \"./demo-plugin-utils\"\n\ninterface HandleUpdateOptions {\n demoName?: string\n filePath: string\n}\n\ninterface HighlightCodeResult {\n full: string\n preview?: string | null\n}\n\ninterface ExtractedSourceCode {\n residualRules?: Map<string, string>\n sourceCodeData: SourceCodeData\n}\n\nlet highlighter: Highlighter | null = null\nlet initializingHighlighter = false\n\nconst demoRegistry = new Map<string, ReactDemoData>()\nconst pageFiles = new Map<string, string[]>()\nconst relativeImportDependents = new Map<string, Set<string>>()\n\n/**\n * Generates virtual modules for React demo components. Virtual modules contain\n * highlighted source code and metadata about each demo.\n */\nexport function reactDemoPlugin({\n demoPattern = \"src/routes/**/demos/*.tsx\",\n routesDir = \"src/routes\",\n theme = {\n dark: quiCustomDarkTheme,\n light: \"github-light-high-contrast\",\n },\n transformers = [],\n transformLine,\n transformTailwindStyles,\n}: QuiDemoPluginOptions = {}): Plugin {\n const defaultShikiOptions = {\n defaultColor: \"light-dark()\",\n lang: \"tsx\",\n themes: {\n dark: theme.dark,\n light: theme.light,\n },\n }\n\n return {\n apply(config, env) {\n return (\n (env.mode === \"development\" && env.command === \"serve\") ||\n (env.mode === \"production\" && env.command === \"build\")\n )\n },\n async buildStart() {\n if (!highlighter && !initializingHighlighter) {\n initializingHighlighter = true\n try {\n highlighter = await createHighlighter({\n langs: [\"tsx\", \"typescript\", \"css\"],\n themes: [theme.dark, theme.light],\n })\n console.log(\n `${chalk.magenta.bold(LOG_PREFIX)} Shiki highlighter initialized`,\n )\n } catch (error) {\n console.warn(\n `${chalk.magenta.bold(LOG_PREFIX)} Failed to initialize highlighter:`,\n error,\n )\n } finally {\n initializingHighlighter = false\n }\n }\n\n await collectReactDemos()\n },\n\n async handleHotUpdate({file, modules, server}) {\n if (isCssAsset(file)) {\n return modules\n }\n\n if (file.endsWith(\".mdx\")) {\n return []\n }\n\n if (isDemoFile(file)) {\n await handleDemoAdditionOrUpdate({filePath: file})\n } else {\n const normalizedFile = resolve(file)\n const dependentDemos = relativeImportDependents.get(normalizedFile)\n if (!dependentDemos?.size) {\n return []\n }\n for (const demoName of Array.from(dependentDemos)) {\n const demo = demoRegistry.get(demoName)\n if (demo) {\n await handleDemoAdditionOrUpdate({\n filePath: demo.filePath,\n })\n }\n }\n }\n\n const autoModule = server.moduleGraph.getModuleById(\n VIRTUAL_MODULE_IDS.AUTO,\n )\n if (autoModule) {\n server.moduleGraph.invalidateModule(autoModule)\n await server.reloadModule(autoModule)\n }\n return []\n },\n\n async load(id) {\n if (id === VIRTUAL_MODULE_IDS.AUTO) {\n return generateAutoScopeModule()\n }\n },\n\n name: \"auto-demo-scope\",\n\n resolveId(id) {\n if (id === \"virtual:qui-demo-scope/auto\") {\n return VIRTUAL_MODULE_IDS.AUTO\n }\n },\n\n writeBundle() {\n console.log(\n `${chalk.blue.bold(LOG_PREFIX)} Successfully integrated ${chalk.green(demoRegistry.size)} component demos`,\n )\n },\n }\n\n async function handleDemoAdditionOrUpdate({\n filePath,\n }: HandleUpdateOptions): Promise<void> {\n const pageId = extractPageId(filePath, routesDir)\n const demoName = createDemoName(filePath)\n\n const existingFiles = pageFiles.get(pageId) ?? []\n if (!existingFiles.includes(filePath)) {\n existingFiles.push(filePath)\n pageFiles.set(pageId, existingFiles)\n }\n\n const fileData = await extractFileData(filePath)\n if (fileData) {\n demoRegistry.set(demoName, {\n ...fileData,\n demoName,\n pageId,\n })\n\n const fileImports = await extractFileImports(filePath)\n if (fileImports) {\n for (const relativeImport of fileImports.relativeImports) {\n const dependents =\n relativeImportDependents.get(relativeImport.resolvedPath) ??\n new Set()\n dependents.add(demoName)\n relativeImportDependents.set(relativeImport.resolvedPath, dependents)\n }\n }\n }\n }\n\n async function highlightCode(\n code: string,\n options: {\n extraTransformers?: ShikiTransformer[]\n onClassesDetected?: (detected: boolean) => void\n onResidualCss?: (rules: Map<string, string>) => void\n } = {},\n ): Promise<HighlightCodeResult> {\n const {extraTransformers = [], onResidualCss} = options\n\n if (!highlighter) {\n return {full: code}\n }\n let previewCode: string | null = null\n\n const tailwindTransformers: ShikiTransformer[] = []\n if (transformTailwindStyles && onResidualCss) {\n const transformer = await createShikiTailwindTransformer({\n onClassesDetected: (detected) => {\n options.onClassesDetected?.(detected)\n },\n onResidualCss,\n styleFormat: \"jsx\",\n styles: dedent`\n @layer theme, base, components, utilities;\n @import \"tailwindcss/theme.css\" layer(theme);\n @import \"tailwindcss/utilities.css\" layer(utilities);\n @import \"@qualcomm-ui/tailwind-plugin/qui-strict.css\";\n `,\n })\n tailwindTransformers.push(transformer)\n } else if (extraTransformers.length > 0) {\n tailwindTransformers.push(...extraTransformers)\n }\n\n try {\n const highlightedCode = highlighter.codeToHtml(code, {\n ...defaultShikiOptions,\n transformers: [\n ...getShikiTransformers(),\n ...transformers,\n ...tailwindTransformers,\n transformerPreviewBlock({\n attributeName: \"data-preview\",\n onComplete: (extractedPreview) => {\n previewCode = extractedPreview\n },\n }),\n transformerCodeAttribute({\n attributeName: \"data-code\",\n }),\n {\n enforce: \"post\",\n name: \"shiki-transformer-trim\",\n preprocess(code) {\n return code.trim()\n },\n },\n ...transformers,\n ],\n })\n\n return {\n full: highlightedCode,\n preview: previewCode\n ? extractPreviewFromHighlightedHtml(highlightedCode)\n : null,\n }\n } catch (error) {\n console.warn(\n `${chalk.magenta.bold(LOG_PREFIX)} Failed to highlight code:`,\n error,\n )\n return {full: code}\n }\n }\n\n async function collectReactDemos() {\n if (demoRegistry.size) {\n return\n }\n\n const demoFiles = (await glob(demoPattern)).filter(isDemoFile)\n\n for (const filePath of demoFiles) {\n const pageId = extractPageId(filePath, routesDir)\n const existingFiles = pageFiles.get(pageId) ?? []\n existingFiles.push(filePath)\n pageFiles.set(pageId, existingFiles)\n\n const fileData = await extractFileData(filePath)\n if (fileData) {\n const demoName = createDemoName(filePath)\n demoRegistry.set(demoName, {\n ...fileData,\n pageId,\n })\n }\n\n const fileImports = await extractFileImports(filePath)\n if (fileImports) {\n for (const relativeImport of fileImports.relativeImports) {\n const demoName = createDemoName(filePath)\n const dependents =\n relativeImportDependents.get(relativeImport.resolvedPath) ??\n new Set()\n dependents.add(demoName)\n relativeImportDependents.set(relativeImport.resolvedPath, dependents)\n }\n }\n }\n }\n\n function generateAutoScopeModule(): string {\n const registryCode = generateDemoRegistry(demoRegistry)\n return [\n \"// Auto-generated demo scope resolver (PROD MODE)\",\n registryCode,\n generateExportedFunctions(),\n ].join(\"\\n\\n\")\n }\n\n function transformLines(code: string): string {\n if (!transformLine) {\n return code\n }\n const result: string[] = []\n for (const line of code.split(\"\\n\")) {\n if (line.trim()) {\n const transformed = transformLine(line)\n if (transformed) {\n result.push(transformed)\n }\n } else {\n // include all empty lines\n result.push(line)\n }\n }\n return result.join(\"\\n\")\n }\n\n async function extractHighlightedCode(\n filePath: string,\n code: string,\n ): Promise<ExtractedSourceCode | null> {\n try {\n const fileName = basename(filePath)\n\n const baseResult = await highlightCode(code)\n\n let inlineResult: HighlightCodeResult | undefined\n let classesDetected: boolean = false\n let residualRules: Map<string, string> | undefined\n\n if (transformTailwindStyles) {\n inlineResult = await highlightCode(code, {\n onClassesDetected: (detected) => {\n classesDetected = detected\n },\n onResidualCss: (rules) => {\n residualRules = rules\n },\n })\n }\n\n return {\n residualRules,\n sourceCodeData: {\n fileName,\n filePath,\n highlighted: {\n full: baseResult.full,\n preview: baseResult.preview,\n },\n highlightedInline:\n classesDetected && inlineResult\n ? {\n full: inlineResult.full,\n preview: inlineResult.preview,\n }\n : undefined,\n type: \"file\",\n },\n }\n } catch {\n return null\n }\n }\n\n async function extractFileData(\n filePath: string,\n ): Promise<Omit<ReactDemoData, \"pageId\"> | null> {\n try {\n const code = await readFile(filePath, \"utf-8\").then(transformLines)\n const imports = stripImports(code, filePath)\n\n const sourceCode: SourceCodeData[] = []\n // Use Map for deduplication across all files in this demo\n const aggregatedRules = new Map<string, string>()\n\n const extractedMain = await extractHighlightedCode(filePath, code)\n\n if (extractedMain) {\n sourceCode.push(extractedMain.sourceCodeData)\n if (extractedMain.residualRules) {\n for (const [className, rule] of extractedMain.residualRules) {\n aggregatedRules.set(className, rule)\n }\n }\n }\n\n const fileImports = await extractFileImports(filePath)\n if (fileImports) {\n for (const relativeImport of fileImports.relativeImports) {\n try {\n const importedCode = await readFile(\n relativeImport.resolvedPath,\n \"utf-8\",\n ).then(transformLines)\n\n const extracted = await extractHighlightedCode(\n relativeImport.resolvedPath,\n importedCode,\n )\n\n if (extracted) {\n sourceCode.push(extracted.sourceCodeData)\n if (extracted.residualRules) {\n for (const [className, rule] of extracted.residualRules) {\n aggregatedRules.set(className, rule)\n }\n }\n }\n } catch {\n console.debug(\"Failed to process file\", relativeImport.resolvedPath)\n }\n }\n }\n\n // Convert aggregated rules to CSS string\n const aggregatedResidualCss =\n aggregatedRules.size > 0\n ? [...aggregatedRules.values()].join(\"\\n\\n\")\n : undefined\n\n if (aggregatedResidualCss) {\n sourceCode.push({\n fileName: \"styles.css\",\n highlighted: await highlightCode(aggregatedResidualCss),\n type: \"residual-css\",\n })\n }\n\n return {\n demoName: createDemoName(filePath),\n fileName: extractedMain?.sourceCodeData.fileName || basename(filePath),\n filePath,\n imports,\n sourceCode,\n }\n } catch {\n return null\n }\n }\n\n function stripImports(code: string, fileName: string): string[] {\n try {\n const sourceFile = ts.createSourceFile(\n fileName,\n code,\n ts.ScriptTarget.Latest,\n true,\n getScriptKind(fileName),\n )\n\n const importRanges: Array<{end: number; start: number}> = []\n\n function visit(node: ts.Node) {\n if (ts.isImportDeclaration(node)) {\n importRanges.push({\n end: node.getEnd(),\n start: node.getFullStart(),\n })\n }\n ts.forEachChild(node, visit)\n }\n\n visit(sourceFile)\n\n return importRanges.map((range) => {\n let endPos = range.end\n if (code[endPos] === \"\\n\") {\n endPos++\n }\n return code.slice(range.start, endPos).trim()\n })\n } catch (error) {\n return []\n }\n }\n\n function generateDemoRegistry(registry: Map<string, ReactDemoData>): string {\n const entries = Array.from(registry.entries())\n .map(([demoName, {fileName, imports, pageId, sourceCode}]) => {\n return ` [\"${demoName}\", { fileName: \"${fileName}\", imports: ${JSON.stringify(imports)}, pageId: \"${pageId}\", sourceCode: ${JSON.stringify(sourceCode)}, demoName: \"${demoName}\" }]`\n })\n .join(\",\\n\")\n return `const demoRegistry = new Map([\\n${entries}\\n])`\n }\n\n function generateExportedFunctions(): string {\n return dedent`\n export function getDemo(demoName) {\n const demo = demoRegistry.get(demoName)\n if (!demo) {\n return {\n fileName: \"\",\n imports: [],\n errorMessage: \\`Demo \"\\${demoName}\" not found.\\`,\n pageId: \"\",\n sourceCode: [],\n }\n }\n return demo\n }\n `\n }\n}\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,KAAK,CAAC,GAAG;AAAA,UACf,KAAK;AACH,iBAAK,WAAW;AA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SAAS,QAAQ,CAAC,EAC1C,IAAI,CAAC,CAAC,UAAU,EAAC,UAAU,SAAS,QAAQ,WAAU,CAAC,MAAM;AAC5D,aAAO,OAAO,QAAQ,mBAAmB,QAAQ,eAAe,KAAK,UAAU,OAAO,CAAC,cAAc,MAAM,kBAAkB,KAAK,UAAU,UAAU,CAAC,gBAAgB,QAAQ;AAAA,IACjL,CAAC,EACA,KAAK,KAAK;AACb,WAAO;AAAA,EAAmC,OAAO;AAAA;AAAA,EACnD;AAEA,WAAS,4BAAoC;AAC3C,WAAOL;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAeT;AACF;",
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", "chalk", "glob", "readFile", "stat", "basename", "dirname", "join", "relative", "resolve", "quiCustomDarkTheme", "dedent", "chalk", "readFileSync", "join", "resolve", "extraTypingsCommander", "join", "relative", "remarkFrontmatter", "remarkMdx", "remarkParse", "remarkParseFrontmatter", "remarkStringify", "unified", "visit", "z", "z", "z", "z", "config", "chalk", "entry", "propTypes", "heading", "remarkParse", "remarkStringify", "unified", "unified", "remarkParse", "remarkStringify", "remarkMdx", "remarkParse", "unified", "visit", "visit", "item", "visit", "remove", "heading", "unified", "remarkMdx", "remarkParse", "capitalCase", "segment", "capitalCase", "state", "routeSegment", "config", "chalk", "join", "visit", "config", "relative", "unified", "remarkParse", "remarkMdx", "remarkFrontmatter", "remarkStringify", "remarkParseFrontmatter", "config", "readFileSync", "resolve", "chalk", "join", "file", "remarkFrontmatter", "remarkGfm", "headingRank", "visit", "visit", "visit", "toString", "visit", "emptyOptions", "visit", "isPreviewLine", "config", "remarkFrontmatter", "remarkGfm", "fromHtml", "readFile", "visit", "createRequire", "VIRTUAL_MODULE_ID", "quiCustomDarkTheme", "chalk", "isCssAsset", "readFile", "glob", "dedent", "extractRelativeImports", "visit", "isRelativeImport", "resolveRelativeImport", "isNodeBuiltin", "loadTsConfigPaths", "relative", "basename", "NODE_BUILTINS", "dirname", "resolve", "join", "stat", "LOG_PREFIX", "chalk", "existsSync", "readFileSync", "readFile", "dirname", "join", "relative", "resolve", "ts", "readFile", "chalk", "LOG_PREFIX", "visit", "isPathAliasImport", "resolvePathAlias", "dirname", "resolve", "existsSync", "join", "loadTsConfigPathsFromFile", "relative", "readFileSync", "chalk", "glob", "readFile", "basename", "resolve", "createHighlighter", "ts", "quiCustomDarkTheme", "dedent", "highlighter", "demoRegistry", "quiCustomDarkTheme", "config", "createHighlighter", "chalk", "LOG_PREFIX", "resolve", "dedent", "code", "glob", "basename", "readFile", "visit"]
7
7
  }