Notes/apps/client/src/services/script_context.ts

37 lines
1.3 KiB
TypeScript
Raw Normal View History

import FrontendScriptApi, { type Entity } from "./frontend_script_api.js";
2025-01-09 18:07:02 +02:00
import utils from "./utils.js";
import froca from "./froca.js";
2024-12-21 16:43:50 +02:00
async function ScriptContext(startNoteId: string, allNoteIds: string[], originEntity: Entity | null = null, $container: JQuery<HTMLElement> | null = null) {
const modules: Record<string, { exports: unknown }> = {};
2021-04-16 22:57:37 +02:00
await froca.initializedPromise;
2020-03-26 16:21:17 +01:00
2021-04-16 22:57:37 +02:00
const startNote = await froca.getNote(startNoteId);
const allNotes = await froca.getNotes(allNoteIds);
if (!startNote) {
throw new Error(`Could not find start note ${startNoteId}.`);
}
return {
modules: modules,
2025-01-09 18:07:02 +02:00
notes: utils.toObject(allNotes, (note) => [note.noteId, note]),
apis: utils.toObject(allNotes, (note) => [note.noteId, new FrontendScriptApi(startNote, note, originEntity, $container)]),
require: (moduleNoteIds: string) => {
return (moduleName: string) => {
2025-01-09 18:07:02 +02:00
const candidates = allNotes.filter((note) => moduleNoteIds.includes(note.noteId));
const note = candidates.find((c) => c.title === moduleName);
if (!note) {
throw new Error(`Could not find module note ${moduleName}`);
}
return modules[note.noteId].exports;
2025-01-09 18:07:02 +02:00
};
}
};
}
2025-01-09 18:07:02 +02:00
export default ScriptContext;