| 1 | import type { ResolvedSlidevOptions } from '@slidev/types' |
| 2 | import type { Plugin } from 'vite' |
| 3 | import fs from 'node:fs/promises' |
| 4 | import { slash } from '@antfu/utils' |
| 5 | import fg from 'fast-glob' |
| 6 | import { dirname, resolve } from 'pathe' |
| 7 | import { findDepPkgJsonPath } from 'vitefu' |
| 8 | import { toAtFS } from '../resolver' |
| 9 | |
| 10 | export function createMonacoTypesLoader({ userRoot, utils }: ResolvedSlidevOptions): Plugin { |
| 11 | return { |
| 12 | name: 'slidev:monaco-types-loader', |
| 13 | |
| 14 | resolveId(id) { |
| 15 | if (id.startsWith('/@slidev-monaco-types/')) |
| 16 | return id |
| 17 | return null |
| 18 | }, |
| 19 | |
| 20 | async load(id) { |
| 21 | if (!id.startsWith('/@slidev-monaco-types/')) |
| 22 | return null |
| 23 | |
| 24 | const url = new URL(id, 'http://localhost') |
| 25 | if (url.pathname === '/@slidev-monaco-types/resolve') { |
| 26 | const query = new URLSearchParams(url.search) |
| 27 | const pkg = query.get('pkg')! |
| 28 | const importer = query.get('importer') ?? userRoot |
| 29 | |
| 30 | const pkgJsonPath = await findDepPkgJsonPath(pkg, importer) |
| 31 | if (!pkgJsonPath) |
| 32 | throw new Error(`Package "${pkg}" not found in "${importer}"`) |
| 33 | const root = slash(dirname(pkgJsonPath)) |
| 34 | |
| 35 | const pkgJson = JSON.parse(await fs.readFile(pkgJsonPath, 'utf-8')) |
| 36 | let deps = Object.keys(pkgJson.dependencies ?? {}) |
| 37 | deps = deps.filter(pkg => !utils.isMonacoTypesIgnored(pkg)) |
| 38 | |
| 39 | return [ |
| 40 | `import "/@slidev-monaco-types/load?${new URLSearchParams({ root, name: pkgJson.name })}"`, |
| 41 | ...deps.map(dep => `import "/@slidev-monaco-types/resolve?${new URLSearchParams({ pkg: dep, importer: root })}"`), |
| 42 | ].join('\n') |
| 43 | } |
| 44 | |
| 45 | if (url.pathname === '/@slidev-monaco-types/load') { |
| 46 | const query = new URLSearchParams(url.search) |
| 47 | const root = query.get('root')! |
| 48 | const name = query.get('name')! |
| 49 | const files = await fg( |
| 50 | [ |
| 51 | '**/*.ts', |
| 52 | '**/*.mts', |
| 53 | '**/*.cts', |
| 54 | 'package.json', |
| 55 | ], |
| 56 | { |
| 57 | cwd: root, |
| 58 | followSymbolicLinks: true, |
| 59 | ignore: ['**/node_modules/**'], |
| 60 | }, |
| 61 | ) |
| 62 | |
| 63 | if (!files.length) |
| 64 | return '/** No files found **/' |
| 65 | |
| 66 | return [ |
| 67 | 'import { addFile } from "@slidev/client/setup/monaco.ts"', |
| 68 | ...files.map(file => `addFile(() => import(${ |
| 69 | JSON.stringify(`${toAtFS(resolve(root, file))}?monaco-types&raw`) |
| 70 | }), ${JSON.stringify(`node_modules/${name}/${file}`)})`), |
| 71 | ].join('\n') |
| 72 | } |
| 73 | }, |
| 74 | } |
| 75 | } |
| 76 |