Files
tuono/packages/vite-fs-router/src/index.ts
T

111 lines
2.6 KiB
TypeScript
Raw Normal View History

2024-04-27 14:00:17 +02:00
import { fileURLToPath, pathToFileURL } from 'url'
2024-04-27 19:08:23 +02:00
import { normalize } from 'path'
// eslint-disable-next-line sort-imports
2024-04-27 14:00:17 +02:00
import { makeCompile, splitFile } from './compiler'
import { SPLIT_PREFIX } from './constants'
2024-04-27 19:08:23 +02:00
import type { Plugin } from 'vite'
2024-04-27 14:00:17 +02:00
const ROUTES_DIRECTORY_PATH = 'src/routes'
const DEBUG = true
let lock = false
export function RouterGenerator(): Plugin {
const generate = async (): Promise<void> => {
2024-04-27 14:00:17 +02:00
if (lock) return
lock = true
try {
// TODO: generator function
// This generator function is from the router-generator package
2024-04-27 14:00:17 +02:00
console.log('Generating [generate fn]')
} catch (err) {
console.log(err)
} finally {
lock = false
}
}
2024-04-27 19:08:23 +02:00
const handleFile = async (file: string): Promise<void> => {
2024-04-27 14:00:17 +02:00
const filePath = normalize(file)
if (filePath.startsWith(ROUTES_DIRECTORY_PATH)) {
// TODO: generator function
console.log('Generating [handleFile fn]')
await generate()
2024-04-27 14:00:17 +02:00
}
}
return {
name: 'vite-plugin-fs-router-generator',
configResolved: async (): Promise<void> => {
await generate()
},
2024-04-27 19:08:23 +02:00
watchChange: async (
file: string,
context: { event: string },
): Promise<void> => {
2024-04-27 14:00:17 +02:00
if (['create', 'update', 'delete'].includes(context.event)) {
await handleFile(file)
}
},
}
}
export function RouterCodeSplitter(): Plugin {
const ROOT: string = process.cwd()
2024-04-27 14:00:17 +02:00
return {
name: 'vite-plugin-fs-router-code-splitter',
enforce: 'pre',
2024-04-27 19:08:23 +02:00
resolveId(source): string {
2024-04-27 14:00:17 +02:00
if (source.startsWith(SPLIT_PREFIX + ':')) {
return source.replace(SPLIT_PREFIX + ':', '')
}
2024-04-27 19:08:23 +02:00
return ''
2024-04-27 14:00:17 +02:00
},
2024-04-27 19:08:23 +02:00
async transform(code, id): Promise<void> {
2024-04-27 14:00:17 +02:00
const url = pathToFileURL(id)
url.searchParams.delete('v')
id = fileURLToPath(url).replace(/\\/g, '/')
const compile = makeCompile({ root: ROOT })
2024-04-27 14:00:17 +02:00
if (DEBUG) console.info('Route: ', id)
if (id.includes(SPLIT_PREFIX)) {
if (DEBUG) console.info('Splitting route: ', id)
const compiled = await splitFile({
code,
compile,
filename: id,
})
if (DEBUG) {
console.info('')
console.info('Split Output')
console.info('')
//console.info(compiled.code)
console.info('')
console.info('')
console.info('')
console.info('')
console.info('')
console.info('')
console.info('')
console.info('')
}
return compiled
}
},
}
}
2024-04-27 19:08:23 +02:00
export function ViteFsRouter(): Plugin[] {
2024-04-27 14:00:17 +02:00
return [RouterGenerator(), RouterCodeSplitter()]
}