|
| 1 | +import { Notice, TFile } from "obsidian"; |
| 2 | +import { IGenerateObject } from "automations/IGenerateObject"; |
| 3 | +import { get_tfiles_from_folder } from "helpers/FileManagement"; |
| 4 | +import { LocalSettings } from "cdm/SettingsModel"; |
| 5 | +import { LOGGER } from "services/Logger"; |
| 6 | + |
| 7 | +export class UserScriptFunctions implements IGenerateObject { |
| 8 | + constructor(private config: LocalSettings) { } |
| 9 | + |
| 10 | + async generate_user_script_functions( |
| 11 | + ): Promise<Map<string, Function>> { |
| 12 | + const user_script_functions: Map<string, Function> = new Map(); |
| 13 | + const files = |
| 14 | + get_tfiles_from_folder( |
| 15 | + this.config.formula_folder_path, |
| 16 | + ); |
| 17 | + |
| 18 | + if (!files) { |
| 19 | + return new Map(); |
| 20 | + } |
| 21 | + |
| 22 | + for (const file of files) { |
| 23 | + if (file.extension.toLowerCase() === "js") { |
| 24 | + await this.load_user_script_function( |
| 25 | + file, |
| 26 | + user_script_functions |
| 27 | + ); |
| 28 | + } |
| 29 | + } |
| 30 | + return user_script_functions; |
| 31 | + } |
| 32 | + |
| 33 | + async load_user_script_function( |
| 34 | + file: TFile, |
| 35 | + user_script_functions: Map<string, Function> |
| 36 | + ): Promise<void> { |
| 37 | + let req = (s: string) => { |
| 38 | + return window.require && window.require(s); |
| 39 | + }; |
| 40 | + let exp: Record<string, unknown> = {}; |
| 41 | + let mod = { |
| 42 | + exports: exp |
| 43 | + }; |
| 44 | + |
| 45 | + const file_content = await app.vault.read(file); |
| 46 | + const wrapping_fn = window.eval("(function anonymous(require, module, exports){" + file_content + "\n})"); |
| 47 | + wrapping_fn(req, mod, exp); |
| 48 | + const formula_function = exp['default'] || mod.exports; |
| 49 | + |
| 50 | + if (!formula_function) { |
| 51 | + const msg = `Failed to load user script ${file.path}. No exports detected.`; |
| 52 | + LOGGER.error(msg); |
| 53 | + new Notice( |
| 54 | + msg |
| 55 | + , 3000); |
| 56 | + throw new Error(msg); |
| 57 | + } |
| 58 | + if (!(formula_function instanceof Function)) { |
| 59 | + const msg = `Failed to load user script ${file.path}. Default export is not a function.` |
| 60 | + LOGGER.error(msg); |
| 61 | + new Notice( |
| 62 | + msg |
| 63 | + , 3000); |
| 64 | + throw new Error(msg); |
| 65 | + } |
| 66 | + user_script_functions.set(`${file.basename}`, formula_function); |
| 67 | + } |
| 68 | + |
| 69 | + async generate_object(): Promise<Record<string, unknown>> { |
| 70 | + const user_script_functions = await this.generate_user_script_functions(); |
| 71 | + return Object.fromEntries(user_script_functions); |
| 72 | + } |
| 73 | +} |
0 commit comments