|
| 1 | +import { readFile } from 'node:fs/promises'; |
| 2 | +import type { Plugin } from 'vite'; |
| 3 | +import type { RollupOptions } from '../../src/rollup/types'; |
| 4 | +import type { Example, Module } from '../types'; |
| 5 | +import { getFilesInDirectory } from './helpers'; |
| 6 | + |
| 7 | +const examplesDirectory = new URL('../repl/examples', import.meta.url); |
| 8 | + |
| 9 | +export function examplesPlugin(): Plugin { |
| 10 | + return { |
| 11 | + async load(id) { |
| 12 | + if (id === 'examples.json') { |
| 13 | + const exampleFiles = await getFilesInDirectory(examplesDirectory); |
| 14 | + const examples: Example[] = await Promise.all( |
| 15 | + exampleFiles.map(async id => { |
| 16 | + const { |
| 17 | + entryModules = ['main.js'], |
| 18 | + options = {}, |
| 19 | + title |
| 20 | + }: { |
| 21 | + entryModules?: string[]; |
| 22 | + options?: RollupOptions; |
| 23 | + title: string; |
| 24 | + } = JSON.parse( |
| 25 | + await readFile(new URL(`examples/${id}/example.json`, examplesDirectory), 'utf8') |
| 26 | + ); |
| 27 | + const moduleFiles = await getFilesInDirectory( |
| 28 | + new URL(`examples/${id}/modules`, examplesDirectory) |
| 29 | + ); |
| 30 | + const modules: Module[] = await Promise.all( |
| 31 | + moduleFiles.map(async name => { |
| 32 | + const code = ( |
| 33 | + await readFile( |
| 34 | + new URL(`examples/${id}/modules/${name}`, examplesDirectory), |
| 35 | + 'utf8' |
| 36 | + ) |
| 37 | + ).trim(); |
| 38 | + return { code, isEntry: entryModules.includes(name), name }; |
| 39 | + }) |
| 40 | + ); |
| 41 | + |
| 42 | + modules.sort((a, b) => { |
| 43 | + if (a.name === 'main.js') return -1; |
| 44 | + if (b.name === 'main.js') return 1; |
| 45 | + if (a.isEntry) return -1; |
| 46 | + if (b.isEntry) return 1; |
| 47 | + return a.name < b.name ? -1 : 1; |
| 48 | + }); |
| 49 | + |
| 50 | + return { id, modules, options, title }; |
| 51 | + }) |
| 52 | + ); |
| 53 | + const examplesById: Record<string, Example> = {}; |
| 54 | + for (const example of examples) { |
| 55 | + examplesById[example.id] = example; |
| 56 | + } |
| 57 | + return JSON.stringify(examplesById); |
| 58 | + } |
| 59 | + }, |
| 60 | + name: 'examples', |
| 61 | + resolveId(source) { |
| 62 | + if (source === 'examples.json') { |
| 63 | + return source; |
| 64 | + } |
| 65 | + } |
| 66 | + }; |
| 67 | +} |
0 commit comments