Skip to content

Commit

Permalink
feat: plugin asset utilities
Browse files Browse the repository at this point in the history
  • Loading branch information
johannschopplich committed Dec 11, 2024
1 parent 79c2a50 commit ca17144
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,5 @@ export const watchPostEffect = globalVue.watchPostEffect;
export const watchSyncEffect = globalVue.watchSyncEffect;

export * from "./composables";
export * from "./utils";
export { globalVue } from "./vue";
2 changes: 2 additions & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from "./logger";
export * from "./plugin";
50 changes: 50 additions & 0 deletions src/utils/plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
interface PluginAsset {
filename: string;
url: string;
}

const registeredAssets: PluginAsset[] = [];
const moduleCache = new Map();

export async function registerPluginAssets(assets: PluginAsset[]) {
if (!Array.isArray(assets)) {
throw new TypeError(`Expected an array, got ${typeof assets}`);
}

for (const asset of assets) {
if (
!registeredAssets.some((existing) => existing.filename === asset.filename)
) {
registeredAssets.push(asset);
}
}
}

export function resolvePluginAsset(filename: string) {
if (registeredAssets.length === 0) {
throw new Error("Plugin assets not registered");
}

const asset = registeredAssets.find((asset) => asset.filename === filename);

if (!asset) {
throw new Error(`Plugin asset "${filename}" not found`);
}

return asset;
}

export async function loadPluginModule(filename: string) {
if (!filename.endsWith(".js")) {
filename += ".js";
}

if (moduleCache.has(filename)) {
return moduleCache.get(filename);
}

const asset = resolvePluginAsset(filename);
const mod = await import(/* @vite-ignore */ asset.url);
moduleCache.set(filename, mod);
return mod;
}

0 comments on commit ca17144

Please sign in to comment.