@qualcomm-ui/mdx-vite 3.8.1 → 3.8.2

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 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/docs-plugin/markdown/knowledge/filter-frontmatter.ts","../src/docs-plugin/markdown/knowledge/plugins/demo-plugin.ts","../src/docs-plugin/markdown/knowledge/plugins/doc-props-plugin.ts","../src/docs-plugin/markdown/knowledge/plugins/filter-text-directives.ts","../src/docs-plugin/markdown/knowledge/plugins/npm-install-tabs-plugin.ts","../src/docs-plugin/markdown/knowledge/plugins/qds-theme-plugin.ts","../src/docs-plugin/markdown/knowledge/knowledge-exporter.ts","../src/docs-plugin/plugin-state.ts","../src/docs-plugin/docs-plugin.ts","../src/docs-plugin/frontmatter-hmr-plugin.ts","../src/docs-plugin/rehype/rehype-slug.ts","../src/docs-plugin/rehype/rehype-sectionize.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/mdx-plugins.ts","../src/docs-plugin/shiki/internal/shiki-transformer-tailwind.ts","../src/angular-demo-plugin/angular-demo-plugin.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"],"sourcesContent":["// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {minimatch} from \"minimatch\"\n\nimport type {KnowledgeFrontmatterConfig} from \"../../config\"\n\nexport function filterFrontmatter(\n frontmatter: Record<string, unknown>,\n config: KnowledgeFrontmatterConfig | undefined,\n): Record<string, unknown> {\n if (!config?.include?.length) {\n return frontmatter\n }\n\n const includePatterns = config.include\n const excludePatterns = config.exclude ?? []\n const filtered: Record<string, unknown> = {}\n\n for (const [field, value] of Object.entries(frontmatter)) {\n if (value === undefined) {\n continue\n }\n const isIncluded = includePatterns.some((pattern) =>\n minimatch(field, pattern),\n )\n const isExcluded = excludePatterns.some((pattern) =>\n minimatch(field, pattern),\n )\n if (isIncluded && !isExcluded) {\n filtered[field] = value\n }\n }\n\n return filtered\n}\n","// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Code, Parent} from \"mdast\"\nimport type {MdxJsxAttribute, MdxJsxFlowElement} from \"mdast-util-mdx-jsx\"\nimport {readFile} from \"node:fs/promises\"\nimport {basename, extname, join} from \"node:path\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nimport {kebabCase} from \"@qualcomm-ui/utils/change-case\"\n\nimport type {ImportedModule} from \"../types\"\nimport {\n exists,\n extractRelativeImports,\n removePreviewLines,\n resolveModulePath,\n} from \"../utils\"\n\nasync function collectDemoImports(\n demoCode: string,\n demoFilePath: string,\n visited: Set<string> = new Set(),\n verbose?: boolean,\n): Promise<ImportedModule[]> {\n const modules: ImportedModule[] = []\n const relativeImports = extractRelativeImports(demoCode)\n\n for (const importPath of relativeImports) {\n const resolvedPath = await resolveModulePath(importPath, demoFilePath)\n if (!resolvedPath || visited.has(resolvedPath)) {\n continue\n }\n visited.add(resolvedPath)\n\n try {\n const importContent = await readFile(resolvedPath, \"utf-8\")\n modules.push({\n content: importContent,\n path: resolvedPath,\n })\n const nestedModules = await collectDemoImports(\n importContent,\n resolvedPath,\n visited,\n verbose,\n )\n modules.push(...nestedModules)\n } catch {\n if (verbose) {\n console.log(` Could not read import: ${resolvedPath}`)\n }\n }\n }\n\n return modules\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 * Imported files are added as sibling code blocks immediately after the demo.\n */\nexport function formatDemos(\n demosFolder: string | undefined,\n verbose?: boolean,\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 (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 (verbose) {\n console.log(` Replaced demo ${demoName} with source code`)\n }\n\n const demoCodeBlock: Code = {\n lang: isAngularDemo ? \"angular-ts\" : \"tsx\",\n meta: null,\n type: \"code\",\n value: cleanedCode,\n }\n\n const importedModules = await collectDemoImports(\n demoCode,\n demoFilePath,\n new Set(),\n verbose,\n )\n\n if (\n importedModules.length === 0 ||\n !parent ||\n index === undefined\n ) {\n Object.assign(node, demoCodeBlock)\n } else {\n const nodesToInsert: Code[] = [demoCodeBlock]\n\n for (const importedModule of importedModules) {\n const ext = extname(importedModule.path).slice(1)\n const filename = basename(importedModule.path)\n nodesToInsert.push({\n lang: ext,\n meta: `title=\"${filename}\"`,\n type: \"code\",\n value: importedModule.content,\n })\n }\n\n parent.children.splice(index, 1, ...nodesToInsert)\n\n if (verbose) {\n console.log(\n ` Added ${importedModules.length} imported file(s) after demo`,\n )\n }\n }\n } catch (error) {\n if (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","// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Parent} from \"mdast\"\nimport type {MdxJsxAttribute, MdxJsxFlowElement} from \"mdast-util-mdx-jsx\"\nimport {readFile} from \"node:fs/promises\"\nimport {dirname, join, resolve} from \"node:path\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nimport type {SimplifiedProp} from \"@qualcomm-ui/mdx-common\"\nimport type {\n QuiComment,\n QuiCommentDisplayPart,\n} from \"@qualcomm-ui/typedoc-common\"\n\nimport {docPropsJsxNodes} from \"../../../doc-props\"\nimport {extractNamesFromAttribute} from \"../../mdx-utils\"\nimport type {ComponentProps, DocProps, PropInfo} from \"../types\"\nimport {exists} from \"../utils\"\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 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\nexport interface PropFormatterOptions {\n docPropsPath?: string\n routeDir: string\n verbose?: boolean\n}\n\nexport class PropFormatter {\n private docProps: DocProps | null = null\n private readonly docPropsPath?: string\n private readonly routeDir: string\n private readonly verbose: boolean\n\n constructor(options: PropFormatterOptions) {\n this.docPropsPath = options.docPropsPath\n this.routeDir = options.routeDir\n this.verbose = options.verbose ?? false\n }\n\n async loadDocProps(): Promise<DocProps | null> {\n if (this.docProps) {\n return this.docProps\n }\n const resolvedDocPropsPath = this.docPropsPath\n ? (await exists(this.docPropsPath))\n ? this.docPropsPath\n : resolve(process.cwd(), this.docPropsPath)\n : join(dirname(this.routeDir), \"doc-props.json\")\n\n if (!(await exists(resolvedDocPropsPath))) {\n if (this.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.verbose) {\n console.log(`Loaded doc props from: ${resolvedDocPropsPath}`)\n console.log(\n `Found ${Object.keys(docProps.props).length} component types`,\n )\n }\n this.docProps = docProps\n return docProps\n } catch (error) {\n if (this.verbose) {\n console.log(\"Error loading doc props\", error)\n }\n return null\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 if (\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 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 extractSinceTag(comment: QuiComment | undefined): string | undefined {\n const sinceTag = comment?.blockTags?.find((tag) => tag?.tag === \"@since\")\n return sinceTag?.content?.[0]?.text\n }\n\n extractProps(props: ComponentProps, isPartial: boolean): 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 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 since: this.extractSinceTag(propInfo.comment),\n }\n }\n\n /**\n * Creates a remark plugin that replaces TypeDocProps JSX elements with\n * Markdown tables containing component prop documentation.\n */\n propsToMarkdownList(): 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 || !docPropsJsxNodes.includes(node.name)) {\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.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 propTypes = this.extractProps(\n componentProps,\n Boolean(isPartial),\n )\n if (this.verbose) {\n console.log(\n ` Replaced TypeDocProps ${propsName} with API documentation`,\n )\n }\n\n const regularProps = propTypes.filter((p) => p.propType === undefined)\n const inputs = propTypes.filter((p) => p.propType === \"input\")\n const outputs = propTypes.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 data: {\n typeDocProps: {\n name: propsName,\n props: propTypes,\n since: this.extractSinceTag(componentProps.comment),\n },\n },\n lang: null,\n meta: null,\n type: \"code\",\n value: markdownContent,\n })\n },\n )\n done()\n }\n }\n}\n","// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Text} from \"mdast\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nimport {isSerializeJsxBlock, isSpoilerBlock, isStepBlock} from \"../../../remark\"\n\nexport const filterTextDirectives: Plugin = () => {\n return (tree, _file, done) => {\n visit(tree, \"text\", (node: Text) => {\n const value = node.value?.trim?.()\n if (\n value &&\n (isStepBlock(value) ||\n isSpoilerBlock(value) ||\n isSerializeJsxBlock(value))\n ) {\n Object.assign(node, {\n value: ``,\n })\n }\n })\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 {Parent} from \"mdast\"\nimport type {MdxJsxAttribute, MdxJsxFlowElement} from \"mdast-util-mdx-jsx\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nimport {extractNamesFromAttribute} from \"../../mdx-utils\"\n\nexport const formatNpmInstallTabs: 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 === \"NpmInstallTabs\") {\n const packages = node.attributes?.find(\n (attr): attr is MdxJsxAttribute =>\n attr.type === \"mdxJsxAttribute\" && attr.name === \"packages\",\n )\n const packageNames = packages\n ? extractNamesFromAttribute(packages)\n : []\n\n if (packageNames.length === 0) {\n if (parent && index !== undefined) {\n parent.children.splice(index, 1)\n }\n return\n }\n\n Object.assign(node, {\n lang: \"shell\",\n meta: null,\n type: \"code\",\n value: `npm install ${packageNames.join(\" \")}`,\n })\n }\n },\n )\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 {MdxJsxAttribute, MdxJsxFlowElement} from \"mdast-util-mdx-jsx\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\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\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 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 replaces theme JSX elements with\n * markdown tables containing theme data from.\n */\nexport async function formatThemeNodes(): 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 = getAttrExpression(node, \"data\")\n return path && getPath(themes, path)\n },\n FontTable: (node) => {\n const path = getAttrExpression(node, \"data\")\n return path && getPath(themes, path)\n },\n SpacingTable: (node) => {\n const path = getAttrExpression(node, \"data\")\n return path && getPath(themes, path)\n },\n ThemePropertyTable: (node) => {\n const path = getAttrExpression(node, \"data\")\n const property = 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","// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Link, Parent, Root} from \"mdast\"\nimport {minimatch} from \"minimatch\"\nimport {readdir} from \"node:fs/promises\"\nimport {join, relative} from \"node:path\"\nimport {visit} from \"unist-util-visit\"\n\nimport type {\n KnowledgePageData,\n KnowledgePages,\n KnowledgeSections,\n PageEntry,\n PageFrontmatter,\n SectionEntry,\n} from \"@qualcomm-ui/mdx-common\"\n\nimport type {\n KnowledgeExtraFile,\n KnowledgeFrontmatterConfig,\n PagesExportConfig,\n SectionExportConfig,\n} from \"../../config\"\nimport {\n getPathnameFromPathSegments,\n getPathSegmentsFromFileName,\n} from \"../../nav-builder\"\nimport {remarkSerializeJsxKnowledge} from \"../../remark\"\nimport type {MdxFileReader} from \"../markdown-file-reader\"\nimport {createRemarkProcessor} from \"../remark-pipeline\"\n\nimport {filterFrontmatter} from \"./filter-frontmatter\"\nimport {\n filterTextDirectives,\n formatDemos,\n formatNpmInstallTabs,\n formatThemeNodes,\n PropFormatter,\n} from \"./plugins\"\nimport {SectionExtractor} from \"./section-extractor\"\nimport type {\n KnowledgePageCache,\n MdxFlowExpression,\n ProcessedPage,\n} from \"./types\"\nimport {computeMd5} from \"./utils\"\n\nexport interface KnowledgeExporterConfig {\n baseUrl?: string\n docPropsPath?: string\n exclude?: string[]\n extraFiles?: KnowledgeExtraFile[]\n frontmatter?: KnowledgeFrontmatterConfig\n pageIdPrefix?: string\n pages?: PagesExportConfig\n routeDir: string\n sections?: SectionExportConfig\n verbose?: boolean\n}\n\n/**\n * Processes MDX documentation pages into structured JSON data (sections + pages).\n * Does not write files — the caller handles persistence.\n */\nexport class KnowledgeExporter {\n private readonly cache: KnowledgePageCache\n private readonly config: KnowledgeExporterConfig\n private readonly fileReader: MdxFileReader\n private readonly propFormatter: PropFormatter\n\n constructor(\n config: KnowledgeExporterConfig,\n fileReader: MdxFileReader,\n cache?: KnowledgePageCache,\n ) {\n this.cache = cache ?? new Map()\n this.config = config\n this.fileReader = fileReader\n this.propFormatter = new PropFormatter({\n docPropsPath: config.docPropsPath,\n routeDir: config.routeDir,\n verbose: config.verbose,\n })\n }\n\n async generate(): Promise<{\n cachedPageCount: number\n pages: KnowledgePages\n sections: KnowledgeSections\n totalPageCount: number\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 [pageInfos] = await Promise.all([\n this.scanPages(),\n this.propFormatter.loadDocProps(),\n ])\n\n if (pageInfos.length === 0) {\n console.log(\"No pages found.\")\n } else if (this.config.verbose) {\n console.log(`Found ${pageInfos.length} page(s)`)\n }\n\n let cachedCount = 0\n const currentFiles = new Set<string>()\n const allSections: SectionEntry[] = []\n const allPages: PageEntry[] = []\n\n const sectionsConfig = this.config.sections ?? {}\n const extractor = new SectionExtractor({\n depths: sectionsConfig.depths,\n minContentLength: sectionsConfig.minContentLength,\n pageIdPrefix: this.config.pageIdPrefix,\n })\n\n for (const page of pageInfos) {\n currentFiles.add(page.mdxFile)\n\n try {\n if (this.config.verbose) {\n console.log(`Processing page: ${page.name}`)\n }\n\n const {fileContents, frontmatter} = this.fileReader.readFileSync(\n page.mdxFile,\n )\n const contentHash = computeMd5(fileContents)\n const cached = this.cache.get(page.mdxFile)\n\n if (cached && cached.contentHash === contentHash) {\n cachedCount++\n allSections.push(...cached.sections)\n if (cached.pageEntry) {\n allPages.push(cached.pageEntry)\n }\n continue\n }\n\n const processed = await this.processMdxPage(page, {\n fileContents,\n frontmatter,\n })\n\n const filteredFrontmatter = filterFrontmatter(\n processed.frontmatter,\n this.config.frontmatter,\n )\n const pageInfo = {\n frontmatter: filteredFrontmatter,\n id: page.id,\n pathname: page.pathname,\n title: processed.title,\n url: processed.url,\n }\n\n const {sections: pageSections} = extractor.extract(\n processed.sectionAst,\n pageInfo,\n )\n allSections.push(...pageSections)\n\n const pageEntry = extractor.extractPage(processed.sectionAst, pageInfo)\n if (pageEntry) {\n pageEntry.content = `# ${processed.title}\\n\\n${pageEntry.content}`\n allPages.push(pageEntry)\n }\n\n this.cache.set(page.mdxFile, {\n contentHash,\n pageEntry: pageEntry ?? null,\n processedPage: processed,\n sections: pageSections,\n })\n } catch (error) {\n console.error(`Failed to process page: ${page.name}`)\n throw error\n }\n }\n\n // Prune cache entries for deleted files\n for (const key of this.cache.keys()) {\n if (!currentFiles.has(key)) {\n this.cache.delete(key)\n }\n }\n\n // Process extra files\n if (this.config.extraFiles?.length) {\n await this.processExtraFiles(\n this.config.extraFiles,\n extractor,\n allSections,\n allPages,\n )\n }\n\n const sectionsHash = computeMd5(JSON.stringify(allSections))\n const pagesHash = computeMd5(JSON.stringify(allPages))\n\n return {\n cachedPageCount: cachedCount,\n pages: {\n generatedAt: new Date().toISOString(),\n hash: pagesHash,\n pages: allPages,\n totalPages: allPages.length,\n version: 1,\n },\n sections: {\n generatedAt: new Date().toISOString(),\n hash: sectionsHash,\n sections: allSections,\n totalSections: allSections.length,\n version: 1,\n },\n totalPageCount: pageInfos.length,\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: ${segments.at(-1)}`)\n console.log(` Demos folder: ${demosFolderPath || \"NOT FOUND\"}`)\n }\n }\n\n for (const entry of entries) {\n if (entry.isDirectory()) {\n await scanDirectory(join(dirPath, entry.name))\n }\n }\n }\n\n await scanDirectory(this.config.routeDir)\n return components\n }\n\n private formatFrontmatterExpressions(\n frontmatter: Record<string, unknown> | PageFrontmatter,\n ) {\n return () => (tree: Root) => {\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: [\n {type: \"text\", value: frontmatter.description as string},\n ],\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) => {\n if (node.type !== \"heading\" || node.depth !== 1) {\n return false\n }\n return node.children?.some(\n (child) =>\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 private transformRelativeUrls() {\n const baseUrl = this.config.baseUrl\n return () => (tree: Root) => {\n if (!baseUrl) {\n return\n }\n visit(tree, \"link\", (node: Link) => {\n if (node.url.startsWith(\"/\")) {\n node.url = `${baseUrl}${node.url}`\n }\n })\n }\n }\n\n private async processMdxContent(\n mdxContent: string,\n pageInfo: KnowledgePageData,\n frontmatter: Record<string, unknown> | PageFrontmatter,\n ): Promise<Root> {\n const themePlugin = await formatThemeNodes()\n\n const processor = createRemarkProcessor({\n frontmatter: true,\n gfm: true,\n mdx: true,\n plugins: [\n remarkSerializeJsxKnowledge,\n formatNpmInstallTabs,\n this.propFormatter.propsToMarkdownList(),\n this.formatFrontmatterExpressions(frontmatter),\n themePlugin,\n formatDemos(pageInfo.demosFolder, this.config.verbose),\n filterTextDirectives,\n this.transformRelativeUrls(),\n ],\n })\n\n return (await processor.run(processor.parse(mdxContent))) as Root\n }\n\n private async processMdxPage(\n pageInfo: KnowledgePageData,\n preRead?: {\n fileContents: string\n frontmatter: Record<string, unknown> | PageFrontmatter\n },\n ): Promise<ProcessedPage> {\n const {fileContents, frontmatter} =\n preRead ?? this.fileReader.readFileSync(pageInfo.mdxFile)\n const ast = await this.processMdxContent(\n fileContents,\n pageInfo,\n frontmatter,\n )\n\n const jsxAndMetaProcessor = createRemarkProcessor({\n extractMeta: {},\n frontmatter: true,\n gfm: true,\n mdx: true,\n output: \"md\",\n removeJsx: true,\n })\n const sectionAst = jsxAndMetaProcessor.runSync(ast) as Root\n const processed = String(jsxAndMetaProcessor.stringify(sectionAst))\n const rawContent = processed\n .replace(/^---\\r?\\n[\\s\\S]*?\\r?\\n---\\r?\\n?/, \"\")\n .replace(/(^#{1,6} .*\\\\<[^>]+)>/gm, \"$1\\\\>\")\n\n // Strip meta blocks from raw content for the prose-only field\n const stripMetaProcessor = createRemarkProcessor({\n extractMeta: {},\n output: \"md\",\n })\n const strippedContent = String(await stripMetaProcessor.process(rawContent))\n\n const title = (frontmatter.title as string) || pageInfo.name\n\n return {\n content: strippedContent.trim(),\n frontmatter: frontmatter as unknown as Record<string, unknown>,\n rawContent: rawContent.trim(),\n sectionAst,\n title,\n url: pageInfo.url,\n }\n }\n\n private async processExtraFiles(\n extraFiles: KnowledgeExtraFile[],\n extractor: SectionExtractor,\n allSections: SectionEntry[],\n allPages: PageEntry[],\n ): Promise<void> {\n await Promise.all(\n extraFiles.map(async (extraFile) => {\n let contents = extraFile.contents\n if (extraFile.processAsMdx) {\n const removeJsxProcessor = createRemarkProcessor({\n frontmatter: true,\n gfm: true,\n mdx: true,\n output: \"md\",\n plugins: [this.transformRelativeUrls()],\n removeJsx: true,\n })\n\n contents = String(await removeJsxProcessor.process(contents))\n }\n\n const lines: string[] = []\n if (extraFile.title) {\n lines.push(`# ${extraFile.title}`)\n lines.push(\"\")\n }\n lines.push(contents)\n const content = lines.join(\"\\n\")\n\n const processor = createRemarkProcessor({gfm: true, output: \"md\"})\n const tree = processor.parse(content)\n\n const pageInfo = {\n frontmatter: {},\n id: extraFile.id,\n pathname: `/${extraFile.id}`,\n title: extraFile.title || extraFile.id,\n }\n\n const {sections: pageSections} = extractor.extract(tree, pageInfo)\n allSections.push(...pageSections)\n\n const pageEntry = extractor.extractPage(tree, pageInfo)\n if (pageEntry) {\n allPages.push(pageEntry)\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 chalk from \"chalk\"\nimport chokidar from \"chokidar\"\nimport {glob} from \"glob\"\nimport {readFileSync} from \"node:fs\"\nimport {mkdir, writeFile} from \"node:fs/promises\"\nimport {join, resolve} from \"node:path\"\nimport prettyMilliseconds from \"pretty-ms\"\nimport type {ViteDevServer} from \"vite\"\n\nimport type {\n KnowledgePages,\n KnowledgeSections,\n PageDocProps,\n SiteData,\n} from \"@qualcomm-ui/mdx-common\"\nimport type {QuiPropTypes} from \"@qualcomm-ui/typedoc-common\"\n\nimport type {ResolvedQuiDocsConfig} from \"./config\"\nimport {ConfigLoader} from \"./config/config-loader\"\nimport {type CompiledMdxFile, MdxFileReader} from \"./markdown\"\nimport {KnowledgeExporter} from \"./markdown/knowledge\"\nimport type {KnowledgePageCache} from \"./markdown/knowledge/types\"\nimport {fixPath} from \"./path-utils\"\nimport {SearchIndexer} from \"./search-indexer\"\n\nconst isDev = process.env.NODE_ENV === \"development\"\n\n// TODO: deprecate and rename to @qualcomm-ui/docs-plugin/site-data\nexport const PLUGIN_VIRTUAL_MODULE_ID = \"\\0@qualcomm-ui/mdx-vite-plugin\"\nexport const CONFIG_VIRTUAL_MODULE_ID = \"\\0@qualcomm-ui/docs-plugin/config\"\nexport const EXPORTS_VIRTUAL_MODULE_ID =\n \"\\0@qualcomm-ui/docs-plugin/markdown-content\"\n\nexport interface ChangeOptions {\n onComplete?: () => void\n}\n\nexport interface ExportsState {\n dir: string\n enabled: boolean\n pathnames: string[]\n}\n\n/**\n * TODO: adjust when https://github.com/vitejs/vite/discussions/16358 lands.\n */\nexport class PluginState {\n buildCount: number = 0\n config: ResolvedQuiDocsConfig | null = null\n configFilePath: string = \"\"\n docPropsFilePath: string = \"\"\n exports: ExportsState = {dir: \"\", enabled: false, pathnames: []}\n indexer!: SearchIndexer\n configLoader: ConfigLoader | null = null\n knowledgeConfig: ResolvedQuiDocsConfig[\"knowledge\"] = undefined\n private knowledgePageCache: KnowledgePageCache = new Map()\n pages: KnowledgePages | null = null\n sections: KnowledgeSections | null = null\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 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: this.indexer.navItems,\n pageDocProps: this.indexer.pageDocProps as unknown as PageDocProps,\n pageMap: this.indexer.pageMap,\n searchIndex: this.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.knowledgePageCache.clear()\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 knowledgeEnabled = !!config.knowledge\n const outputPath = config.knowledge?.outputPath ?? \"exports\"\n this.exports = {\n dir: knowledgeEnabled ? `/${outputPath}` : \"\",\n enabled: knowledgeEnabled,\n pathnames: [],\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))}${this.indexer.cachedFileCount ? chalk.greenBright.bold(` (${this.indexer.cachedFileCount}/${this.indexer.mdxFileCount} files cached)`) : \"\"}`,\n )\n }\n\n return compiledMdxFiles\n }\n\n sendUpdate() {\n for (const server of this.servers) {\n const virtualModule = server.moduleGraph.getModuleById(\n PLUGIN_VIRTUAL_MODULE_ID,\n )\n if (virtualModule) {\n server.moduleGraph.invalidateModule(virtualModule)\n server.reloadModule(virtualModule)\n }\n }\n }\n\n handleChange(opts: ChangeOptions = {}) {\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 generateKnowledge(publicDir: string): Promise<void> {\n if (!this.knowledgeConfig) {\n return\n }\n\n const outputDir = join(\n publicDir,\n this.knowledgeConfig.outputPath ?? \"exports\",\n )\n const startTime = Date.now()\n\n const fileReader = new MdxFileReader(isDev)\n const exporter = new KnowledgeExporter(\n {\n baseUrl: this.knowledgeConfig.baseUrl,\n docPropsPath: this.docPropsFilePath || undefined,\n exclude: this.knowledgeConfig.exclude,\n extraFiles: this.knowledgeConfig.extraFiles,\n frontmatter: this.knowledgeConfig.frontmatter,\n pageIdPrefix: this.knowledgeConfig.pageIdPrefix,\n pages: this.knowledgeConfig.pages,\n routeDir: this.routesDir,\n sections: this.knowledgeConfig.sections,\n },\n fileReader,\n this.knowledgePageCache,\n )\n\n const result = await exporter.generate()\n this.pages = result.pages\n this.sections = result.sections\n\n await mkdir(outputDir, {recursive: true})\n await writeFile(\n join(outputDir, \"sections.json\"),\n JSON.stringify(result.sections, null, 2),\n \"utf-8\",\n )\n await writeFile(\n join(outputDir, \"pages.json\"),\n JSON.stringify(result.pages, null, 2),\n \"utf-8\",\n )\n\n this.exports.pathnames = result.pages.pages.map((p) => p.pathname)\n\n const cacheInfo =\n result.cachedPageCount > 0\n ? chalk.greenBright.bold(\n ` (${result.cachedPageCount}/${result.totalPageCount} pages cached)`,\n )\n : \"\"\n console.debug(\n `${chalk.magenta.bold(`@qualcomm-ui/mdx-vite/docs-plugin:`)} Generated knowledge exports in: ${chalk.blueBright.bold(prettyMilliseconds(Date.now() - startTime))}${cacheInfo}`,\n )\n }\n\n debouncedGenerateKnowledge(\n publicDir: string,\n opts: {onDone?: () => void} = {},\n ): void {\n if (!this.knowledgeConfig) {\n return\n }\n clearTimeout(this.exportsTimeout)\n this.exportsTimeout = setTimeout(() => {\n void this.generateKnowledge(publicDir).then(() => {\n opts.onDone?.()\n })\n }, 500)\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\"\nimport type {PluginOption, ResolvedConfig} from \"vite\"\n\nimport {dedent} from \"@qualcomm-ui/utils/dedent\"\n\nimport type {QuiDocsPluginOptions} from \"./config\"\nimport {ConfigLoader} from \"./config/config-loader\"\nimport {fixPath} from \"./path-utils\"\nimport {\n CONFIG_VIRTUAL_MODULE_ID,\n EXPORTS_VIRTUAL_MODULE_ID,\n PLUGIN_VIRTUAL_MODULE_ID,\n PluginState,\n} from \"./plugin-state\"\n\nconst isDev = process.env.NODE_ENV === \"development\"\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 function getPublicDir() {\n return viteConfig.publicDir || join(state.getCwd(), \"public\")\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 buildStart: async () => {\n state.buildIndex(state.buildCount > 0)\n state.buildCount++\n\n if (!isDev && state.knowledgeConfig) {\n await state.generateKnowledge(getPublicDir())\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.knowledgeConfig) {\n await state.generateKnowledge(getPublicDir())\n }\n\n server.middlewares.use(\"/__qui-docs/pages\", (_req, res) => {\n res.setHeader(\"Content-Type\", \"application/json\")\n res.end(JSON.stringify(state.pages))\n })\n\n server.middlewares.use(\"/__qui-docs/sections\", (_req, res) => {\n res.setHeader(\"Content-Type\", \"application/json\")\n res.end(JSON.stringify(state.sections))\n })\n\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 state.debouncedGenerateKnowledge(getPublicDir())\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 state.debouncedGenerateKnowledge(getPublicDir())\n },\n })\n }\n })\n state.servers.push(server)\n },\n handleHotUpdate: ({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 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 state.debouncedGenerateKnowledge(getPublicDir())\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 = server.moduleGraph.getModuleById(\n PLUGIN_VIRTUAL_MODULE_ID,\n )\n if (virtualModule) {\n server.moduleGraph.invalidateModule(virtualModule)\n\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 === PLUGIN_VIRTUAL_MODULE_ID) {\n return `export const siteData = ${JSON.stringify(state.siteData)}`\n }\n if (id === CONFIG_VIRTUAL_MODULE_ID) {\n return `export const quiDocsConfig = ${JSON.stringify({...state.config, cwd: state.cwd, publicDir: viteConfig.publicDir})}`\n }\n if (id === EXPORTS_VIRTUAL_MODULE_ID) {\n if (isDev) {\n // serve the sections/pages as middleware for faster updates in dev mode.\n // This prevents the vite dev server from slowing down from frequent,\n // large module invalidations.\n const {host = \"localhost\", port = 5173} = viteConfig.server\n const hostname = host === true ? \"localhost\" : host || \"localhost\"\n const base = `${viteConfig.server.https ? \"https\" : \"http\"}://${hostname}:${port}`\n return dedent`\n export const getSections = () => fetch('${base}/__qui-docs/sections').then(r => r.json())\n export const getPages = () => fetch('${base}/__qui-docs/pages').then(r => r.json())\n `\n }\n return dedent`\n export const getSections = () => Promise.resolve(${JSON.stringify(state.sections)})\n export const getPages = () => Promise.resolve(${JSON.stringify(state.pages)})\n `\n }\n return undefined\n },\n name: \"qui-mdx-vite-plugin\",\n resolveId: (id) => {\n if (id === PLUGIN_VIRTUAL_MODULE_ID.substring(1)) {\n return PLUGIN_VIRTUAL_MODULE_ID\n }\n if (id === CONFIG_VIRTUAL_MODULE_ID.substring(1)) {\n return CONFIG_VIRTUAL_MODULE_ID\n }\n if (id === EXPORTS_VIRTUAL_MODULE_ID.substring(1)) {\n return EXPORTS_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 {PluginOption} from \"vite\"\n\nconst REACT_ROUTER_HMR_RUNTIME_ID = \"virtual:react-router/hmr-runtime\"\nconst REACT_ROUTER_FULL_RELOAD_PATH = \"/__frontmatter-hmr-fix/full-reload\"\nconst reactRouterMissingRouteModuleUpdateError =\n /^(\\s*)throw Error\\(\\s*`\\[react-router:hmr\\] No module update found for route \\$\\{route\\.id\\}`,\\s*\\);/m\n\n/**\n * Options for the {@link frontmatterHmrPlugin}.\n */\nexport interface FrontmatterHmrPluginOptions {\n /**\n * The name of the frontmatter export to target. This needs to match the\n * '@mdx-js/react' frontmatter export name, which defaults to `frontmatter`.\n *\n * @default frontmatter\n */\n exportName?: string\n}\n\n/**\n * A Vite plugin that fixes Hot Module Replacement (HMR) for MDX frontmatter exports.\n *\n * By default, React Fast Refresh only processes modules that export React\n * components. Since frontmatter is a plain object, changes to it don't trigger HMR\n * updates and instead prompt a full refresh.\n *\n * This plugin works around the issue by attaching a `$$typeof` property set to\n * `Symbol.for('react.memo')` on the exported `frontmatter` object, tricking React\n * Fast Refresh's {@link https://github.com/facebook/react/blob/f5af92d2c47d1e1f455faf912b1d3221d1038c37/packages/react-refresh/src/ReactFreshRuntime.js#L717-L723 isLikelyComponentType}\n * check into treating the module as a component module eligible for HMR.\n *\n * @since 3.2.0\n *\n * @returns A Vite plugin option that transforms modules containing frontmatter exports.\n */\nexport function frontmatterHmrPlugin(\n opts: FrontmatterHmrPluginOptions = {},\n): PluginOption {\n const {exportName = \"frontmatter\"} = opts\n return {\n configureServer(server) {\n server.middlewares.use(\n REACT_ROUTER_FULL_RELOAD_PATH,\n (req, res, next) => {\n if (req.method !== \"POST\") {\n next()\n return\n }\n\n server.ws.send({type: \"full-reload\"})\n res.statusCode = 204\n res.end()\n },\n )\n },\n name: \"frontmatter-hmr-fix\",\n transform(code: string, id: string) {\n if (id.includes(REACT_ROUTER_HMR_RUNTIME_ID)) {\n // React Router sends route metadata updates for edited route files even\n // when the browser has not imported that route module yet. In that\n // cold-route case there is no module accept callback to populate\n // __reactRouterRouteModuleUpdates, so the runtime needs to reload\n // instead of throwing.\n return code.replace(\n reactRouterMissingRouteModuleUpdateError,\n (_match, indent: string) =>\n [\n `${indent}console.debug(\\`[react-router:hmr] No module update found for route \\${route.id}\\`);`,\n `${indent}void fetch(\"${REACT_ROUTER_FULL_RELOAD_PATH}\", {method: \"POST\"}).catch(() => window.location.reload());`,\n `${indent}return;`,\n ].join(\"\\n\"),\n )\n }\n\n if (code.includes(`export const ${exportName}`)) {\n // cheat `isLikelyComponentType`\n // https://github.com/facebook/react/blob/f5af92d2c47d1e1f455faf912b1d3221d1038c37/packages/react-refresh/src/ReactFreshRuntime.js#L717-L723\n code += `\n if (typeof ${exportName} === 'object') {\n Object.defineProperty(${exportName}, \"$$typeof\", {\n enumerable: false,\n value: Symbol.for('react.memo')\n });\n }\n `\n return code\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 {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\nimport {SlugGenerator} from \"../markdown/create-slug\"\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 slugGenerator = new SlugGenerator()\n\n return (tree) => {\n slugGenerator.reset()\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 + slugGenerator.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 {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\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 → 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 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 \"./config\"\nimport {rehypeSectionize, rehypeSlug, type RehypeSlugOptions} from \"./rehype\"\nimport {\n remarkAlerts,\n remarkCodeTabs,\n remarkFrontmatterDescription,\n remarkFrontmatterTitle,\n remarkSerializeJsxRender,\n remarkSpoilers,\n remarkSteps,\n} from \"./remark\"\nimport {remarkExtractMeta} from \"./remark/remark-extract-meta\"\nimport {transformerCodeAttribute, transformerNotationHidden} from \"./shiki\"\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 addLanguageClass: true,\n defaultColor: \"light-dark()\",\n defaultLanguage: \"plaintext\",\n fallbackLanguage: \"plaintext\",\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 * @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 remarkSteps,\n remarkSerializeJsxRender,\n remarkExtractMeta,\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\nimport chalk from \"chalk\"\nimport {type FSWatcher, watch} from \"chokidar\"\nimport {glob} from \"glob\"\nimport {existsSync, statSync} from \"node:fs\"\nimport {readFile} 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 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 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 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\", (filePath: string) => {\n try {\n const fileStats = statSync(filePath)\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 void handleAngularDemoUpdate(filePath).then(() => {\n triggerRegistryUpdate()\n })\n }\n } catch {\n console.debug(\"Failed to update registry file stats\")\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\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 const updatedDemoNames: string[] = []\n\n if (isDemoFile(file)) {\n await handleDemoAdditionOrUpdate({filePath: file})\n updatedDemoNames.push(createDemoName(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 updatedDemoNames.push(demoName)\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 }\n\n for (const demoName of updatedDemoNames) {\n const demo = demoRegistry.get(demoName)\n if (demo) {\n server.ws.send({\n data: demo,\n event: \"qui-demo:update\",\n type: \"custom\",\n })\n }\n }\n\n return []\n },\n\n 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 const parts = [\n \"// Auto-generated demo scope resolver\",\n registryCode,\n generateExportedFunctions(),\n ]\n\n if (process.env.NODE_ENV === \"development\") {\n parts.push(generateHmrHandler())\n }\n\n return parts.join(\"\\n\\n\")\n }\n\n function generateHmrHandler(): string {\n return dedent`\n if (import.meta.hot) {\n import.meta.hot.on(\"qui-demo:update\", (data) => {\n demoRegistry.set(data.demoName, data)\n })\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"],"mappings":"22DAOA,SAAgB,kBACd,EACA,EACyB,CACzB,GAAI,CAAC,GAAQ,SAAS,OACpB,OAAO,EAGT,IAAM,EAAkB,EAAO,QACzB,EAAkB,EAAO,SAAW,EAAE,CACtC,EAAoC,EAAE,CAE5C,IAAK,GAAM,CAAC,EAAO,KAAU,OAAO,QAAQ,EAAY,CAAE,CACxD,GAAI,IAAU,IAAA,GACZ,SAEF,IAAM,EAAa,EAAgB,KAAM,GACvC,EAAU,EAAO,EAAQ,CAC1B,CACK,EAAa,EAAgB,KAAM,GACvC,EAAU,EAAO,EAAQ,CAC1B,CACG,GAAc,CAAC,IACjB,EAAS,GAAS,GAItB,OAAO,ECdT,eAAe,mBACb,EACA,EACA,EAAuB,IAAI,IAC3B,EAC2B,CAC3B,IAAM,EAA4B,EAAE,CAC9B,EAAkB,GAAuB,EAAS,CAExD,IAAK,IAAM,KAAc,EAAiB,CACxC,IAAM,EAAe,MAAM,GAAkB,EAAY,EAAa,CAClE,MAAC,GAAgB,EAAQ,IAAI,EAAa,EAG9C,GAAQ,IAAI,EAAa,CAEzB,GAAI,CACF,IAAM,EAAgB,MAAM,EAAS,EAAc,QAAQ,CAC3D,EAAQ,KAAK,CACX,QAAS,EACT,KAAM,EACP,CAAC,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AAe,aAAa,CAM1E,IAAM,EACJ,EAAgB,KAAO,EACnB,CAAC,GAAG,EAAgB,QAAQ,CAAC,CAAC,KAAK;;EAAO,CAC1C,IAAA,GAUN,OARI,GACF,EAAW,KAAK,CACd,SAAU,aACV,YAAa,MAAM,cAAc,EAAsB,CACvD,KAAM,eACP,CAAC,CAGG,CACL,SAAU,eAAe,EAAS,CAClC,SAAU,GAAe,eAAe,UAAY,EAAS,EAAS,CACtE,WACA,UACA,aACD,MACK,CACN,OAAO,MAIX,SAAS,aAAa,EAAc,EAA4B,CAC9D,GAAI,CACF,IAAM,EAAa,EAAG,iBACpB,EACA,EACA,EAAG,aAAa,OAChB,GACA,cAAc,EAAS,CACxB,CAEK,EAAoD,EAAE,CAE5D,SAAS,MAAM,EAAe,CACxB,EAAG,oBAAoB,EAAK,EAC9B,EAAa,KAAK,CAChB,IAAK,EAAK,QAAQ,CAClB,MAAO,EAAK,cAAc,CAC3B,CAAC,CAEJ,EAAG,aAAa,EAAM,MAAM,CAK9B,OAFA,MAAM,EAAW,CAEV,EAAa,IAAK,GAAU,CACjC,IAAI,EAAS,EAAM,IAInB,OAHI,EAAK,KAAY;GACnB,IAEK,EAAK,MAAM,EAAM,MAAO,EAAO,CAAC,MAAM,EAC7C,MACY,CACd,MAAO,EAAE,EAIb,SAAS,qBAAqB,EAA8C,CAM1E,MAAO,mCALS,MAAM,KAAK,EAAS,SAAS,CAAC,CAC3C,KAAK,CAAC,EAAU,CAAC,WAAU,UAAS,SAAQ,iBACpC,OAAO,EAAS,kBAAkB,EAAS,cAAc,KAAK,UAAU,EAAQ,CAAC,aAAa,EAAO,iBAAiB,KAAK,UAAU,EAAW,CAAC,eAAe,EAAS,MAChL,CACD,KAAK;EAAM,CACoC,MAGpD,SAAS,2BAAoC,CAC3C,MAAO,EAAM"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/docs-plugin/markdown/knowledge/filter-frontmatter.ts","../src/docs-plugin/markdown/knowledge/plugins/demo-plugin.ts","../src/docs-plugin/markdown/knowledge/plugins/doc-props-plugin.ts","../src/docs-plugin/markdown/knowledge/plugins/filter-text-directives.ts","../src/docs-plugin/markdown/knowledge/plugins/npm-install-tabs-plugin.ts","../src/docs-plugin/markdown/knowledge/plugins/qds-theme-plugin.ts","../src/docs-plugin/markdown/knowledge/knowledge-exporter.ts","../src/docs-plugin/plugin-state.ts","../src/docs-plugin/docs-plugin.ts","../src/docs-plugin/frontmatter-hmr-plugin.ts","../src/docs-plugin/rehype/rehype-slug.ts","../src/docs-plugin/rehype/rehype-sectionize.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/mdx-plugins.ts","../src/docs-plugin/shiki/internal/shiki-transformer-tailwind.ts","../src/angular-demo-plugin/angular-demo-plugin.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"],"sourcesContent":["// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport {minimatch} from \"minimatch\"\n\nimport type {KnowledgeFrontmatterConfig} from \"../../config\"\n\nexport function filterFrontmatter(\n frontmatter: Record<string, unknown>,\n config: KnowledgeFrontmatterConfig | undefined,\n): Record<string, unknown> {\n if (!config?.include?.length) {\n return frontmatter\n }\n\n const includePatterns = config.include\n const excludePatterns = config.exclude ?? []\n const filtered: Record<string, unknown> = {}\n\n for (const [field, value] of Object.entries(frontmatter)) {\n if (value === undefined) {\n continue\n }\n const isIncluded = includePatterns.some((pattern) =>\n minimatch(field, pattern),\n )\n const isExcluded = excludePatterns.some((pattern) =>\n minimatch(field, pattern),\n )\n if (isIncluded && !isExcluded) {\n filtered[field] = value\n }\n }\n\n return filtered\n}\n","// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Code, Parent} from \"mdast\"\nimport type {MdxJsxAttribute, MdxJsxFlowElement} from \"mdast-util-mdx-jsx\"\nimport {readFile} from \"node:fs/promises\"\nimport {basename, extname, join} from \"node:path\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nimport {kebabCase} from \"@qualcomm-ui/utils/change-case\"\n\nimport type {ImportedModule} from \"../types\"\nimport {\n exists,\n extractRelativeImports,\n removePreviewLines,\n resolveModulePath,\n} from \"../utils\"\n\nasync function collectDemoImports(\n demoCode: string,\n demoFilePath: string,\n visited: Set<string> = new Set(),\n verbose?: boolean,\n): Promise<ImportedModule[]> {\n const modules: ImportedModule[] = []\n const relativeImports = extractRelativeImports(demoCode)\n\n for (const importPath of relativeImports) {\n const resolvedPath = await resolveModulePath(importPath, demoFilePath)\n if (!resolvedPath || visited.has(resolvedPath)) {\n continue\n }\n visited.add(resolvedPath)\n\n try {\n const importContent = await readFile(resolvedPath, \"utf-8\")\n modules.push({\n content: importContent,\n path: resolvedPath,\n })\n const nestedModules = await collectDemoImports(\n importContent,\n resolvedPath,\n visited,\n verbose,\n )\n modules.push(...nestedModules)\n } catch {\n if (verbose) {\n console.log(` Could not read import: ${resolvedPath}`)\n }\n }\n }\n\n return modules\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 * Imported files are added as sibling code blocks immediately after the demo.\n */\nexport function formatDemos(\n demosFolder: string | undefined,\n verbose?: boolean,\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 (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 (verbose) {\n console.log(` Replaced demo ${demoName} with source code`)\n }\n\n const demoCodeBlock: Code = {\n lang: isAngularDemo ? \"angular-ts\" : \"tsx\",\n meta: null,\n type: \"code\",\n value: cleanedCode,\n }\n\n const importedModules = await collectDemoImports(\n demoCode,\n demoFilePath,\n new Set(),\n verbose,\n )\n\n if (\n importedModules.length === 0 ||\n !parent ||\n index === undefined\n ) {\n Object.assign(node, demoCodeBlock)\n } else {\n const nodesToInsert: Code[] = [demoCodeBlock]\n\n for (const importedModule of importedModules) {\n const ext = extname(importedModule.path).slice(1)\n const filename = basename(importedModule.path)\n nodesToInsert.push({\n lang: ext,\n meta: `title=\"${filename}\"`,\n type: \"code\",\n value: importedModule.content,\n })\n }\n\n parent.children.splice(index, 1, ...nodesToInsert)\n\n if (verbose) {\n console.log(\n ` Added ${importedModules.length} imported file(s) after demo`,\n )\n }\n }\n } catch (error) {\n if (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","// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Parent} from \"mdast\"\nimport type {MdxJsxAttribute, MdxJsxFlowElement} from \"mdast-util-mdx-jsx\"\nimport {readFile} from \"node:fs/promises\"\nimport {dirname, join, resolve} from \"node:path\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nimport type {SimplifiedProp} from \"@qualcomm-ui/mdx-common\"\nimport type {\n QuiComment,\n QuiCommentDisplayPart,\n} from \"@qualcomm-ui/typedoc-common\"\n\nimport {docPropsJsxNodes} from \"../../../doc-props\"\nimport {extractNamesFromAttribute} from \"../../mdx-utils\"\nimport type {ComponentProps, DocProps, PropInfo} from \"../types\"\nimport {exists} from \"../utils\"\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 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\nexport interface PropFormatterOptions {\n docPropsPath?: string\n routeDir: string\n verbose?: boolean\n}\n\nexport class PropFormatter {\n private docProps: DocProps | null = null\n private readonly docPropsPath?: string\n private readonly routeDir: string\n private readonly verbose: boolean\n\n constructor(options: PropFormatterOptions) {\n this.docPropsPath = options.docPropsPath\n this.routeDir = options.routeDir\n this.verbose = options.verbose ?? false\n }\n\n async loadDocProps(): Promise<DocProps | null> {\n if (this.docProps) {\n return this.docProps\n }\n const resolvedDocPropsPath = this.docPropsPath\n ? (await exists(this.docPropsPath))\n ? this.docPropsPath\n : resolve(process.cwd(), this.docPropsPath)\n : join(dirname(this.routeDir), \"doc-props.json\")\n\n if (!(await exists(resolvedDocPropsPath))) {\n if (this.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.verbose) {\n console.log(`Loaded doc props from: ${resolvedDocPropsPath}`)\n console.log(\n `Found ${Object.keys(docProps.props).length} component types`,\n )\n }\n this.docProps = docProps\n return docProps\n } catch (error) {\n if (this.verbose) {\n console.log(\"Error loading doc props\", error)\n }\n return null\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 if (\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 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 extractSinceTag(comment: QuiComment | undefined): string | undefined {\n const sinceTag = comment?.blockTags?.find((tag) => tag?.tag === \"@since\")\n return sinceTag?.content?.[0]?.text\n }\n\n extractProps(props: ComponentProps, isPartial: boolean): 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 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 since: this.extractSinceTag(propInfo.comment),\n }\n }\n\n /**\n * Creates a remark plugin that replaces TypeDocProps JSX elements with\n * Markdown tables containing component prop documentation.\n */\n propsToMarkdownList(): 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 || !docPropsJsxNodes.includes(node.name)) {\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.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 propTypes = this.extractProps(\n componentProps,\n Boolean(isPartial),\n )\n if (this.verbose) {\n console.log(\n ` Replaced TypeDocProps ${propsName} with API documentation`,\n )\n }\n\n const regularProps = propTypes.filter((p) => p.propType === undefined)\n const inputs = propTypes.filter((p) => p.propType === \"input\")\n const outputs = propTypes.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 data: {\n typeDocProps: {\n name: propsName,\n props: propTypes,\n since: this.extractSinceTag(componentProps.comment),\n },\n },\n lang: null,\n meta: null,\n type: \"code\",\n value: markdownContent,\n })\n },\n )\n done()\n }\n }\n}\n","// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Text} from \"mdast\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nimport {isSerializeJsxBlock, isSpoilerBlock, isStepBlock} from \"../../../remark\"\n\nexport const filterTextDirectives: Plugin = () => {\n return (tree, _file, done) => {\n visit(tree, \"text\", (node: Text) => {\n const value = node.value?.trim?.()\n if (\n value &&\n (isStepBlock(value) ||\n isSpoilerBlock(value) ||\n isSerializeJsxBlock(value))\n ) {\n Object.assign(node, {\n value: ``,\n })\n }\n })\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 {Parent} from \"mdast\"\nimport type {MdxJsxAttribute, MdxJsxFlowElement} from \"mdast-util-mdx-jsx\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\n\nimport {extractNamesFromAttribute} from \"../../mdx-utils\"\n\nexport const formatNpmInstallTabs: 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 === \"NpmInstallTabs\") {\n const packages = node.attributes?.find(\n (attr): attr is MdxJsxAttribute =>\n attr.type === \"mdxJsxAttribute\" && attr.name === \"packages\",\n )\n const packageNames = packages\n ? extractNamesFromAttribute(packages)\n : []\n\n if (packageNames.length === 0) {\n if (parent && index !== undefined) {\n parent.children.splice(index, 1)\n }\n return\n }\n\n Object.assign(node, {\n lang: \"shell\",\n meta: null,\n type: \"code\",\n value: `npm install ${packageNames.join(\" \")}`,\n })\n }\n },\n )\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 {MdxJsxAttribute, MdxJsxFlowElement} from \"mdast-util-mdx-jsx\"\nimport type {Plugin} from \"unified\"\nimport {visit} from \"unist-util-visit\"\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\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 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 replaces theme JSX elements with\n * markdown tables containing theme data from.\n */\nexport async function formatThemeNodes(): 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 = getAttrExpression(node, \"data\")\n return path && getPath(themes, path)\n },\n FontTable: (node) => {\n const path = getAttrExpression(node, \"data\")\n return path && getPath(themes, path)\n },\n SpacingTable: (node) => {\n const path = getAttrExpression(node, \"data\")\n return path && getPath(themes, path)\n },\n ThemePropertyTable: (node) => {\n const path = getAttrExpression(node, \"data\")\n const property = 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","// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.\n// SPDX-License-Identifier: BSD-3-Clause-Clear\n\nimport type {Link, Parent, Root} from \"mdast\"\nimport {minimatch} from \"minimatch\"\nimport {readdir} from \"node:fs/promises\"\nimport {join, relative} from \"node:path\"\nimport {visit} from \"unist-util-visit\"\n\nimport type {\n KnowledgePageData,\n KnowledgePages,\n KnowledgeSections,\n PageEntry,\n PageFrontmatter,\n SectionEntry,\n} from \"@qualcomm-ui/mdx-common\"\n\nimport type {\n KnowledgeExtraFile,\n KnowledgeFrontmatterConfig,\n PagesExportConfig,\n SectionExportConfig,\n} from \"../../config\"\nimport {\n getPathnameFromPathSegments,\n getPathSegmentsFromFileName,\n} from \"../../nav-builder\"\nimport {remarkSerializeJsxKnowledge} from \"../../remark\"\nimport type {MdxFileReader} from \"../markdown-file-reader\"\nimport {createRemarkProcessor} from \"../remark-pipeline\"\n\nimport {filterFrontmatter} from \"./filter-frontmatter\"\nimport {\n filterTextDirectives,\n formatDemos,\n formatNpmInstallTabs,\n formatThemeNodes,\n PropFormatter,\n} from \"./plugins\"\nimport {SectionExtractor} from \"./section-extractor\"\nimport type {\n KnowledgePageCache,\n MdxFlowExpression,\n ProcessedPage,\n} from \"./types\"\nimport {computeMd5} from \"./utils\"\n\nexport interface KnowledgeExporterConfig {\n baseUrl?: string\n docPropsPath?: string\n exclude?: string[]\n extraFiles?: KnowledgeExtraFile[]\n frontmatter?: KnowledgeFrontmatterConfig\n pageIdPrefix?: string\n pages?: PagesExportConfig\n routeDir: string\n sections?: SectionExportConfig\n verbose?: boolean\n}\n\n/**\n * Processes MDX documentation pages into structured JSON data (sections + pages).\n * Does not write files — the caller handles persistence.\n */\nexport class KnowledgeExporter {\n private readonly cache: KnowledgePageCache\n private readonly config: KnowledgeExporterConfig\n private readonly fileReader: MdxFileReader\n private readonly propFormatter: PropFormatter\n\n constructor(\n config: KnowledgeExporterConfig,\n fileReader: MdxFileReader,\n cache?: KnowledgePageCache,\n ) {\n this.cache = cache ?? new Map()\n this.config = config\n this.fileReader = fileReader\n this.propFormatter = new PropFormatter({\n docPropsPath: config.docPropsPath,\n routeDir: config.routeDir,\n verbose: config.verbose,\n })\n }\n\n async generate(): Promise<{\n cachedPageCount: number\n pages: KnowledgePages\n sections: KnowledgeSections\n totalPageCount: number\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 [pageInfos] = await Promise.all([\n this.scanPages(),\n this.propFormatter.loadDocProps(),\n ])\n\n if (pageInfos.length === 0) {\n console.log(\"No pages found.\")\n } else if (this.config.verbose) {\n console.log(`Found ${pageInfos.length} page(s)`)\n }\n\n let cachedCount = 0\n const currentFiles = new Set<string>()\n const allSections: SectionEntry[] = []\n const allPages: PageEntry[] = []\n\n const sectionsConfig = this.config.sections ?? {}\n const extractor = new SectionExtractor({\n depths: sectionsConfig.depths,\n minContentLength: sectionsConfig.minContentLength,\n pageIdPrefix: this.config.pageIdPrefix,\n })\n\n for (const page of pageInfos) {\n currentFiles.add(page.mdxFile)\n\n try {\n if (this.config.verbose) {\n console.log(`Processing page: ${page.name}`)\n }\n\n const {fileContents, frontmatter} = this.fileReader.readFileSync(\n page.mdxFile,\n )\n const contentHash = computeMd5(fileContents)\n const cached = this.cache.get(page.mdxFile)\n\n if (cached && cached.contentHash === contentHash) {\n cachedCount++\n allSections.push(...cached.sections)\n if (cached.pageEntry) {\n allPages.push(cached.pageEntry)\n }\n continue\n }\n\n const processed = await this.processMdxPage(page, {\n fileContents,\n frontmatter,\n })\n\n const filteredFrontmatter = filterFrontmatter(\n processed.frontmatter,\n this.config.frontmatter,\n )\n const pageInfo = {\n frontmatter: filteredFrontmatter,\n id: page.id,\n pathname: page.pathname,\n title: processed.title,\n url: processed.url,\n }\n\n const {sections: pageSections} = extractor.extract(\n processed.sectionAst,\n pageInfo,\n )\n allSections.push(...pageSections)\n\n const pageEntry = extractor.extractPage(processed.sectionAst, pageInfo)\n if (pageEntry) {\n pageEntry.content = `# ${processed.title}\\n\\n${pageEntry.content}`\n allPages.push(pageEntry)\n }\n\n this.cache.set(page.mdxFile, {\n contentHash,\n pageEntry: pageEntry ?? null,\n processedPage: processed,\n sections: pageSections,\n })\n } catch (error) {\n console.error(`Failed to process page: ${page.name}`)\n throw error\n }\n }\n\n // Prune cache entries for deleted files\n for (const key of this.cache.keys()) {\n if (!currentFiles.has(key)) {\n this.cache.delete(key)\n }\n }\n\n // Process extra files\n if (this.config.extraFiles?.length) {\n await this.processExtraFiles(\n this.config.extraFiles,\n extractor,\n allSections,\n allPages,\n )\n }\n\n const sectionsHash = computeMd5(JSON.stringify(allSections))\n const pagesHash = computeMd5(JSON.stringify(allPages))\n\n return {\n cachedPageCount: cachedCount,\n pages: {\n generatedAt: new Date().toISOString(),\n hash: pagesHash,\n pages: allPages,\n totalPages: allPages.length,\n version: 1,\n },\n sections: {\n generatedAt: new Date().toISOString(),\n hash: sectionsHash,\n sections: allSections,\n totalSections: allSections.length,\n version: 1,\n },\n totalPageCount: pageInfos.length,\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: ${segments.at(-1)}`)\n console.log(` Demos folder: ${demosFolderPath || \"NOT FOUND\"}`)\n }\n }\n\n for (const entry of entries) {\n if (entry.isDirectory()) {\n await scanDirectory(join(dirPath, entry.name))\n }\n }\n }\n\n await scanDirectory(this.config.routeDir)\n return components\n }\n\n private formatFrontmatterExpressions(\n frontmatter: Record<string, unknown> | PageFrontmatter,\n ) {\n return () => (tree: Root) => {\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: [\n {type: \"text\", value: frontmatter.description as string},\n ],\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) => {\n if (node.type !== \"heading\" || node.depth !== 1) {\n return false\n }\n return node.children?.some(\n (child) =>\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 private transformRelativeUrls() {\n const baseUrl = this.config.baseUrl\n return () => (tree: Root) => {\n if (!baseUrl) {\n return\n }\n visit(tree, \"link\", (node: Link) => {\n if (node.url.startsWith(\"/\")) {\n node.url = `${baseUrl}${node.url}`\n }\n })\n }\n }\n\n private async processMdxContent(\n mdxContent: string,\n pageInfo: KnowledgePageData,\n frontmatter: Record<string, unknown> | PageFrontmatter,\n ): Promise<Root> {\n const themePlugin = await formatThemeNodes()\n\n const processor = createRemarkProcessor({\n frontmatter: true,\n gfm: true,\n mdx: true,\n plugins: [\n remarkSerializeJsxKnowledge,\n formatNpmInstallTabs,\n this.propFormatter.propsToMarkdownList(),\n this.formatFrontmatterExpressions(frontmatter),\n themePlugin,\n formatDemos(pageInfo.demosFolder, this.config.verbose),\n filterTextDirectives,\n this.transformRelativeUrls(),\n ],\n })\n\n return (await processor.run(processor.parse(mdxContent))) as Root\n }\n\n private async processMdxPage(\n pageInfo: KnowledgePageData,\n preRead?: {\n fileContents: string\n frontmatter: Record<string, unknown> | PageFrontmatter\n },\n ): Promise<ProcessedPage> {\n const {fileContents, frontmatter} =\n preRead ?? this.fileReader.readFileSync(pageInfo.mdxFile)\n const ast = await this.processMdxContent(\n fileContents,\n pageInfo,\n frontmatter,\n )\n\n const jsxAndMetaProcessor = createRemarkProcessor({\n extractMeta: {},\n frontmatter: true,\n gfm: true,\n mdx: true,\n output: \"md\",\n removeJsx: true,\n })\n const sectionAst = jsxAndMetaProcessor.runSync(ast) as Root\n const processed = String(jsxAndMetaProcessor.stringify(sectionAst))\n const rawContent = processed\n .replace(/^---\\r?\\n[\\s\\S]*?\\r?\\n---\\r?\\n?/, \"\")\n .replace(/(^#{1,6} .*\\\\<[^>]+)>/gm, \"$1\\\\>\")\n\n // Strip meta blocks from raw content for the prose-only field\n const stripMetaProcessor = createRemarkProcessor({\n extractMeta: {},\n output: \"md\",\n })\n const strippedContent = String(await stripMetaProcessor.process(rawContent))\n\n const title = (frontmatter.title as string) || pageInfo.name\n\n return {\n content: strippedContent.trim(),\n frontmatter: frontmatter as unknown as Record<string, unknown>,\n rawContent: rawContent.trim(),\n sectionAst,\n title,\n url: pageInfo.url,\n }\n }\n\n private async processExtraFiles(\n extraFiles: KnowledgeExtraFile[],\n extractor: SectionExtractor,\n allSections: SectionEntry[],\n allPages: PageEntry[],\n ): Promise<void> {\n await Promise.all(\n extraFiles.map(async (extraFile) => {\n let contents = extraFile.contents\n if (extraFile.processAsMdx) {\n const removeJsxProcessor = createRemarkProcessor({\n frontmatter: true,\n gfm: true,\n mdx: true,\n output: \"md\",\n plugins: [this.transformRelativeUrls()],\n removeJsx: true,\n })\n\n contents = String(await removeJsxProcessor.process(contents))\n }\n\n const lines: string[] = []\n if (extraFile.title) {\n lines.push(`# ${extraFile.title}`)\n lines.push(\"\")\n }\n lines.push(contents)\n const content = lines.join(\"\\n\")\n\n const processor = createRemarkProcessor({gfm: true, output: \"md\"})\n const tree = processor.parse(content)\n\n const pageInfo = {\n frontmatter: {},\n id: extraFile.id,\n pathname: `/${extraFile.id}`,\n title: extraFile.title || extraFile.id,\n }\n\n const {sections: pageSections} = extractor.extract(tree, pageInfo)\n allSections.push(...pageSections)\n\n const pageEntry = extractor.extractPage(tree, pageInfo)\n if (pageEntry) {\n allPages.push(pageEntry)\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 chalk from \"chalk\"\nimport chokidar from \"chokidar\"\nimport {glob} from \"glob\"\nimport {readFileSync} from \"node:fs\"\nimport {mkdir, writeFile} from \"node:fs/promises\"\nimport {join, resolve} from \"node:path\"\nimport prettyMilliseconds from \"pretty-ms\"\nimport type {ViteDevServer} from \"vite\"\n\nimport type {\n KnowledgePages,\n KnowledgeSections,\n PageDocProps,\n SiteData,\n} from \"@qualcomm-ui/mdx-common\"\nimport type {QuiPropTypes} from \"@qualcomm-ui/typedoc-common\"\n\nimport type {ResolvedQuiDocsConfig} from \"./config\"\nimport {ConfigLoader} from \"./config/config-loader\"\nimport {type CompiledMdxFile, MdxFileReader} from \"./markdown\"\nimport {KnowledgeExporter} from \"./markdown/knowledge\"\nimport type {KnowledgePageCache} from \"./markdown/knowledge/types\"\nimport {fixPath} from \"./path-utils\"\nimport {SearchIndexer} from \"./search-indexer\"\n\nconst isDev = process.env.NODE_ENV === \"development\"\n\n// TODO: deprecate and rename to @qualcomm-ui/docs-plugin/site-data\nexport const PLUGIN_VIRTUAL_MODULE_ID = \"\\0@qualcomm-ui/mdx-vite-plugin\"\nexport const CONFIG_VIRTUAL_MODULE_ID = \"\\0@qualcomm-ui/docs-plugin/config\"\nexport const EXPORTS_VIRTUAL_MODULE_ID =\n \"\\0@qualcomm-ui/docs-plugin/markdown-content\"\n\nexport interface ChangeOptions {\n onComplete?: () => void\n}\n\nexport interface ExportsState {\n dir: string\n enabled: boolean\n pathnames: string[]\n}\n\n/**\n * TODO: adjust when https://github.com/vitejs/vite/discussions/16358 lands.\n */\nexport class PluginState {\n buildCount: number = 0\n config: ResolvedQuiDocsConfig | null = null\n configFilePath: string = \"\"\n docPropsFilePath: string = \"\"\n exports: ExportsState = {dir: \"\", enabled: false, pathnames: []}\n indexer!: SearchIndexer\n configLoader: ConfigLoader | null = null\n knowledgeConfig: ResolvedQuiDocsConfig[\"knowledge\"] = undefined\n private knowledgePageCache: KnowledgePageCache = new Map()\n pages: KnowledgePages | null = null\n sections: KnowledgeSections | null = null\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 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: this.indexer.navItems,\n pageDocProps: this.indexer.pageDocProps as unknown as PageDocProps,\n pageMap: this.indexer.pageMap,\n searchIndex: this.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.knowledgePageCache.clear()\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 knowledgeEnabled = !!config.knowledge\n const outputPath = config.knowledge?.outputPath ?? \"exports\"\n this.exports = {\n dir: knowledgeEnabled ? `/${outputPath}` : \"\",\n enabled: knowledgeEnabled,\n pathnames: [],\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))}${this.indexer.cachedFileCount ? chalk.greenBright.bold(` (${this.indexer.cachedFileCount}/${this.indexer.mdxFileCount} files cached)`) : \"\"}`,\n )\n }\n\n return compiledMdxFiles\n }\n\n sendUpdate() {\n for (const server of this.servers) {\n const virtualModule = server.moduleGraph.getModuleById(\n PLUGIN_VIRTUAL_MODULE_ID,\n )\n if (virtualModule) {\n server.moduleGraph.invalidateModule(virtualModule)\n server.reloadModule(virtualModule)\n }\n }\n }\n\n handleChange(opts: ChangeOptions = {}) {\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 generateKnowledge(publicDir: string): Promise<void> {\n if (!this.knowledgeConfig) {\n return\n }\n\n const outputDir = join(\n publicDir,\n this.knowledgeConfig.outputPath ?? \"exports\",\n )\n const startTime = Date.now()\n\n const fileReader = new MdxFileReader(isDev)\n const exporter = new KnowledgeExporter(\n {\n baseUrl: this.knowledgeConfig.baseUrl,\n docPropsPath: this.docPropsFilePath || undefined,\n exclude: this.knowledgeConfig.exclude,\n extraFiles: this.knowledgeConfig.extraFiles,\n frontmatter: this.knowledgeConfig.frontmatter,\n pageIdPrefix: this.knowledgeConfig.pageIdPrefix,\n pages: this.knowledgeConfig.pages,\n routeDir: this.routesDir,\n sections: this.knowledgeConfig.sections,\n },\n fileReader,\n this.knowledgePageCache,\n )\n\n const result = await exporter.generate()\n this.pages = result.pages\n this.sections = result.sections\n\n await mkdir(outputDir, {recursive: true})\n await writeFile(\n join(outputDir, \"sections.json\"),\n JSON.stringify(result.sections, null, 2),\n \"utf-8\",\n )\n await writeFile(\n join(outputDir, \"pages.json\"),\n JSON.stringify(result.pages, null, 2),\n \"utf-8\",\n )\n\n this.exports.pathnames = result.pages.pages.map((p) => p.pathname)\n\n const cacheInfo =\n result.cachedPageCount > 0\n ? chalk.greenBright.bold(\n ` (${result.cachedPageCount}/${result.totalPageCount} pages cached)`,\n )\n : \"\"\n console.debug(\n `${chalk.magenta.bold(`@qualcomm-ui/mdx-vite/docs-plugin:`)} Generated knowledge exports in: ${chalk.blueBright.bold(prettyMilliseconds(Date.now() - startTime))}${cacheInfo}`,\n )\n }\n\n debouncedGenerateKnowledge(\n publicDir: string,\n opts: {onDone?: () => void} = {},\n ): void {\n if (!this.knowledgeConfig) {\n return\n }\n clearTimeout(this.exportsTimeout)\n this.exportsTimeout = setTimeout(() => {\n void this.generateKnowledge(publicDir).then(() => {\n opts.onDone?.()\n })\n }, 500)\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\"\nimport type {PluginOption, ResolvedConfig} from \"vite\"\n\nimport {dedent} from \"@qualcomm-ui/utils/dedent\"\n\nimport type {QuiDocsPluginOptions} from \"./config\"\nimport {ConfigLoader} from \"./config/config-loader\"\nimport {fixPath} from \"./path-utils\"\nimport {\n CONFIG_VIRTUAL_MODULE_ID,\n EXPORTS_VIRTUAL_MODULE_ID,\n PLUGIN_VIRTUAL_MODULE_ID,\n PluginState,\n} from \"./plugin-state\"\n\nconst isDev = process.env.NODE_ENV === \"development\"\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 function getPublicDir() {\n return viteConfig.publicDir || join(state.getCwd(), \"public\")\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 buildStart: async () => {\n state.buildIndex(state.buildCount > 0)\n state.buildCount++\n\n if (!isDev && state.knowledgeConfig) {\n await state.generateKnowledge(getPublicDir())\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.knowledgeConfig) {\n await state.generateKnowledge(getPublicDir())\n }\n\n server.middlewares.use(\"/__qui-docs/pages\", (_req, res) => {\n res.setHeader(\"Content-Type\", \"application/json\")\n res.end(JSON.stringify(state.pages))\n })\n\n server.middlewares.use(\"/__qui-docs/sections\", (_req, res) => {\n res.setHeader(\"Content-Type\", \"application/json\")\n res.end(JSON.stringify(state.sections))\n })\n\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 state.debouncedGenerateKnowledge(getPublicDir())\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 state.debouncedGenerateKnowledge(getPublicDir())\n },\n })\n }\n })\n state.servers.push(server)\n },\n handleHotUpdate: ({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 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 state.debouncedGenerateKnowledge(getPublicDir())\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 = server.moduleGraph.getModuleById(\n PLUGIN_VIRTUAL_MODULE_ID,\n )\n if (virtualModule) {\n server.moduleGraph.invalidateModule(virtualModule)\n\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 === PLUGIN_VIRTUAL_MODULE_ID) {\n return `export const siteData = ${JSON.stringify(state.siteData)}`\n }\n if (id === CONFIG_VIRTUAL_MODULE_ID) {\n return `export const quiDocsConfig = ${JSON.stringify({...state.config, cwd: state.cwd, publicDir: viteConfig.publicDir})}`\n }\n if (id === EXPORTS_VIRTUAL_MODULE_ID) {\n if (isDev) {\n // serve the sections/pages as middleware for faster updates in dev mode.\n // This prevents the vite dev server from slowing down from frequent,\n // large module invalidations.\n const {host = \"localhost\", port = 5173} = viteConfig.server\n const hostname = host === true ? \"localhost\" : host || \"localhost\"\n const base = `${viteConfig.server.https ? \"https\" : \"http\"}://${hostname}:${port}`\n return dedent`\n export const getSections = () => fetch('${base}/__qui-docs/sections').then(r => r.json())\n export const getPages = () => fetch('${base}/__qui-docs/pages').then(r => r.json())\n `\n }\n return dedent`\n export const getSections = () => Promise.resolve(${JSON.stringify(state.sections)})\n export const getPages = () => Promise.resolve(${JSON.stringify(state.pages)})\n `\n }\n return undefined\n },\n name: \"qui-mdx-vite-plugin\",\n resolveId: (id) => {\n if (id === PLUGIN_VIRTUAL_MODULE_ID.substring(1)) {\n return PLUGIN_VIRTUAL_MODULE_ID\n }\n if (id === CONFIG_VIRTUAL_MODULE_ID.substring(1)) {\n return CONFIG_VIRTUAL_MODULE_ID\n }\n if (id === EXPORTS_VIRTUAL_MODULE_ID.substring(1)) {\n return EXPORTS_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 {PluginOption} from \"vite\"\n\nconst REACT_ROUTER_HMR_RUNTIME_ID = \"virtual:react-router/hmr-runtime\"\nconst REACT_ROUTER_FULL_RELOAD_PATH = \"/__frontmatter-hmr-fix/full-reload\"\nconst reactRouterMissingRouteModuleUpdateError =\n /^(\\s*)throw Error\\(\\s*`\\[react-router:hmr\\] No module update found for route \\$\\{route\\.id\\}`,\\s*\\);/m\n\n/**\n * Options for the {@link frontmatterHmrPlugin}.\n */\nexport interface FrontmatterHmrPluginOptions {\n /**\n * The name of the frontmatter export to target. This needs to match the\n * '@mdx-js/react' frontmatter export name, which defaults to `frontmatter`.\n *\n * @default frontmatter\n */\n exportName?: string\n}\n\n/**\n * A Vite plugin that fixes Hot Module Replacement (HMR) for MDX frontmatter exports.\n *\n * By default, React Fast Refresh only processes modules that export React\n * components. Since frontmatter is a plain object, changes to it don't trigger HMR\n * updates and instead prompt a full refresh.\n *\n * This plugin works around the issue by attaching a `$$typeof` property set to\n * `Symbol.for('react.memo')` on the exported `frontmatter` object, tricking React\n * Fast Refresh's {@link https://github.com/facebook/react/blob/f5af92d2c47d1e1f455faf912b1d3221d1038c37/packages/react-refresh/src/ReactFreshRuntime.js#L717-L723 isLikelyComponentType}\n * check into treating the module as a component module eligible for HMR.\n *\n * @since 3.2.0\n *\n * @returns A Vite plugin option that transforms modules containing frontmatter exports.\n */\nexport function frontmatterHmrPlugin(\n opts: FrontmatterHmrPluginOptions = {},\n): PluginOption {\n const {exportName = \"frontmatter\"} = opts\n return {\n configureServer(server) {\n server.middlewares.use(\n REACT_ROUTER_FULL_RELOAD_PATH,\n (req, res, next) => {\n if (req.method !== \"POST\") {\n next()\n return\n }\n\n server.ws.send({type: \"full-reload\"})\n res.statusCode = 204\n res.end()\n },\n )\n },\n name: \"frontmatter-hmr-fix\",\n transform(code: string, id: string) {\n if (id.includes(REACT_ROUTER_HMR_RUNTIME_ID)) {\n // React Router sends route metadata updates for edited route files even\n // when the browser has not imported that route module yet. In that\n // cold-route case there is no module accept callback to populate\n // __reactRouterRouteModuleUpdates, so the runtime needs to reload\n // instead of throwing.\n return code.replace(\n reactRouterMissingRouteModuleUpdateError,\n (_match, indent: string) =>\n [\n `${indent}console.debug(\\`[react-router:hmr] No module update found for route \\${route.id}\\`);`,\n `${indent}void fetch(\"${REACT_ROUTER_FULL_RELOAD_PATH}\", {method: \"POST\"}).catch(() => window.location.reload());`,\n `${indent}return;`,\n ].join(\"\\n\"),\n )\n }\n\n if (code.includes(`export const ${exportName}`)) {\n // cheat `isLikelyComponentType`\n // https://github.com/facebook/react/blob/f5af92d2c47d1e1f455faf912b1d3221d1038c37/packages/react-refresh/src/ReactFreshRuntime.js#L717-L723\n code += `\n if (typeof ${exportName} === 'object') {\n Object.defineProperty(${exportName}, \"$$typeof\", {\n enumerable: false,\n value: Symbol.for('react.memo')\n });\n }\n `\n return code\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 {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\nimport {SlugGenerator} from \"../markdown/create-slug\"\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 slugGenerator = new SlugGenerator()\n\n return (tree) => {\n slugGenerator.reset()\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 + slugGenerator.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 {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\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 → 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 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 \"./config\"\nimport {rehypeSectionize, rehypeSlug, type RehypeSlugOptions} from \"./rehype\"\nimport {\n remarkAlerts,\n remarkCodeTabs,\n remarkFrontmatterDescription,\n remarkFrontmatterTitle,\n remarkSerializeJsxRender,\n remarkSpoilers,\n remarkSteps,\n} from \"./remark\"\nimport {remarkExtractMeta} from \"./remark/remark-extract-meta\"\nimport {transformerCodeAttribute, transformerNotationHidden} from \"./shiki\"\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 addLanguageClass: true,\n defaultColor: \"light-dark()\",\n defaultLanguage: \"plaintext\",\n fallbackLanguage: \"plaintext\",\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 * @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 remarkSteps,\n remarkSerializeJsxRender,\n remarkExtractMeta,\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\nimport chalk from \"chalk\"\nimport {type FSWatcher, watch} from \"chokidar\"\nimport {glob} from \"glob\"\nimport {existsSync, statSync} from \"node:fs\"\nimport {readFile} 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 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 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 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\", (filePath: string) => {\n try {\n const fileStats = statSync(filePath)\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 void handleAngularDemoUpdate(filePath).then(() => {\n triggerRegistryUpdate()\n })\n }\n } catch {\n console.debug(\"Failed to update registry file stats\")\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\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 const updatedDemoNames: string[] = []\n\n if (isDemoFile(file)) {\n await handleDemoAdditionOrUpdate({filePath: file})\n updatedDemoNames.push(createDemoName(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 updatedDemoNames.push(demoName)\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 }\n\n for (const demoName of updatedDemoNames) {\n const demo = demoRegistry.get(demoName)\n if (demo) {\n server.ws.send({\n data: demo,\n event: \"qui-demo:update\",\n type: \"custom\",\n })\n }\n }\n\n return []\n },\n\n 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 const parts = [\n \"// Auto-generated demo scope resolver\",\n registryCode,\n generateExportedFunctions(),\n ]\n\n if (process.env.NODE_ENV === \"development\") {\n parts.push(generateHmrHandler())\n }\n\n return parts.join(\"\\n\\n\")\n }\n\n function generateHmrHandler(): string {\n return dedent`\n if (import.meta.hot) {\n import.meta.hot.on(\"qui-demo:update\", (data) => {\n demoRegistry.set(data.demoName, data)\n })\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"],"mappings":"+yDAOA,SAAgB,GACd,EACA,EACyB,CACzB,GAAI,CAAC,GAAQ,SAAS,OACpB,OAAO,EAGT,IAAM,EAAkB,EAAO,QACzB,EAAkB,EAAO,SAAW,EAAE,CACtC,EAAoC,EAAE,CAE5C,IAAK,GAAM,CAAC,EAAO,KAAU,OAAO,QAAQ,EAAY,CAAE,CACxD,GAAI,IAAU,IAAA,GACZ,SAEF,IAAM,EAAa,EAAgB,KAAM,GACvC,GAAU,EAAO,EAAQ,CAC1B,CACK,EAAa,EAAgB,KAAM,GACvC,GAAU,EAAO,EAAQ,CAC1B,CACG,GAAc,CAAC,IACjB,EAAS,GAAS,GAItB,OAAO,ECdT,eAAe,GACb,EACA,EACA,EAAuB,IAAI,IAC3B,EAC2B,CAC3B,IAAM,EAA4B,EAAE,CAC9B,EAAkB,GAAuB,EAAS,CAExD,IAAK,IAAM,KAAc,EAAiB,CACxC,IAAM,EAAe,MAAM,GAAkB,EAAY,EAAa,CAClE,MAAC,GAAgB,EAAQ,IAAI,EAAa,EAG9C,GAAQ,IAAI,EAAa,CAEzB,GAAI,CACF,IAAM,EAAgB,MAAM,EAAS,EAAc,QAAQ,CAC3D,EAAQ,KAAK,CACX,QAAS,EACT,KAAM,EACP,CAAC,CACF,IAAM,EAAgB,MAAM,GAC1B,EACA,EACA,EACA,EACD,CACD,EAAQ,KAAK,GAAG,EAAc,MACxB,CACF,GACF,QAAQ,IAAI,4BAA4B,IAAe,GAK7D,OAAO,EAQT,SAAgB,GACd,EACA,EACQ,CACR,UAAa,KAAO,IAAS,CAC3B,IAAM,EAA4B,EAAE,CAEpC,EACE,EACA,qBAEE,EACA,EACA,IACG,CACH,GACE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