feat: add module runtime lifecycle
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
import type { CapabilityId, ModuleId } from "./identifiers.js";
|
||||
import { moduleIdSchema } from "./identifiers.js";
|
||||
import { semanticVersionSchema } from "./versions.js";
|
||||
|
||||
export type Awaitable<Value> = Value | PromiseLike<Value>;
|
||||
|
||||
export interface RegisteredCapability {
|
||||
readonly id: CapabilityId;
|
||||
readonly implementation: unknown;
|
||||
readonly moduleId: ModuleId;
|
||||
readonly version: string;
|
||||
}
|
||||
|
||||
export interface CapabilityResolver {
|
||||
resolve(capabilityId: CapabilityId): RegisteredCapability | undefined;
|
||||
}
|
||||
|
||||
export interface CapabilityRegistrar extends CapabilityResolver {
|
||||
provide(capabilityId: CapabilityId, implementation: unknown): void;
|
||||
}
|
||||
|
||||
export interface ModuleRegistrationContext {
|
||||
readonly capabilities: CapabilityRegistrar;
|
||||
readonly moduleId: ModuleId;
|
||||
}
|
||||
|
||||
export interface ModuleRuntimeContext {
|
||||
readonly capabilities: CapabilityResolver;
|
||||
readonly moduleId: ModuleId;
|
||||
}
|
||||
|
||||
export interface ModuleRuntimeDefinition {
|
||||
readonly id: ModuleId;
|
||||
readonly register?: (context: ModuleRegistrationContext) => Awaitable<void>;
|
||||
readonly start?: (context: ModuleRuntimeContext) => Awaitable<void>;
|
||||
readonly stop?: (context: ModuleRuntimeContext) => Awaitable<void>;
|
||||
readonly version: string;
|
||||
}
|
||||
|
||||
const runtimeDefinitionKeys = new Set(["id", "register", "start", "stop", "version"]);
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
export function isModuleRuntimeDefinition(value: unknown): value is ModuleRuntimeDefinition {
|
||||
if (
|
||||
!isRecord(value) ||
|
||||
!moduleIdSchema.safeParse(value.id).success ||
|
||||
!semanticVersionSchema.safeParse(value.version).success
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (Object.keys(value).some((key) => !runtimeDefinitionKeys.has(key))) {
|
||||
return false;
|
||||
}
|
||||
return [value.register, value.start, value.stop].every(
|
||||
(hook) => hook === undefined || typeof hook === "function",
|
||||
);
|
||||
}
|
||||
|
||||
export function parseModuleRuntimeDefinition(value: unknown): ModuleRuntimeDefinition {
|
||||
if (!isModuleRuntimeDefinition(value)) {
|
||||
throw new TypeError("Invalid Ekklesia module runtime definition.");
|
||||
}
|
||||
return Object.freeze({
|
||||
id: value.id,
|
||||
version: value.version,
|
||||
...(value.register ? { register: value.register } : {}),
|
||||
...(value.start ? { start: value.start } : {}),
|
||||
...(value.stop ? { stop: value.stop } : {}),
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user