2022-05-26 19:17:15 -07:00
import { ComponentParser } from 'sveld'
import * as svelte from 'svelte/compiler'
import fs from 'fs/promises'
import path from 'path'
2022-06-20 23:50:33 -07:00
import { preprocess } from '../../src/config/svelte.js'
2022-03-29 00:44:23 -07:00
export default function sveld ( ) {
2022-05-26 19:17:15 -07:00
return {
name : 'vite-plugin-sveld' ,
async transform ( src , id ) {
if ( id . endsWith ( '?raw&sveld' ) ) {
const raw = JSON . parse ( src . split ( 'export default ' ) [ 1 ] )
const data = await parseRaw ( raw , id )
return {
code : ` export default ${ JSON . stringify ( data ) } ` ,
map : null ,
}
}
} ,
// This generates a `COMPONENT_API.json` with sveld in the `/_app` folder on build, which is used by the docs about components (only when built statically)
async buildStart ( ) {
const output = { }
2022-06-17 19:58:01 -07:00
const componentFiles = await fs . readdir ( path . resolve ( './src/components' ) )
2022-05-26 19:17:15 -07:00
for ( const fileName of componentFiles . filter ( ( name ) => name . endsWith ( '.svelte' ) ) ) {
2022-06-17 19:58:01 -07:00
const filePath = path . resolve ( './src/components' , fileName )
2022-05-26 19:17:15 -07:00
const raw = ( await fs . readFile ( filePath ) ) . toString ( )
output [ fileName ] = await parseRaw ( raw , filePath )
}
try {
2022-06-17 19:58:01 -07:00
await fs . mkdir ( path . resolve ( './generated' ) )
2022-05-26 19:17:15 -07:00
} catch {
// Do nothing, directory already exists
}
2022-06-17 19:58:01 -07:00
await fs . writeFile ( path . resolve ( './generated/COMPONENT_API.json' ) , JSON . stringify ( output ) )
2022-05-26 19:17:15 -07:00
} ,
}
2022-03-29 22:06:43 -07:00
}
async function parseRaw ( raw , filePath ) {
2022-05-26 19:17:15 -07:00
let { code } = await svelte . preprocess ( raw , preprocess , {
filename : filePath ,
} )
return new ComponentParser ( {
verbose : false ,
} ) . parseSvelteComponent ( code , {
filePath ,
moduleName : filePath ,
} )
2022-05-20 00:10:45 -07:00
}