Engine api
This commit is contained in:
+248
@@ -0,0 +1,248 @@
|
||||
// engine access: hooks on the engine's own methods, like neoforge's mixins, and the global the bworld/engine shim reads.
|
||||
// see docs/modding/misc/engine.md and docs/modding_plan.md
|
||||
import { GAME_VERSION } from "./constants.ts";
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
type Method = (...args: any[]) => any;
|
||||
type MethodOf<T, K extends keyof T> = T[K] extends Method ? T[K] : never;
|
||||
|
||||
export interface HookHandlers<T, K extends keyof T> {
|
||||
// runs first. change args in place, or return { result } to skip the method and everything after
|
||||
before?(self: T, args: Parameters<MethodOf<T, K>>): { result: ReturnType<MethodOf<T, K>> } | void;
|
||||
// wraps the method, calling original (or not)
|
||||
replace?(
|
||||
self: T,
|
||||
args: Parameters<MethodOf<T, K>>,
|
||||
original: (...args: Parameters<MethodOf<T, K>>) => ReturnType<MethodOf<T, K>>,
|
||||
): ReturnType<MethodOf<T, K>>;
|
||||
// runs last, and returns the result the caller gets. returning undefined keeps the result it was given
|
||||
after?(
|
||||
self: T,
|
||||
args: Parameters<MethodOf<T, K>>,
|
||||
result: ReturnType<MethodOf<T, K>>,
|
||||
): ReturnType<MethodOf<T, K>> | void;
|
||||
// lower runs earlier, the default is 1000. ties go in load order
|
||||
priority?: number;
|
||||
}
|
||||
|
||||
export type Hook = <T extends object, K extends keyof T>(
|
||||
target: T,
|
||||
method: K,
|
||||
handlers: HookHandlers<T, K>,
|
||||
) => () => void;
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
type AnyHandlers = HookHandlers<any, any>;
|
||||
|
||||
interface Entry {
|
||||
mod: string;
|
||||
handlers: AnyHandlers;
|
||||
priority: number;
|
||||
// when it was hooked, for ties
|
||||
order: number;
|
||||
}
|
||||
|
||||
// one hooked method. the original goes back once its last hook is gone, so a method nobody hooks costs nothing
|
||||
interface Hooked {
|
||||
target: object;
|
||||
key: PropertyKey;
|
||||
name: string;
|
||||
// how it was before the first hook: its own property on target, or inherited when undefined
|
||||
descriptor: PropertyDescriptor | undefined;
|
||||
original: Method;
|
||||
entries: Entry[];
|
||||
}
|
||||
|
||||
const hooked = new Map<object, Map<PropertyKey, Hooked>>();
|
||||
let next_order = 0;
|
||||
|
||||
// the mod whose script is loading or running setup. hooks are made then, so each one knows its mod
|
||||
let loading: { mod: string; engine_access: boolean } | undefined;
|
||||
|
||||
function log(mod: string, what: string, e: unknown) {
|
||||
console.error(`[${mod}] ${what} threw:`, e);
|
||||
}
|
||||
|
||||
// the wrapper that replaces the method. it's made again whenever the hooks change, with only the steps they need, so
|
||||
// a method with only after hooks doesn't walk empty before and replace lists every call
|
||||
function wrapper(state: Hooked): Method {
|
||||
const { original, name } = state;
|
||||
const before = state.entries.filter((e) => e.handlers.before);
|
||||
const replace = state.entries.filter((e) => e.handlers.replace);
|
||||
const after = state.entries.filter((e) => e.handlers.after);
|
||||
|
||||
// the replace hooks, the first outermost, around the original
|
||||
// deno-lint-ignore no-explicit-any
|
||||
const call = (self: any, args: any[], i: number): any => {
|
||||
if (i === replace.length) return original.apply(self, args);
|
||||
const { mod, handlers } = replace[i];
|
||||
let called = false;
|
||||
let inner: unknown;
|
||||
const next = (...next_args: unknown[]) => {
|
||||
called = true;
|
||||
inner = call(self, next_args, i + 1);
|
||||
return inner;
|
||||
};
|
||||
try {
|
||||
return handlers.replace!(self, args, next);
|
||||
} catch (e) {
|
||||
log(mod, `a replace hook on ${name}`, e);
|
||||
// skipped: what it got from the method if it called it, so the method doesn't run twice
|
||||
return called ? inner : call(self, args, i + 1);
|
||||
}
|
||||
};
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
return function (this: any, ...args: any[]) {
|
||||
for (const { mod, handlers } of before) {
|
||||
try {
|
||||
const skip = handlers.before!(this, args);
|
||||
if (skip) return skip.result;
|
||||
} catch (e) {
|
||||
log(mod, `a before hook on ${name}`, e);
|
||||
}
|
||||
}
|
||||
let result = call(this, args, 0);
|
||||
for (const { mod, handlers } of after) {
|
||||
try {
|
||||
const changed = handlers.after!(this, args, result);
|
||||
if (changed !== undefined) result = changed;
|
||||
} catch (e) {
|
||||
log(mod, `an after hook on ${name}`, e);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
};
|
||||
}
|
||||
|
||||
function install(state: Hooked) {
|
||||
if (state.entries.length > 0) {
|
||||
Object.defineProperty(state.target, state.key, {
|
||||
value: wrapper(state),
|
||||
writable: true,
|
||||
configurable: true,
|
||||
enumerable: state.descriptor?.enumerable ?? false,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (state.descriptor) {
|
||||
Object.defineProperty(state.target, state.key, state.descriptor);
|
||||
} else {
|
||||
delete (state.target as Record<PropertyKey, unknown>)[state.key];
|
||||
}
|
||||
hooked.get(state.target)?.delete(state.key);
|
||||
}
|
||||
|
||||
function method_name(target: object, key: PropertyKey) {
|
||||
const owner = typeof target === "function" ? target.name : target.constructor?.name;
|
||||
return owner && owner !== "Object" ? `${owner}.${String(key)}` : String(key);
|
||||
}
|
||||
|
||||
// hooks target's method for the mod that's loading. see HookHandlers
|
||||
export const hook: Hook = (target, method, handlers) => {
|
||||
if (!loading) throw new Error("hook can only be called while a mod's script loads or runs its setup");
|
||||
if (!loading.engine_access) {
|
||||
throw new Error(`${loading.mod} hooks the engine without "engine_access" in its manifest`);
|
||||
}
|
||||
const key = method as PropertyKey;
|
||||
let by_key = hooked.get(target);
|
||||
let state = by_key?.get(key);
|
||||
if (!state) {
|
||||
const original = (target as Record<PropertyKey, unknown>)[key];
|
||||
if (typeof original !== "function") throw new Error(`${method_name(target, key)} isn't a method`);
|
||||
if (!Object.isExtensible(target)) throw new Error(`${method_name(target, key)} can't be hooked`);
|
||||
state = {
|
||||
target,
|
||||
key,
|
||||
name: method_name(target, key),
|
||||
descriptor: Object.getOwnPropertyDescriptor(target, key),
|
||||
original: original as Method,
|
||||
entries: [],
|
||||
};
|
||||
if (state.descriptor && !state.descriptor.configurable) {
|
||||
throw new Error(`${state.name} can't be hooked`);
|
||||
}
|
||||
if (!by_key) hooked.set(target, by_key = new Map());
|
||||
by_key.set(key, state);
|
||||
}
|
||||
const entry: Entry = {
|
||||
mod: loading.mod,
|
||||
handlers: handlers as AnyHandlers,
|
||||
priority: handlers.priority ?? 1000,
|
||||
order: next_order++,
|
||||
};
|
||||
state.entries.push(entry);
|
||||
state.entries.sort((a, b) => a.priority - b.priority || a.order - b.order);
|
||||
install(state);
|
||||
|
||||
const hooked_state = state;
|
||||
return () => {
|
||||
const i = hooked_state.entries.indexOf(entry);
|
||||
if (i === -1) return;
|
||||
hooked_state.entries.splice(i, 1);
|
||||
install(hooked_state);
|
||||
};
|
||||
};
|
||||
|
||||
// puts every hooked method back, before a game loads its mods. tests start many games in one realm, and a client
|
||||
// joining another server leaves the last one's mods behind
|
||||
export function clear_hooks() {
|
||||
for (const by_key of [...hooked.values()]) {
|
||||
for (const state of [...by_key.values()]) {
|
||||
state.entries = [];
|
||||
install(state);
|
||||
}
|
||||
}
|
||||
hooked.clear();
|
||||
}
|
||||
|
||||
// runs fn as the mod: hook knows whose hooks it makes, and bworld/engine refuses mods without engine_access
|
||||
export async function loading_mod<T>(mod: string, engine_access: boolean, fn: () => Promise<T>): Promise<T> {
|
||||
const previous = loading;
|
||||
loading = { mod, engine_access };
|
||||
try {
|
||||
return await fn();
|
||||
} finally {
|
||||
loading = previous;
|
||||
}
|
||||
}
|
||||
|
||||
// the engine's modules on each side, what mods get as engine
|
||||
export interface EngineModules {
|
||||
common?: Record<string, unknown>;
|
||||
server?: Record<string, unknown>;
|
||||
client?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
// what bworld/engine reads, see common/mod_api/engine.ts
|
||||
export interface EngineGlobal {
|
||||
version: string;
|
||||
engine: EngineModules;
|
||||
hook: Hook;
|
||||
// throws unless the mod that's loading has engine_access
|
||||
check_access(): void;
|
||||
}
|
||||
|
||||
export const ENGINE_GLOBAL = "__bworld_engine";
|
||||
|
||||
// puts a side's modules where bworld/engine finds them. a realm with the server and a client in it, like tests, gets
|
||||
// both
|
||||
export function expose_engine(modules: EngineModules) {
|
||||
const global = globalThis as unknown as Record<string, EngineGlobal | undefined>;
|
||||
const existing = global[ENGINE_GLOBAL];
|
||||
if (existing) {
|
||||
Object.assign(existing.engine, modules);
|
||||
return;
|
||||
}
|
||||
global[ENGINE_GLOBAL] = {
|
||||
version: GAME_VERSION,
|
||||
engine: { ...modules },
|
||||
hook,
|
||||
check_access() {
|
||||
if (!loading) throw new Error("bworld/engine can only be imported by a mod's script");
|
||||
if (!loading.engine_access) {
|
||||
throw new Error(`${loading.mod} imports bworld/engine without "engine_access" in its manifest`);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user