1+ const fs = require ( 'fs' ) ;
2+ const path = require ( 'path' ) ;
3+ const glob = require ( 'glob' ) ;
4+
5+ function codeImportPlugin ( context , options ) {
6+ return {
7+ name : 'code-import-plugin' ,
8+ async loadContent ( ) {
9+ // Find all markdown files in docs directory that might contain code imports
10+ const docsPath = path . join ( context . siteDir , 'docs' ) ;
11+
12+ const markdownFiles = [
13+ ...glob . sync ( '**/*.md' , { cwd : docsPath , absolute : true } ) ,
14+ ...glob . sync ( '**/*.mdx' , { cwd : docsPath , absolute : true } ) ,
15+ ] ;
16+
17+ // Process each markdown file for code imports
18+ const processedFiles = [ ] ;
19+
20+ for ( const filePath of markdownFiles ) {
21+ try {
22+ let content = fs . readFileSync ( filePath , 'utf8' ) ;
23+ let modified = false ;
24+
25+ // Process code blocks with file= syntax
26+ content = content . replace ( / ` ` ` ( \w + ) ? \s * ( f i l e = [ ^ \s \n ] + ) ( [ ^ \n ] * ) \n ( [ ^ ` ] * ?) ` ` ` / g, ( match , lang , fileParam , additionalMeta , existingContent ) => {
27+ try {
28+ const importPath = fileParam . replace ( 'file=' , '' ) ;
29+ const absoluteImportPath = path . resolve ( context . siteDir , importPath ) ;
30+ const importedContent = fs . readFileSync ( absoluteImportPath , 'utf8' ) ;
31+ modified = true ;
32+
33+ // Preserve the complete metadata including file= and any additional parameters
34+ const fullMeta = `${ fileParam } ${ additionalMeta } ` ;
35+ const metaStr = fullMeta ? ` ${ fullMeta } ` : '' ;
36+
37+ return `\`\`\`${ lang || '' } ${ metaStr } \n${ importedContent } \`\`\`` ;
38+ } catch ( error ) {
39+ console . warn ( `Could not import file ${ importPath } in ${ filePath } : ${ error . message } ` ) ;
40+ return match ; // Return original if import fails
41+ }
42+ } ) ;
43+
44+ if ( modified ) {
45+ processedFiles . push ( {
46+ path : filePath ,
47+ content : content ,
48+ originalPath : filePath
49+ } ) ;
50+ }
51+ } catch ( error ) {
52+ console . warn ( `Error processing file ${ filePath } : ${ error . message } ` ) ;
53+ }
54+ }
55+
56+ return { processedFiles } ;
57+ } ,
58+
59+ async contentLoaded ( { content, actions } ) {
60+ const { processedFiles } = content ;
61+
62+ // Write processed files back to disk during build
63+ for ( const file of processedFiles ) {
64+ try {
65+ fs . writeFileSync ( file . path , file . content , 'utf8' ) ;
66+ console . log ( `Processed code imports in: ${ path . relative ( context . siteDir , file . path ) } ` ) ;
67+ } catch ( error ) {
68+ console . error ( `Error writing processed file ${ file . path } : ${ error . message } ` ) ;
69+ }
70+ }
71+ }
72+ } ;
73+ }
74+
75+ module . exports = codeImportPlugin ;
0 commit comments