refactor(bgm): use virtual: module specifiers
Rename the plugin's virtual modules to virtual:bgm/packages and virtual:bgm/package/<id> so they read as plugin-provided modules rather than real packages. Update the unit and build integration tests.
This commit is contained in:
@@ -1,10 +1,19 @@
|
||||
/**
|
||||
* Vite plugin: resolve `bgm/<package>` imports to the package's JSON.
|
||||
* Vite plugin: resolve `virtual:bgm/packages` and `virtual:bgm/package/<id>`
|
||||
* imports to JSON.
|
||||
*
|
||||
* The loader reads a games root (markdown code blocks + real
|
||||
* yaml/json/toml/csv files), collects packages, and this plugin serves each
|
||||
* package as a module whose default export is the assembled JSON. Editing a
|
||||
* game definition hot-reloads the app via `addWatchFile`.
|
||||
* yaml/json/toml/csv files), collects packages, and this plugin serves them
|
||||
* as modules:
|
||||
*
|
||||
* - `virtual:bgm/packages` — the default export is an array of every
|
||||
* discovered package.
|
||||
* - `virtual:bgm/package/<id>` — the default export is that single package's
|
||||
* assembled JSON.
|
||||
*
|
||||
* The `virtual:` prefix marks these as plugin-provided modules, so they can't
|
||||
* be mistaken for real installed packages. Editing a game definition
|
||||
* hot-reloads the app via `addWatchFile`.
|
||||
*/
|
||||
import * as path from 'node:path';
|
||||
import type { Plugin } from 'vite';
|
||||
@@ -12,6 +21,10 @@ import { collectPackages, loadDefs } from './collect.js';
|
||||
import type { Package } from './types.js';
|
||||
|
||||
const VIRTUAL_PREFIX = '\0bgm:';
|
||||
/** Public specifier for the module that lists every package. */
|
||||
const PACKAGES = 'virtual:bgm/packages';
|
||||
/** Public specifier prefix for a single package module. */
|
||||
const PACKAGE = 'virtual:bgm/package/';
|
||||
|
||||
export interface BgmOptions {
|
||||
/** Absolute path to the games root (e.g. `<repo>/games`). */
|
||||
@@ -36,11 +49,17 @@ export function bgm(options: BgmOptions): Plugin {
|
||||
}
|
||||
},
|
||||
resolveId(id) {
|
||||
if (id.startsWith('bgm/')) return VIRTUAL_PREFIX + id;
|
||||
if (id === PACKAGES) return VIRTUAL_PREFIX + PACKAGES;
|
||||
if (id.startsWith(PACKAGE)) return VIRTUAL_PREFIX + id;
|
||||
},
|
||||
load(id) {
|
||||
if (!id.startsWith(VIRTUAL_PREFIX)) return;
|
||||
const name = id.slice(VIRTUAL_PREFIX.length + 'bgm/'.length);
|
||||
const virtual = id.slice(VIRTUAL_PREFIX.length);
|
||||
if (virtual === PACKAGES) {
|
||||
const packages = collect().map(toJson);
|
||||
return `export default ${JSON.stringify(packages)}`;
|
||||
}
|
||||
const name = virtual.slice(PACKAGE.length);
|
||||
const pkg = collect().find((p) => p.meta.id === name);
|
||||
if (!pkg) {
|
||||
throw new Error(`bgm package "${name}" not found`);
|
||||
|
||||
Reference in New Issue
Block a user