refactor(onebot): compile and seal the action registry

Compile canonical names, aliases, stream kinds, documentation, and raw reservations into one immutable registry. Reject duplicate, undeclared, mismatched, or late handler registration before requests can be dispatched.
This commit is contained in:
DrSmoothl committed 2026-07-10 13:45:32 +08:00
1 parent 4825434ffa
commit 588fdab8de
9 files changed
+613 -104

No files matched your search

+174 -13
View File
@@ -1,15 +1,13 @@
// Action registry barrel — the single source of "which files contribute which
// actions", replacing three hand-synced lists that had to stay in lock-step:
// 1. ApiHandler's 12 `register as registerX` imports + 12 constructor calls,
// 2. each file's `export function register(h, ctx)` footer,
// 3. action-docs' own 13 imports + GROUPS array.
// Adding an action file now means editing exactly one place: ACTION_GROUPS.
// Action registry — the single source of the executable OneBot namespace.
//
// "Source file = domain category" is the existing convention (see action-docs),
// so the category label lives here too, making ACTION_GROUPS serve both runtime
// registration (via ALL_ACTIONS) and the doc collector (via the groups).
// ACTION_GROUPS is the authored input. ACTION_REGISTRY compiles it exactly
// once at module initialization, validating canonical names, aliases, stream
// classification, and the reserved raw-action namespace before any
// ApiHandler can start. Runtime registration and generated docs are projections
// of that same compiled value; neither is allowed to rebuild its own list.
import type { RegisteredActionSpec } from '../action-kit';
import type { ActionDoc, RegisteredActionSpec } from '../action-kit';
import type { ApiActionContext, ApiHandler } from '../api-handler';
import { actions as infoActions } from './info';
import { actions as messageActions } from './message';
import { actions as friendActions } from './friend';
@@ -29,7 +27,164 @@ export interface ActionGroup {
readonly actions: readonly RegisteredActionSpec[];
}
/** Every action, grouped by domain category. The single source of truth. */
export interface RawActionReservation {
/** Executable wire name reserved for a handler that cannot be an ActionSpec. */
readonly name: string;
/** Diagnostic owner. Usually identical to name; explicit for conflict logs. */
readonly canonical: string;
}
export type CompiledActionKind = RegisteredActionSpec['kind'] | 'raw';
export type ActionNameRole = 'canonical' | 'alias' | 'raw';
export interface CompiledAction {
readonly canonical: string;
readonly names: readonly string[];
readonly kind: RegisteredActionSpec['kind'];
readonly category: string;
readonly doc: ActionDoc;
readonly spec: RegisteredActionSpec;
}
interface ActionNameClaimBase {
readonly name: string;
readonly canonical: string;
readonly kind: CompiledActionKind;
readonly role: ActionNameRole;
}
export interface CompiledDeclarativeName extends ActionNameClaimBase {
readonly kind: RegisteredActionSpec['kind'];
readonly role: 'canonical' | 'alias';
readonly action: CompiledAction;
}
export interface CompiledRawName extends ActionNameClaimBase {
readonly kind: 'raw';
readonly role: 'raw';
}
export type CompiledActionName = CompiledDeclarativeName | CompiledRawName;
export interface CompiledActionRegistry {
/** Canonical declarative actions in authored group/action order. */
readonly actions: readonly CompiledAction[];
/** Every executable name, including aliases and reserved raw handlers. */
readonly executableNames: readonly CompiledActionName[];
/** Category order/counts used by the docs and UI. */
readonly categories: readonly { category: string; count: number }[];
readonly rawActions: readonly CompiledRawName[];
resolve(name: string): CompiledActionName | undefined;
register(h: ApiHandler, ctx: ApiActionContext): void;
}
function validateSpecProjection(spec: RegisteredActionSpec, doc: ActionDoc): void {
const canonical = spec.names[0];
if (!canonical || canonical.trim() === '') {
throw new Error(`Action registry invalid ${spec.kind} action: canonical name must not be empty`);
}
for (const name of spec.names) {
if (name.trim() === '') {
throw new Error(`Action registry invalid ${spec.kind} action canonical "${canonical}": executable name must not be empty`);
}
}
const aliases = spec.names.slice(1);
if (doc.name !== canonical || doc.aliases.length !== aliases.length || doc.aliases.some((name, i) => name !== aliases[i])) {
throw new Error(
`Action registry invalid ${spec.kind} action canonical "${canonical}": describe() names do not match executable names`,
);
}
const documentedKind = doc.stream === true ? 'stream' : 'normal';
if (documentedKind !== spec.kind) {
throw new Error(
`Action registry invalid ${spec.kind} action canonical "${canonical}": describe() reports kind ${documentedKind}`,
);
}
}
function conflictMessage(name: string, first: CompiledActionName, second: CompiledActionName): string {
return [
`Action registry conflict for executable name "${name}"`,
`canonical "${first.canonical}" (name "${first.name}", kind ${first.kind}, role ${first.role})`,
`canonical "${second.canonical}" (name "${second.name}", kind ${second.kind}, role ${second.role})`,
].join(': ');
}
/** Compile and validate a complete executable namespace. Exported so the
* conflict matrix can be tested without constructing an ApiHandler. */
export function compileActionRegistry(
groups: readonly ActionGroup[],
rawReservations: readonly RawActionReservation[] = [],
): CompiledActionRegistry {
const actions: CompiledAction[] = [];
const executableNames: CompiledActionName[] = [];
const rawActions: CompiledRawName[] = [];
const byName = new Map<string, CompiledActionName>();
const claim = (next: CompiledActionName): void => {
const previous = byName.get(next.name);
if (previous) throw new Error(conflictMessage(next.name, previous, next));
byName.set(next.name, next);
executableNames.push(next);
};
for (const group of groups) {
for (const spec of group.actions) {
const described = spec.describe();
validateSpecProjection(spec, described);
const canonical = spec.names[0]!;
const action: CompiledAction = Object.freeze({
canonical,
names: Object.freeze([...spec.names]),
kind: spec.kind,
category: group.category,
doc: Object.freeze({ ...described, category: group.category }),
spec,
});
actions.push(action);
action.names.forEach((name, index) => claim(Object.freeze({
name,
canonical,
kind: action.kind,
role: index === 0 ? 'canonical' : 'alias',
action,
})));
}
}
for (const reservation of rawReservations) {
if (reservation.name.trim() === '' || reservation.canonical.trim() === '') {
throw new Error('Action registry invalid raw action: canonical and executable name must not be empty');
}
const raw: CompiledRawName = Object.freeze({
name: reservation.name,
canonical: reservation.canonical,
kind: 'raw',
role: 'raw',
});
claim(raw);
rawActions.push(raw);
}
const categories = groups.map(({ category, actions: groupActions }) => Object.freeze({
category,
count: groupActions.length,
}));
return Object.freeze({
actions: Object.freeze(actions),
executableNames: Object.freeze(executableNames),
categories: Object.freeze(categories),
rawActions: Object.freeze(rawActions),
resolve: (name: string) => byName.get(name),
register: (h: ApiHandler, ctx: ApiActionContext) => {
for (const action of actions) action.spec.register(h, ctx);
},
});
}
/** Every declarative action, grouped by domain category. Authored input. */
export const ACTION_GROUPS: readonly ActionGroup[] = [
{ category: '信息', actions: infoActions },
{ category: '消息', actions: messageActions },
@@ -44,5 +199,11 @@ export const ACTION_GROUPS: readonly ActionGroup[] = [
{ category: '流式接口', actions: [...streamFileActions, ...streamDownloadActions] },
];
/** Flat list of every action spec, for one-shot registration onto an ApiHandler. */
export const ALL_ACTIONS: readonly RegisteredActionSpec[] = ACTION_GROUPS.flatMap((g) => g.actions);
/** The sole non-ActionSpec handler; reserved in the same namespace up front. */
export const HANDLE_QUICK_OPERATION_ACTION = '.handle_quick_operation';
export const RAW_ACTION_RESERVATIONS: readonly RawActionReservation[] = [
{ name: HANDLE_QUICK_OPERATION_ACTION, canonical: HANDLE_QUICK_OPERATION_ACTION },
];
/** Complete, validated runtime/docs registry. Compilation happens on import. */
export const ACTION_REGISTRY = compileActionRegistry(ACTION_GROUPS, RAW_ACTION_RESERVATIONS);