@qualcomm-ui/mdx-vite 3.8.2 → 3.8.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +3 -3
- package/dist/cli.js.map +1 -1
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/dist/{search-indexer-DOffnbB9.js → search-indexer-Chr-z_vN.js} +6 -6
- package/dist/{search-indexer-DOffnbB9.js.map → search-indexer-Chr-z_vN.js.map} +1 -1
- package/package.json +6 -3
- package/dist/tsbuildinfo +0 -1
package/dist/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import{A as e,C as t,D as n,E as r,F as i,I as a,M as o,N as s,O as c,P as l,S as u,T as d,_ as f,a as p,b as m,c as ee,d as h,f as g,g as te,h as _,i as v,j as ne,k as y,l as re,m as ie,n as ae,o as b,p as oe,r as se,s as ce,t as le,u as ue,v as de,w as fe,x as pe,y as me}from"./search-indexer-
|
|
2
|
-
`)}var ot=class{constructor(e){this.
|
|
1
|
+
import{A as e,C as t,D as n,E as r,F as i,I as a,M as o,N as s,O as c,P as l,S as u,T as d,_ as f,a as p,b as m,c as ee,d as h,f as g,g as te,h as _,i as v,j as ne,k as y,l as re,m as ie,n as ae,o as b,p as oe,r as se,s as ce,t as le,u as ue,v as de,w as fe,x as pe,y as me}from"./search-indexer-Chr-z_vN.js";import{basename as x,dirname as S,extname as he,join as C,relative as w,resolve as T,sep as ge}from"node:path";import{existsSync as E,readFileSync as _e,statSync as ve}from"node:fs";import{glob as ye}from"glob";import{mkdir as be,readFile as D,readdir as xe,writeFile as Se}from"node:fs/promises";import O from"chalk";import{visit as k}from"unist-util-visit";import{quiCustomDarkTheme as Ce}from"@qualcomm-ui/mdx-common";import we from"remark-frontmatter";import Te from"remark-gfm";import*as A from"typescript";import{merge as Ee}from"lodash-es";import{camelCase as De,kebabCase as Oe,pascalCase as ke}from"@qualcomm-ui/utils/change-case";import Ae,{watch as je}from"chokidar";import{createHighlighter as Me}from"shiki";import{dedent as j}from"@qualcomm-ui/utils/dedent";import Ne from"pretty-ms";import{minimatch as Pe}from"minimatch";import Fe from"@shikijs/rehype";import{transformerNotationDiff as Ie,transformerNotationErrorLevel as Le,transformerNotationFocus as Re,transformerNotationHighlight as ze,transformerNotationWordHighlight as Be,transformerRemoveNotationEscape as Ve,transformerRenderIndentGuides as He}from"@shikijs/transformers";import Ue from"rehype-mdx-code-props";import We from"remark-mdx-frontmatter";import{headingRank as Ge}from"hast-util-heading-rank";import{toString as Ke}from"hast-util-to-string";import{heading as qe}from"hast-util-heading";import"hast-util-from-html";import"hast-util-to-html";import Je from"postcss";import Ye from"postcss-selector-parser";import{compile as Xe}from"tailwindcss";function Ze(e,t){if(!t?.include?.length)return e;let n=t.include,r=t.exclude??[],i={};for(let[t,a]of Object.entries(e)){if(a===void 0)continue;let e=n.some(e=>Pe(t,e)),o=r.some(e=>Pe(t,e));e&&!o&&(i[t]=a)}return i}async function Qe(e,t,n=new Set,r){let i=[],a=ce(e);for(let e of a){let a=await re(e,t);if(!(!a||n.has(a))){n.add(a);try{let e=await D(a,`utf-8`);i.push({content:e,path:a});let t=await Qe(e,a,n,r);i.push(...t)}catch{r&&console.log(` Could not read import: ${a}`)}}}return i}function $e(e,t){return()=>async n=>{let r=[];k(n,`mdxJsxFlowElement`,(n,i,a)=>{if(!n?.name||![`QdsDemo`,`CodeDemo`,`Demo`].includes(n.name))return;let o=n.attributes?.find(e=>e.type===`mdxJsxAttribute`&&e.name===`name`),s=n.attributes?.find(e=>e.type===`mdxJsxAttribute`&&e.name===`node`),c;if(o&&typeof o.value==`string`)c=o.value;else if(s?.value&&typeof s.value!=`string`){let e=s.value.data?.estree;if(e?.body?.[0]?.type===`ExpressionStatement`){let t=e.body[0].expression;t.type===`MemberExpression`&&t.object.type===`Identifier`&&t.object.name===`Demo`&&t.property.type===`Identifier`&&(c=t.property.name)}}if(!c){a&&i!==void 0&&a.children.splice(i,1);return}r.push((async()=>{let r=Oe(c),o=`${r}.tsx`;if(!e){t&&console.log(` No demos folder for ${c}`),a&&i!==void 0&&a.children.splice(i,1);return}let s=C(e,o),l=!1;if(!await b(s))if(s=C(e,`${r}.ts`),await b(s))l=!0,o=`${Oe(c).replace(`-component`,`.component`)}.ts`,s=C(e,o);else{console.log(` Demo not found ${c}`),a&&i!==void 0&&a.children.splice(i,1);return}try{let e=await D(s,`utf-8`),r=ee(e);t&&console.log(` Replaced demo ${c} with source code`);let o={lang:l?`angular-ts`:`tsx`,meta:null,type:`code`,value:r},u=await Qe(e,s,new Set,t);if(u.length===0||!a||i===void 0)Object.assign(n,o);else{let e=[o];for(let t of u){let n=he(t.path).slice(1),r=x(t.path);e.push({lang:n,meta:`title="${r}"`,type:`code`,value:t.content})}a.children.splice(i,1,...e),t&&console.log(` Added ${u.length} imported file(s) after demo`)}}catch(e){t&&console.log(`Error reading demo ${c}`,e),a&&i!==void 0&&a.children.splice(i,1)}})())}),await Promise.all(r)}}function et(e){let t=e.resolvedType?.prettyType||e.type;return nt(t.startsWith(`| `)?t.substring(2):t)}function tt(e,t){return!!(e.resolvedType?.required&&!t)}function nt(e){return e.replace(/\n/g,` `).replace(/\s+/g,` `).trim()}function rt(e){return e.replace(/^\n+/,``).replace(/\n+$/,``).trim()}function it(e){return e.replace(/\n/g,` `)}function at(e){return e.length===0?``:e.map(e=>{let t=[`- **${e.name}** (\`${it(e.type)}\``];return e.defaultValue&&t.push(`, default: \`${it(e.defaultValue)}\``),e.required&&t.push(`, required`),t.push(`)`),e.description&&t.push(` - ${it(e.description)}`),t.join(``)}).join(`
|
|
2
|
+
`)}var ot=class{docProps=null;docPropsPath;routeDir;verbose;constructor(e){this.docPropsPath=e.docPropsPath,this.routeDir=e.routeDir,this.verbose=e.verbose??!1}async loadDocProps(){if(this.docProps)return this.docProps;let e=this.docPropsPath?await b(this.docPropsPath)?this.docPropsPath:T(process.cwd(),this.docPropsPath):C(S(this.routeDir),`doc-props.json`);if(!await b(e))return this.verbose&&console.log(`Doc props file not found at: ${e}`),null;try{let t=await D(e,`utf-8`),n=JSON.parse(t);return this.verbose&&(console.log(`Loaded doc props from: ${e}`),console.log(`Found ${Object.keys(n.props).length} component types`)),this.docProps=n,n}catch(e){return this.verbose&&console.log(`Error loading doc props`,e),null}}formatCommentParts(e){return e.map(e=>{switch(e.kind){case`text`:return e.text;case`code`:let t=e.text.replace(/```\w*\n?/g,``).replace(/\n?```/g,``).trim();return t.includes(`
|
|
3
3
|
`)?`\`\`\`\n${t}\n\`\`\``:t;default:return`tag`in e&&e.tag===`@link`&&typeof e.target==`string`&&e.text===`Learn more`?``:e.text}}).join(``).replace(/\n/g,` `).replace(/\s+/g,` `).trim()}formatComment(e){if(!e)return``;let t=[];if(e.summary&&e.summary.length>0){let n=this.formatCommentParts(e.summary);n.trim()&&t.push(n.trim())}if(e.blockTags&&e.blockTags.length>0)for(let n of e.blockTags){let e=this.formatCommentParts(n.content);if(e.trim()){let r=n.tag.replace(`@`,``);if(r===`default`||r===`defaultValue`)continue;r===`example`?t.push(`**Example:**\n\`\`\`\n${e.trim()}\n\`\`\``):t.push(`**${r}:** ${e.trim()}`)}}return t.join(`
|
|
4
4
|
|
|
5
5
|
`)}extractSinceTag(e){return(e?.blockTags?.find(e=>e?.tag===`@since`))?.content?.[0]?.text}extractProps(e,t){let n=[];return e.props?.length&&n.push(...e.props.map(e=>this.convertPropInfo(e,t))),e.input?.length&&n.push(...e.input.map(e=>this.convertPropInfo(e,t,`input`))),e.output?.length&&n.push(...e.output.map(e=>this.convertPropInfo(e,t,`output`))),n}convertPropInfo(e,t,n=void 0){return{name:e.name,type:et(e),...e.defaultValue&&{defaultValue:rt(e.defaultValue)},description:this.formatComment(e.comment||null),propType:n,required:tt(e,t)||void 0,since:this.extractSinceTag(e.comment)}}propsToMarkdownList(){return()=>(e,t,n)=>{k(e,`mdxJsxFlowElement`,(e,t,n)=>{if(!e.name||!ue.includes(e.name))return;let r=e.attributes?.find(e=>e.type===`mdxJsxAttribute`&&e.name===`name`),i=e.attributes?.some(e=>e.type===`mdxJsxAttribute`&&e.name===`partial`);if(!this.docProps||!r){n&&t!==void 0&&n.children.splice(t,1);return}let a=y(r);if(a.length===0){n&&t!==void 0&&n.children.splice(t,1);return}let o=a[0],s=this.docProps.props[o];if(!s){this.verbose&&console.log(` TypeDocProps not found: ${o}`),n&&t!==void 0&&n.children.splice(t,1);return}let c=this.extractProps(s,!!i);this.verbose&&console.log(` Replaced TypeDocProps ${o} with API documentation`);let l=c.filter(e=>e.propType===void 0),u=c.filter(e=>e.propType===`input`),d=c.filter(e=>e.propType===`output`),f=[];l.length>0&&f.push(at(l)),u.length>0&&f.push(`**Inputs**\n\n${at(u)}`),d.length>0&&f.push(`**Outputs**\n\n${at(d)}`);let p=f.join(`
|
|
6
6
|
|
|
7
|
-
`);if(!p){n&&t!==void 0&&n.children.splice(t,1);return}Object.assign(e,{data:{typeDocProps:{name:o,props:c,since:this.extractSinceTag(s.comment)}},lang:null,meta:null,type:`code`,value:p})}),n()}}},st=()=>(e,t,n)=>{k(e,`text`,e=>{let t=e.value?.trim?.();t&&(g(t)||ie(t)||te(t))&&Object.assign(e,{value:``})}),n()},ct=()=>(e,t,n)=>{k(e,`mdxJsxFlowElement`,(e,t,n)=>{if(e?.name===`NpmInstallTabs`){let r=e.attributes?.find(e=>e.type===`mdxJsxAttribute`&&e.name===`packages`),i=r?y(r):[];if(i.length===0){n&&t!==void 0&&n.children.splice(t,1);return}Object.assign(e,{lang:`shell`,meta:null,type:`code`,value:`npm install ${i.join(` `)}`})}}),n()};function lt(e,t){return!e||typeof e!=`object`?``:JSON.stringify(t?{cssProperty:t,data:e}:e,null,2)}function M(e,t){return t.split(`.`).reduce((e,t)=>e&&typeof e==`object`?e[t]:void 0,e)}function N(e,t){let n=e.attributes?.find(e=>e.type===`mdxJsxAttribute`&&e.name===t);return n?.value?typeof n.value==`string`?n.value:typeof n.value==`object`&&`value`in n.value?n.value.value:null:null}async function ut(){let e=null;try{e=await import(`@qualcomm-ui/tailwind-plugin/theme`)}catch{return()=>{}}let t={ColorTable:t=>{let n=N(t,`data`);return n&&M(e,n)},FontTable:t=>{let n=N(t,`data`);return n&&M(e,n)},SpacingTable:t=>{let n=N(t,`data`);return n&&M(e,n)},ThemePropertyTable:t=>{let n=N(t,`data`),r=N(t,`cssProperty`),i=n&&M(e,n);return n&&r?{cssPropertyName:r,data:i}:void 0}};return()=>(e,n,r)=>{k(e,`mdxJsxFlowElement`,e=>{let n=e.name&&t[e.name];if(!n)return;let r=n(e);if(!r){console.warn(`No theme data for ${e.name}`);return}let i;if(typeof r==`object`&&r&&`cssPropertyName`in r&&`data`in r){let{cssPropertyName:e,data:t}=r;i=lt(t,e)}else i=lt(r);i&&Object.assign(e,{lang:`json`,meta:null,type:`code`,value:i})}),r()}}var dt=class{constructor(e,t,n){this.cache=n??new Map,this.config=e,this.fileReader=t,this.propFormatter=new ot({docPropsPath:e.docPropsPath,routeDir:e.routeDir,verbose:e.verbose})}async generate(){this.config.verbose&&(console.log(`Scanning pages in: ${this.config.routeDir}`),this.config.exclude?.length&&console.log(`Excluding patterns: ${this.config.exclude.join(`, `)}`));let[e]=await Promise.all([this.scanPages(),this.propFormatter.loadDocProps()]);e.length===0?console.log(`No pages found.`):this.config.verbose&&console.log(`Found ${e.length} page(s)`);let t=0,n=new Set,r=[],i=[],a=this.config.sections??{},o=new v({depths:a.depths,minContentLength:a.minContentLength,pageIdPrefix:this.config.pageIdPrefix});for(let a of e){n.add(a.mdxFile);try{this.config.verbose&&console.log(`Processing page: ${a.name}`);let{fileContents:e,frontmatter:n}=this.fileReader.readFileSync(a.mdxFile),s=p(e),c=this.cache.get(a.mdxFile);if(c&&c.contentHash===s){t++,r.push(...c.sections),c.pageEntry&&i.push(c.pageEntry);continue}let l=await this.processMdxPage(a,{fileContents:e,frontmatter:n}),u={frontmatter:Ze(l.frontmatter,this.config.frontmatter),id:a.id,pathname:a.pathname,title:l.title,url:l.url},{sections:d}=o.extract(l.sectionAst,u);r.push(...d);let f=o.extractPage(l.sectionAst,u);f&&(f.content=`# ${l.title}\n\n${f.content}`,i.push(f)),this.cache.set(a.mdxFile,{contentHash:s,pageEntry:f??null,processedPage:l,sections:d})}catch(e){throw console.error(`Failed to process page: ${a.name}`),e}}for(let e of this.cache.keys())n.has(e)||this.cache.delete(e);this.config.extraFiles?.length&&await this.processExtraFiles(this.config.extraFiles,o,r,i);let s=p(JSON.stringify(r)),c=p(JSON.stringify(i));return{cachedPageCount:t,pages:{generatedAt:new Date().toISOString(),hash:c,pages:i,totalPages:i.length,version:1},sections:{generatedAt:new Date().toISOString(),hash:s,sections:r,totalSections:r.length,version:1},totalPageCount:e.length}}async scanPages(){let e=[],t=this.config.exclude??[],n=e=>{if(t.length===0)return!1;let n=w(this.config.routeDir,e);return t.some(e=>Pe(n,e,{matchBase:!0}))},r=async t=>{if(n(t)){this.config.verbose&&console.log(`Excluding directory: ${w(this.config.routeDir,t)}`);return}let i=await xe(t,{withFileTypes:!0}),a=i.filter(e=>e.name.endsWith(`.mdx`)&&!n(C(t,e.name)))??[];for(let n of a){let r=i.find(e=>e.name===`demos`),a=r?C(t,r.name):void 0,o=ae(C(t,n.name),this.config.routeDir),s=se(o);e.push({demosFolder:a,filePath:t,id:o.join(`-`).trim(),mdxFile:C(t,n.name),name:o.at(-1),pathname:s,url:this.config.baseUrl?new URL(s,this.config.baseUrl).toString():void 0}),this.config.verbose&&(console.log(`Found file: ${o.at(-1)}`),console.log(` Demos folder: ${a||`NOT FOUND`}`))}for(let e of i)e.isDirectory()&&await r(C(t,e.name))};return await r(this.config.routeDir),e}formatFrontmatterExpressions(e){return()=>t=>{k(t,`mdxFlowExpression`,(t,n,r)=>{t.value.trim()!==`frontmatter.description`||n===void 0||!r||(e.description?r.children.splice(n,1,{children:[{type:`text`,value:e.description}],type:`paragraph`}):r.children.splice(n,1))});let n=t,r=n.children.findIndex(e=>e.type!==`heading`||e.depth!==1?!1:e.children?.some(e=>e.type===`mdxTextExpression`&&e.value?.includes(`frontmatter`)));r>=0&&n.children.splice(r,1)}}transformRelativeUrls(){let e=this.config.baseUrl;return()=>t=>{e&&k(t,`link`,t=>{t.url.startsWith(`/`)&&(t.url=`${e}${t.url}`)})}}async processMdxContent(e,t,n){let r=await ut(),i=h({frontmatter:!0,gfm:!0,mdx:!0,plugins:[f,ct,this.propFormatter.propsToMarkdownList(),this.formatFrontmatterExpressions(n),r,$e(t.demosFolder,this.config.verbose),st,this.transformRelativeUrls()]});return await i.run(i.parse(e))}async processMdxPage(e,t){let{fileContents:n,frontmatter:r}=t??this.fileReader.readFileSync(e.mdxFile),i=await this.processMdxContent(n,e,r),a=h({extractMeta:{},frontmatter:!0,gfm:!0,mdx:!0,output:`md`,removeJsx:!0}),o=a.runSync(i),s=String(a.stringify(o)).replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,``).replace(/(^#{1,6} .*\\<[^>]+)>/gm,`$1\\>`),c=h({extractMeta:{},output:`md`}),l=String(await c.process(s)),u=r.title||e.name;return{content:l.trim(),frontmatter:r,rawContent:s.trim(),sectionAst:o,title:u,url:e.url}}async processExtraFiles(e,t,n,r){await Promise.all(e.map(async e=>{let i=e.contents;if(e.processAsMdx){let e=h({frontmatter:!0,gfm:!0,mdx:!0,output:`md`,plugins:[this.transformRelativeUrls()],removeJsx:!0});i=String(await e.process(i))}let a=[];e.title&&(a.push(`# ${e.title}`),a.push(``)),a.push(i);let o=a.join(`
|
|
8
|
-
`),s=h({gfm:!0,output:`md`}).parse(o),c={frontmatter:{},id:e.id,pathname:`/${e.id}`,title:e.title||e.id},{sections:l}=t.extract(s,c);n.push(...l);let u=t.extractPage(s,c);u&&r.push(u)}))}},ft=process.env.NODE_ENV===`development`,pt=`\0@qualcomm-ui/mdx-vite-plugin`,mt=`\0@qualcomm-ui/docs-plugin/config`,ht=`\0@qualcomm-ui/docs-plugin/markdown-content`,gt=class{
|
|
7
|
+
`);if(!p){n&&t!==void 0&&n.children.splice(t,1);return}Object.assign(e,{data:{typeDocProps:{name:o,props:c,since:this.extractSinceTag(s.comment)}},lang:null,meta:null,type:`code`,value:p})}),n()}}},st=()=>(e,t,n)=>{k(e,`text`,e=>{let t=e.value?.trim?.();t&&(g(t)||ie(t)||te(t))&&Object.assign(e,{value:``})}),n()},ct=()=>(e,t,n)=>{k(e,`mdxJsxFlowElement`,(e,t,n)=>{if(e?.name===`NpmInstallTabs`){let r=e.attributes?.find(e=>e.type===`mdxJsxAttribute`&&e.name===`packages`),i=r?y(r):[];if(i.length===0){n&&t!==void 0&&n.children.splice(t,1);return}Object.assign(e,{lang:`shell`,meta:null,type:`code`,value:`npm install ${i.join(` `)}`})}}),n()};function lt(e,t){return!e||typeof e!=`object`?``:JSON.stringify(t?{cssProperty:t,data:e}:e,null,2)}function M(e,t){return t.split(`.`).reduce((e,t)=>e&&typeof e==`object`?e[t]:void 0,e)}function N(e,t){let n=e.attributes?.find(e=>e.type===`mdxJsxAttribute`&&e.name===t);return n?.value?typeof n.value==`string`?n.value:typeof n.value==`object`&&`value`in n.value?n.value.value:null:null}async function ut(){let e=null;try{e=await import(`@qualcomm-ui/tailwind-plugin/theme`)}catch{return()=>{}}let t={ColorTable:t=>{let n=N(t,`data`);return n&&M(e,n)},FontTable:t=>{let n=N(t,`data`);return n&&M(e,n)},SpacingTable:t=>{let n=N(t,`data`);return n&&M(e,n)},ThemePropertyTable:t=>{let n=N(t,`data`),r=N(t,`cssProperty`),i=n&&M(e,n);return n&&r?{cssPropertyName:r,data:i}:void 0}};return()=>(e,n,r)=>{k(e,`mdxJsxFlowElement`,e=>{let n=e.name&&t[e.name];if(!n)return;let r=n(e);if(!r){console.warn(`No theme data for ${e.name}`);return}let i;if(typeof r==`object`&&r&&`cssPropertyName`in r&&`data`in r){let{cssPropertyName:e,data:t}=r;i=lt(t,e)}else i=lt(r);i&&Object.assign(e,{lang:`json`,meta:null,type:`code`,value:i})}),r()}}var dt=class{cache;config;fileReader;propFormatter;constructor(e,t,n){this.cache=n??new Map,this.config=e,this.fileReader=t,this.propFormatter=new ot({docPropsPath:e.docPropsPath,routeDir:e.routeDir,verbose:e.verbose})}async generate(){this.config.verbose&&(console.log(`Scanning pages in: ${this.config.routeDir}`),this.config.exclude?.length&&console.log(`Excluding patterns: ${this.config.exclude.join(`, `)}`));let[e]=await Promise.all([this.scanPages(),this.propFormatter.loadDocProps()]);e.length===0?console.log(`No pages found.`):this.config.verbose&&console.log(`Found ${e.length} page(s)`);let t=0,n=new Set,r=[],i=[],a=this.config.sections??{},o=new v({depths:a.depths,minContentLength:a.minContentLength,pageIdPrefix:this.config.pageIdPrefix});for(let a of e){n.add(a.mdxFile);try{this.config.verbose&&console.log(`Processing page: ${a.name}`);let{fileContents:e,frontmatter:n}=this.fileReader.readFileSync(a.mdxFile),s=p(e),c=this.cache.get(a.mdxFile);if(c&&c.contentHash===s){t++,r.push(...c.sections),c.pageEntry&&i.push(c.pageEntry);continue}let l=await this.processMdxPage(a,{fileContents:e,frontmatter:n}),u={frontmatter:Ze(l.frontmatter,this.config.frontmatter),id:a.id,pathname:a.pathname,title:l.title,url:l.url},{sections:d}=o.extract(l.sectionAst,u);r.push(...d);let f=o.extractPage(l.sectionAst,u);f&&(f.content=`# ${l.title}\n\n${f.content}`,i.push(f)),this.cache.set(a.mdxFile,{contentHash:s,pageEntry:f??null,processedPage:l,sections:d})}catch(e){throw console.error(`Failed to process page: ${a.name}`),e}}for(let e of this.cache.keys())n.has(e)||this.cache.delete(e);this.config.extraFiles?.length&&await this.processExtraFiles(this.config.extraFiles,o,r,i);let s=p(JSON.stringify(r)),c=p(JSON.stringify(i));return{cachedPageCount:t,pages:{generatedAt:new Date().toISOString(),hash:c,pages:i,totalPages:i.length,version:1},sections:{generatedAt:new Date().toISOString(),hash:s,sections:r,totalSections:r.length,version:1},totalPageCount:e.length}}async scanPages(){let e=[],t=this.config.exclude??[],n=e=>{if(t.length===0)return!1;let n=w(this.config.routeDir,e);return t.some(e=>Pe(n,e,{matchBase:!0}))},r=async t=>{if(n(t)){this.config.verbose&&console.log(`Excluding directory: ${w(this.config.routeDir,t)}`);return}let i=await xe(t,{withFileTypes:!0}),a=i.filter(e=>e.name.endsWith(`.mdx`)&&!n(C(t,e.name)))??[];for(let n of a){let r=i.find(e=>e.name===`demos`),a=r?C(t,r.name):void 0,o=ae(C(t,n.name),this.config.routeDir),s=se(o);e.push({demosFolder:a,filePath:t,id:o.join(`-`).trim(),mdxFile:C(t,n.name),name:o.at(-1),pathname:s,url:this.config.baseUrl?new URL(s,this.config.baseUrl).toString():void 0}),this.config.verbose&&(console.log(`Found file: ${o.at(-1)}`),console.log(` Demos folder: ${a||`NOT FOUND`}`))}for(let e of i)e.isDirectory()&&await r(C(t,e.name))};return await r(this.config.routeDir),e}formatFrontmatterExpressions(e){return()=>t=>{k(t,`mdxFlowExpression`,(t,n,r)=>{t.value.trim()!==`frontmatter.description`||n===void 0||!r||(e.description?r.children.splice(n,1,{children:[{type:`text`,value:e.description}],type:`paragraph`}):r.children.splice(n,1))});let n=t,r=n.children.findIndex(e=>e.type!==`heading`||e.depth!==1?!1:e.children?.some(e=>e.type===`mdxTextExpression`&&e.value?.includes(`frontmatter`)));r>=0&&n.children.splice(r,1)}}transformRelativeUrls(){let e=this.config.baseUrl;return()=>t=>{e&&k(t,`link`,t=>{t.url.startsWith(`/`)&&(t.url=`${e}${t.url}`)})}}async processMdxContent(e,t,n){let r=await ut(),i=h({frontmatter:!0,gfm:!0,mdx:!0,plugins:[f,ct,this.propFormatter.propsToMarkdownList(),this.formatFrontmatterExpressions(n),r,$e(t.demosFolder,this.config.verbose),st,this.transformRelativeUrls()]});return await i.run(i.parse(e))}async processMdxPage(e,t){let{fileContents:n,frontmatter:r}=t??this.fileReader.readFileSync(e.mdxFile),i=await this.processMdxContent(n,e,r),a=h({extractMeta:{},frontmatter:!0,gfm:!0,mdx:!0,output:`md`,removeJsx:!0}),o=a.runSync(i),s=String(a.stringify(o)).replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,``).replace(/(^#{1,6} .*\\<[^>]+)>/gm,`$1\\>`),c=h({extractMeta:{},output:`md`}),l=String(await c.process(s)),u=r.title||e.name;return{content:l.trim(),frontmatter:r,rawContent:s.trim(),sectionAst:o,title:u,url:e.url}}async processExtraFiles(e,t,n,r){await Promise.all(e.map(async e=>{let i=e.contents;if(e.processAsMdx){let e=h({frontmatter:!0,gfm:!0,mdx:!0,output:`md`,plugins:[this.transformRelativeUrls()],removeJsx:!0});i=String(await e.process(i))}let a=[];e.title&&(a.push(`# ${e.title}`),a.push(``)),a.push(i);let o=a.join(`
|
|
8
|
+
`),s=h({gfm:!0,output:`md`}).parse(o),c={frontmatter:{},id:e.id,pathname:`/${e.id}`,title:e.title||e.id},{sections:l}=t.extract(s,c);n.push(...l);let u=t.extractPage(s,c);u&&r.push(u)}))}},ft=process.env.NODE_ENV===`development`,pt=`\0@qualcomm-ui/mdx-vite-plugin`,mt=`\0@qualcomm-ui/docs-plugin/config`,ht=`\0@qualcomm-ui/docs-plugin/markdown-content`,gt=class{buildCount=0;config=null;configFilePath=``;docPropsFilePath=``;exports={dir:``,enabled:!1,pathnames:[]};indexer;configLoader=null;knowledgeConfig=void 0;knowledgePageCache=new Map;pages=null;sections=null;routesDir;servers=[];timeout=void 0;exportsTimeout=void 0;watching=!1;cwd;init(e){this.cwd=e}getCwd(){return this.cwd}get docPropsDirectory(){return this.docPropsFilePath?this.docPropsFilePath.substring(0,this.docPropsFilePath.lastIndexOf(`/`)):``}get siteData(){let{filePath:e,...t}=this.config??{};return{config:t,exports:this.exports,navItems:this.indexer.navItems,pageDocProps:this.indexer.pageDocProps,pageMap:this.indexer.pageMap,searchIndex:this.indexer.searchIndex}}resolveDocProps(){if(!this.docPropsFilePath)return{};try{return JSON.parse(_e(this.docPropsFilePath,`utf-8`))?.props}catch{return console.debug(`Invalid doc props file. Unable to parse JSON. Please check the file`),{}}}createIndexer(e){this.knowledgePageCache.clear(),this.config=e,this.configFilePath=e.filePath,this.docPropsFilePath=e.typeDocProps?a(T(this.cwd,e.typeDocProps)):``,this.routesDir=a(T(e.appDirectory,e.pageDirectory)),this.knowledgeConfig=e.knowledge,this.indexer=new le({...e,srcDir:a(T(this.cwd,e.appDirectory)),typeDocProps:this.resolveDocProps()});let t=!!e.knowledge,n=e.knowledge?.outputPath??`exports`;this.exports={dir:t?`/${n}`:``,enabled:t,pathnames:[]}}buildIndex(e){let t=ye.sync([`${this.routesDir}/**/*.mdx`,`${this.routesDir}/**/*.tsx`],{absolute:!0,cwd:this.cwd});if(!t.length)return[];let n=Date.now(),r=this.indexer.buildIndex(t,e);return ft&&e&&console.debug(`${O.magenta.bold(`@qualcomm-ui/mdx-vite/docs-plugin:`)} Compiled search index in: ${O.blueBright.bold(Ne(Date.now()-n))}${this.indexer.cachedFileCount?O.greenBright.bold(` (${this.indexer.cachedFileCount}/${this.indexer.mdxFileCount} files cached)`):``}`),r}sendUpdate(){for(let e of this.servers){let t=e.moduleGraph.getModuleById(pt);t&&(e.moduleGraph.invalidateModule(t),e.reloadModule(t))}}handleChange(e={}){clearTimeout(this.timeout),this.timeout=setTimeout(()=>{this.buildIndex(!0),this.sendUpdate(),e?.onComplete?.()},300)}initWatchers(e){this.watching||=(this.initConfigWatcher(e),!0)}initConfigWatcher(e){let t=[this.configFilePath];this.docPropsFilePath&&t.push(this.docPropsFilePath),Ae.watch(t,{cwd:this.cwd}).on(`change`,()=>{console.debug(`qui-docs config changed, reloading plugin`),this.configLoader=new o({configFile:e});let t=this.configLoader.loadConfig();this.configFilePath=t.filePath,this.createIndexer(t),this.handleChange({onComplete:()=>{this.servers.forEach(e=>e.ws.send({type:`full-reload`}))}})})}async generateKnowledge(t){if(!this.knowledgeConfig)return;let n=C(t,this.knowledgeConfig.outputPath??`exports`),r=Date.now(),i=new e(ft),a=await new dt({baseUrl:this.knowledgeConfig.baseUrl,docPropsPath:this.docPropsFilePath||void 0,exclude:this.knowledgeConfig.exclude,extraFiles:this.knowledgeConfig.extraFiles,frontmatter:this.knowledgeConfig.frontmatter,pageIdPrefix:this.knowledgeConfig.pageIdPrefix,pages:this.knowledgeConfig.pages,routeDir:this.routesDir,sections:this.knowledgeConfig.sections},i,this.knowledgePageCache).generate();this.pages=a.pages,this.sections=a.sections,await be(n,{recursive:!0}),await Se(C(n,`sections.json`),JSON.stringify(a.sections,null,2),`utf-8`),await Se(C(n,`pages.json`),JSON.stringify(a.pages,null,2),`utf-8`),this.exports.pathnames=a.pages.pages.map(e=>e.pathname);let o=a.cachedPageCount>0?O.greenBright.bold(` (${a.cachedPageCount}/${a.totalPageCount} pages cached)`):``;console.debug(`${O.magenta.bold(`@qualcomm-ui/mdx-vite/docs-plugin:`)} Generated knowledge exports in: ${O.blueBright.bold(Ne(Date.now()-r))}${o}`)}debouncedGenerateKnowledge(e,t={}){this.knowledgeConfig&&(clearTimeout(this.exportsTimeout),this.exportsTimeout=setTimeout(()=>{this.generateKnowledge(e).then(()=>{t.onDone?.()})},500))}},_t=process.env.NODE_ENV===`development`,P=new gt;function vt(e){P.init(a(e?.cwd??process.cwd()));let t=new o(e||{}).loadConfig();P.createIndexer(t);let n;function r(){return n.publicDir||C(P.getCwd(),`public`)}return{apply(e,t){return t.mode===`development`&&t.command===`serve`||t.mode===`production`&&t.command===`build`},buildStart:async()=>{P.buildIndex(P.buildCount>0),P.buildCount++,!_t&&P.knowledgeConfig&&await P.generateKnowledge(r())},configResolved(e){n=e},configureServer:async t=>{_t&&(P.initWatchers(e?.configFile),P.knowledgeConfig&&await P.generateKnowledge(r()),t.middlewares.use(`/__qui-docs/pages`,(e,t)=>{t.setHeader(`Content-Type`,`application/json`),t.end(JSON.stringify(P.pages))}),t.middlewares.use(`/__qui-docs/sections`,(e,t)=>{t.setHeader(`Content-Type`,`application/json`),t.end(JSON.stringify(P.sections))}),t.watcher.on(`add`,e=>{e.endsWith(`.mdx`)&&P.handleChange({onComplete:()=>{t.ws.send({type:`full-reload`}),P.debouncedGenerateKnowledge(r())}})}),t.watcher.on(`unlink`,e=>{e.endsWith(`.mdx`)&&P.handleChange({onComplete:()=>{t.ws.send({type:`full-reload`}),P.debouncedGenerateKnowledge(r())}})}),P.servers.push(t))},handleHotUpdate:({file:e,modules:n,server:i})=>{if(e.endsWith(`.css`))return n;let o=a(e);if((!t.hotUpdateIgnore||!t.hotUpdateIgnore.test(o))&&o!==P.configFilePath){if(P.docPropsDirectory&&o.startsWith(P.docPropsFilePath))return[];if(e.endsWith(`.mdx`)){P.debouncedGenerateKnowledge(r());let t=P.buildIndex(!0);if(!i.moduleGraph.getModulesByFile(e)?.size)return console.debug(`no module found for file, returning`,e),[];let n=i.moduleGraph.getModuleById(pt);return n&&(i.moduleGraph.invalidateModule(n),i.ws.send({data:P.siteData,event:`qui-docs-plugin:refresh-site-data`,type:`custom`})),t.some(e=>e.metadata.changed.frontmatter)?(console.debug(`Frontmatter changed, reloading plugin to reflect changes in the page configuration`),n&&i.moduleGraph.invalidateModule(n),i.ws.send({type:`full-reload`}),[]):n?[n]:[]}}return[]},load:e=>{if(e===`\0@qualcomm-ui/mdx-vite-plugin`)return`export const siteData = ${JSON.stringify(P.siteData)}`;if(e===`\0@qualcomm-ui/docs-plugin/config`)return`export const quiDocsConfig = ${JSON.stringify({...P.config,cwd:P.cwd,publicDir:n.publicDir})}`;if(e===`\0@qualcomm-ui/docs-plugin/markdown-content`){if(_t){let{host:e=`localhost`,port:t=5173}=n.server,r=e===!0?`localhost`:e||`localhost`,i=`${n.server.https?`https`:`http`}://${r}:${t}`;return j`
|
|
9
9
|
export const getSections = () => fetch('${i}/__qui-docs/sections').then(r => r.json())
|
|
10
10
|
export const getPages = () => fetch('${i}/__qui-docs/pages').then(r => r.json())
|
|
11
11
|
`}return j`
|