diff --git a/packages/onebot/src/action-docs.ts b/packages/onebot/src/action-docs.ts index 77f121e4..ef485160 100644 --- a/packages/onebot/src/action-docs.ts +++ b/packages/onebot/src/action-docs.ts @@ -4,27 +4,28 @@ // structured doc list + a Markdown view. The metadata is carried on the same // values that drive runtime validation, so docs cannot drift from behavior. // -// Coverage note: the ~15 genuinely irregular actions in `actions/extended.ts` -// that remain on the legacy `h.registerAction(...)` path are NOT ActionSpecs -// and so do not appear here — that is the documented irregular tail. +// The reserved `.handle_quick_operation` raw handler deliberately has no +// ActionSpec/doc entry; every catalogued action comes from ACTION_REGISTRY. // // The serving SURFACE (WebUI panel / OpenAPI export / static markdown) is a // deferred product decision; this module produces format-agnostic data plus a // Markdown default. Point any renderer at `collectActionDocs()`. import type { ActionDoc } from './action-kit'; -import { ACTION_GROUPS } from './actions'; +import { ACTION_REGISTRY } from './actions'; /** Every declarative action's doc (with category), sorted by name. */ export function collectActionDocs(): ActionDoc[] { - return ACTION_GROUPS - .flatMap(({ category, actions }) => actions.map((s) => ({ ...s.describe(), category }))) + return ACTION_REGISTRY.actions + // Preserve the collector's value semantics: callers may sort/transform + // docs without mutating the process-wide compiled registry. + .map(({ doc }) => structuredClone(doc)) .sort((a, b) => a.name.localeCompare(b.name)); } /** Distinct categories with action counts. */ export function collectCategories(): Array<{ category: string; count: number }> { - return ACTION_GROUPS.map(({ category, actions }) => ({ category, count: actions.length })); + return ACTION_REGISTRY.categories.map(({ category, count }) => ({ category, count })); } function paramRow(p: ActionDoc['params'][number]): string { @@ -57,7 +58,7 @@ export function renderActionDocsMarkdown(docs: readonly ActionDoc[] = collectAct '# OneBot Actions', '', '> 由 `packages/onebot/src/action-docs.ts` 从各 `ActionSpec.describe()` 自动生成,请勿手改。', - '> 仅覆盖声明式 action;`extended.ts` 中少量走 legacy `registerAction` 的不规则 action 不在此列。', + '> 覆盖完整声明式 Action registry;保留的 raw `.handle_quick_operation` handler 不生成文档。', '', `共 ${docs.length} 个声明式 action。`, '', diff --git a/packages/onebot/src/action-kit.ts b/packages/onebot/src/action-kit.ts index a06207ce..14bf0efb 100644 --- a/packages/onebot/src/action-kit.ts +++ b/packages/onebot/src/action-kit.ts @@ -447,12 +447,18 @@ type Handler = (params: JsonObject) => Promise; * both kinds in one flat list without coupling to either concrete generic. */ export interface RegisteredActionSpec { + /** Runtime dispatch kind. Kept on the spec so the compiled registry can + * validate the executable namespace without inferring behavior from docs. */ + readonly kind: 'normal' | 'stream'; + /** Canonical name first, followed by every executable alias. */ + readonly names: readonly string[]; describe(): ActionDoc; register(h: ApiHandler, ctx: ApiActionContext): void; } export interface ActionSpec extends RegisteredActionSpec { - readonly names: string[]; + readonly kind: 'normal'; + readonly names: readonly string[]; readonly params: S; /** Pure: coerce + validate + cross-field, no ctx, no I/O. The test surface. */ parse(raw: JsonObject): CoerceResult>; @@ -482,7 +488,7 @@ interface ActionDef { const wording = (e: Err): string => (e.field ? `${e.field}: ${e.reason}` : e.reason); export function defineAction(def: ActionDef): ActionSpec { - const names = typeof def.name === 'string' ? [def.name] : [...def.name]; + const names = Object.freeze(typeof def.name === 'string' ? [def.name] : [...def.name]); const rules: readonly CrossFieldRule[] = def.rules ? def.rules(RULES as unknown as RuleBuilders>) : []; @@ -510,6 +516,7 @@ export function defineAction(def: ActionDef): ActionSpec { }; return { + kind: 'normal', names, params: def.params, parse, @@ -567,7 +574,8 @@ interface StreamActionDef { } export interface StreamActionSpec extends RegisteredActionSpec { - readonly names: string[]; + readonly kind: 'stream'; + readonly names: readonly string[]; readonly params: S; parse(raw: JsonObject): CoerceResult>; } @@ -587,6 +595,7 @@ export function defineStreamAction(def: StreamActionDef): Str }); return { + kind: 'stream', names: base.names, params: def.params, parse: base.parse, diff --git a/packages/onebot/src/actions/index.ts b/packages/onebot/src/actions/index.ts index 5fbd5e92..3a79035f 100644 --- a/packages/onebot/src/actions/index.ts +++ b/packages/onebot/src/actions/index.ts @@ -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(); + + 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); diff --git a/packages/onebot/src/api-handler.ts b/packages/onebot/src/api-handler.ts index b404709a..57ea12b9 100644 --- a/packages/onebot/src/api-handler.ts +++ b/packages/onebot/src/api-handler.ts @@ -1,8 +1,12 @@ import { renderParamsVerbose, summarizeParams } from '@snowluma/common/log-summary'; import { createLogger, getLogLevel, nextRequestId, runWithRequestId, type Logger } from '@snowluma/common/logger'; import type { BridgeInterface } from '@snowluma/core/bridge-interface'; -import { ALL_ACTIONS } from './actions'; -import { registerActions } from './action-kit'; +import { + ACTION_REGISTRY, + HANDLE_QUICK_OPERATION_ACTION, + type CompiledActionKind, + type CompiledActionRegistry, +} from './actions'; import type { ForwardPreviewMeta } from './modules/message-actions'; import type { JsonObject, JsonValue, MessageMeta } from './types'; import { RETCODE, failedResponse, okResponse } from './types'; @@ -75,6 +79,12 @@ export interface ApiActionContext { type ActionHandler = (params: JsonObject, sink?: StreamSink) => Promise; +interface RegisteredHandler { + readonly handler: ActionHandler; + readonly canonical: string; + readonly kind: CompiledActionKind; +} + /** A handled-action record handed to debug observers. */ export interface ActionRecord { action: string; @@ -85,10 +95,11 @@ export interface ActionRecord { export type ActionObserver = (rec: ActionRecord) => void; export class ApiHandler { - private readonly handlers = new Map(); - /** Names that answer with a multi-frame Stream API response (#163). The - * network adapter consults this BEFORE dispatch to pick streaming output. */ - private readonly streamActions = new Set(); + /** Handler + dispatch kind live in one record so stream classification can + * never outlive or drift from the handler it describes. */ + private readonly handlers = new Map(); + private readonly registry: CompiledActionRegistry; + private registrationOpen = true; private readonly log: Logger; /** Debug-stream taps — notified after every handled action. Attached * on-demand (ref-counted) by the WebUI debug stream. */ @@ -100,43 +111,106 @@ export class ApiHandler { return () => { this.observers.delete(cb); }; } - constructor(context: ApiActionContext, uin?: number) { + constructor( + context: ApiActionContext, + uin?: number, + registry: CompiledActionRegistry = ACTION_REGISTRY, + ) { + this.registry = registry; this.log = typeof uin === 'number' && uin > 0 ? moduleLog.child({ uin }) : moduleLog; - registerActions(this, context, ALL_ACTIONS); + try { + registry.register(this, context); - // The one non-ActionSpec handler: `.handle_quick_operation` needs the - // ApiHandler itself (to re-drive actions via executeQuickOperation), which - // ActionSpec.run's (params, ctx) signature can't supply — so it's the sole - // raw registration, kept here rather than in an action file's footer. - this.registerAction('.handle_quick_operation', async (params) => { - const opContext = params.context as JsonObject | undefined; - const operation = params.operation as Record | undefined; - if (!opContext || !operation) return failedResponse(RETCODE.BAD_REQUEST, 'context and operation are required'); - const { executeQuickOperation } = await import('./network/quick-operation'); - await executeQuickOperation(opContext, operation, this); - return okResponse(); - }); + // The one non-ActionSpec handler: `.handle_quick_operation` needs the + // ApiHandler itself (to re-drive actions via executeQuickOperation), which + // ActionSpec.run's (params, ctx) signature can't supply — so it's the sole + // raw registration, kept here rather than in an action file's footer. + this.registerRawAction(HANDLE_QUICK_OPERATION_ACTION, async (params) => { + const opContext = params.context as JsonObject | undefined; + const operation = params.operation as Record | undefined; + if (!opContext || !operation) return failedResponse(RETCODE.BAD_REQUEST, 'context and operation are required'); + const { executeQuickOperation } = await import('./network/quick-operation'); + await executeQuickOperation(opContext, operation, this); + return okResponse(); + }); + this.assertRegistryFullyBound(); + } finally { + // registerAction/registerStreamAction are the constructor-time port used + // by ActionSpec. Once construction finishes (successfully or not), the + // runtime namespace is immutable and cannot bypass the compiled registry. + this.registrationOpen = false; + } } registerAction(action: string, handler: ActionHandler): void { - this.handlers.set(action, handler); + this.registerHandler(action, handler, 'normal'); } /** Register a Stream API action — dispatched exactly like a normal action, * but flagged so adapters stream its frames (the handler receives a sink). */ registerStreamAction(action: string, handler: ActionHandler): void { - this.handlers.set(action, handler); - this.streamActions.add(action); + this.registerHandler(action, handler, 'stream'); + } + + private registerRawAction(action: string, handler: ActionHandler): void { + this.registerHandler(action, handler, 'raw'); + } + + private registerHandler(action: string, handler: ActionHandler, kind: CompiledActionKind): void { + if (!this.registrationOpen) { + throw new Error( + `Action registry is sealed; cannot register canonical "${action}" (name "${action}", kind ${kind})`, + ); + } + const claim = this.registry.resolve(action); + if (!claim) { + throw new Error( + `Action registration is not declared by the compiled registry: ` + + `canonical "${action}" (name "${action}", kind ${kind})`, + ); + } + const canonical = claim.canonical; + const existing = this.handlers.get(action); + if (existing) { + throw new Error( + `Action handler conflict for executable name "${action}": ` + + `canonical "${existing.canonical}" (name "${action}", kind ${existing.kind}) conflicts with ` + + `canonical "${canonical}" (name "${action}", kind ${kind})`, + ); + } + if (claim.kind !== kind) { + throw new Error( + `Action handler kind mismatch for canonical "${canonical}" (name "${action}"): ` + + `registry kind ${claim.kind}, registration kind ${kind}`, + ); + } + this.handlers.set(action, { handler, canonical, kind }); + } + + private assertRegistryFullyBound(): void { + for (const claim of this.registry.executableNames) { + if (this.handlers.has(claim.name)) continue; + throw new Error( + `Action registry claim has no handler: canonical "${claim.canonical}" ` + + `(name "${claim.name}", kind ${claim.kind})`, + ); + } + if (this.handlers.size !== this.registry.executableNames.length) { + throw new Error( + `Action registry binding count mismatch: ${this.handlers.size} handlers for ` + + `${this.registry.executableNames.length} executable names`, + ); + } } /** Whether `action` answers with a multi-frame Stream API response. */ isStreamAction(action: string): boolean { - return this.streamActions.has(action); + return this.handlers.get(action)?.kind === 'stream'; } async handle(action: string, params: JsonObject, sink?: StreamSink): Promise { - const handler = this.handlers.get(action); - if (!handler) { + const registered = this.handlers.get(action); + if (!registered) { this.log.debug('unknown action %s', action); return failedResponse(RETCODE.UNKNOWN_ACTION, 'unknown action'); } @@ -146,9 +220,9 @@ export class ApiHandler { // the wrap + id allocation when trace is actually live, so the default // path stays allocation-free. if (getLogLevel() !== 'trace') { - return this.runAction(action, handler, params, sink); + return this.runAction(action, registered.handler, params, sink); } - return runWithRequestId(nextRequestId(), () => this.runAction(action, handler, params, sink)); + return runWithRequestId(nextRequestId(), () => this.runAction(action, registered.handler, params, sink)); } private async runAction( diff --git a/packages/onebot/tests/action-registry.test.ts b/packages/onebot/tests/action-registry.test.ts new file mode 100644 index 00000000..8919e227 --- /dev/null +++ b/packages/onebot/tests/action-registry.test.ts @@ -0,0 +1,223 @@ +import { describe, expect, it } from 'vitest'; +import { defineAction, defineStreamAction, type RegisteredActionSpec } from '../src/action-kit'; +import { ApiHandler, type ApiActionContext } from '../src/api-handler'; +import { + ACTION_REGISTRY, + HANDLE_QUICK_OPERATION_ACTION, + RAW_ACTION_RESERVATIONS, + compileActionRegistry, + type ActionGroup, + type RawActionReservation, +} from '../src/actions'; +import { collectActionDocs } from '../src/action-docs'; +import { okResponse } from '../src/types'; + +type ActionNames = string | readonly [string, ...string[]]; + +function normal(name: ActionNames): RegisteredActionSpec { + return defineAction({ name, params: {}, run: () => okResponse() }); +} + +function stream(name: ActionNames): RegisteredActionSpec { + return defineStreamAction({ name, params: {}, run: () => okResponse() }); +} + +function groups(...actions: RegisteredActionSpec[]): readonly ActionGroup[] { + return [{ category: 'test', actions }]; +} + +function conflict( + actionGroups: readonly ActionGroup[], + raw: readonly RawActionReservation[] = [], +): string { + try { + compileActionRegistry(actionGroups, raw); + } catch (error) { + if (error instanceof Error) return error.message; + throw error; + } + throw new Error('expected registry compilation to fail'); +} + +describe('compileActionRegistry namespace conflicts', () => { + it('rejects canonical ↔ canonical', () => { + const message = conflict(groups(normal('shared'), normal('shared'))); + expect(message).toContain('executable name "shared"'); + expect(message).toContain('canonical "shared" (name "shared", kind normal, role canonical)'); + }); + + it.each([ + ['canonical first', [normal('shared'), normal(['owner', 'shared'])]], + ['alias first', [normal(['owner', 'shared']), normal('shared')]], + ] as const)('rejects canonical ↔ alias (%s)', (_label, specs) => { + const message = conflict(groups(...specs)); + expect(message).toContain('canonical "shared" (name "shared", kind normal, role canonical)'); + expect(message).toContain('canonical "owner" (name "shared", kind normal, role alias)'); + }); + + it('rejects alias ↔ alias', () => { + const message = conflict(groups(normal(['first', 'shared']), normal(['second', 'shared']))); + expect(message).toContain('canonical "first" (name "shared", kind normal, role alias)'); + expect(message).toContain('canonical "second" (name "shared", kind normal, role alias)'); + }); + + it('rejects normal ↔ stream and reports both kinds', () => { + const message = conflict(groups(normal('shared'), stream('shared'))); + expect(message).toContain('canonical "shared" (name "shared", kind normal, role canonical)'); + expect(message).toContain('canonical "shared" (name "shared", kind stream, role canonical)'); + }); + + it.each([ + ['canonical', normal(HANDLE_QUICK_OPERATION_ACTION), 'role canonical'], + ['alias', normal(['owner', HANDLE_QUICK_OPERATION_ACTION]), 'role alias'], + ] as const)('rejects a declarative %s colliding with a reserved raw action', (_label, spec, role) => { + const message = conflict(groups(spec), [ + { name: HANDLE_QUICK_OPERATION_ACTION, canonical: HANDLE_QUICK_OPERATION_ACTION }, + ]); + expect(message).toContain(`name "${HANDLE_QUICK_OPERATION_ACTION}"`); + expect(message).toContain(`kind normal, ${role}`); + expect(message).toContain('kind raw, role raw'); + }); + + it('rejects duplicate raw reservations', () => { + const message = conflict([], [ + { name: 'raw', canonical: 'first-raw' }, + { name: 'raw', canonical: 'second-raw' }, + ]); + expect(message).toContain('canonical "first-raw" (name "raw", kind raw, role raw)'); + expect(message).toContain('canonical "second-raw" (name "raw", kind raw, role raw)'); + }); +}); + +describe('compiled production Action registry', () => { + it('preserves all 179 canonical Action docs', () => { + expect(ACTION_REGISTRY.actions).toHaveLength(179); + expect(collectActionDocs()).toHaveLength(179); + }); + + it('resolves every executable name to exactly one canonical doc', () => { + const docs = new Map(collectActionDocs().map((doc) => [doc.name, doc])); + + for (const executable of ACTION_REGISTRY.executableNames) { + expect(ACTION_REGISTRY.resolve(executable.name)).toBe(executable); + if (executable.kind === 'raw') { + expect(executable.name).toBe(HANDLE_QUICK_OPERATION_ACTION); + expect(docs.has(executable.canonical)).toBe(false); + continue; + } + + const doc = docs.get(executable.canonical); + expect(doc, executable.name).toBeDefined(); + expect(executable.action.doc).toEqual(doc); + expect(executable.action.kind).toBe(doc!.stream === true ? 'stream' : 'normal'); + expect([doc!.name, ...doc!.aliases]).toContain(executable.name); + } + }); + + it('registers the exact compiled executable-name/kind projection at runtime', () => { + const registered: Array<[string, 'normal' | 'stream']> = []; + const fakeHandler = { + registerAction: (name: string) => { registered.push([name, 'normal']); }, + registerStreamAction: (name: string) => { registered.push([name, 'stream']); }, + } as unknown as ApiHandler; + + ACTION_REGISTRY.register(fakeHandler, {} as ApiActionContext); + + expect(registered).toEqual( + ACTION_REGISTRY.executableNames + .filter((entry) => entry.kind !== 'raw') + .map((entry) => [entry.name, entry.kind]), + ); + }); +}); + +describe('ApiHandler constructor-time registry transaction', () => { + const handler = async () => okResponse(); + + function testRegistry(...specs: RegisteredActionSpec[]) { + return compileActionRegistry(groups(...specs), RAW_ACTION_RESERVATIONS); + } + + function withRegistration( + base: RegisteredActionSpec, + register: RegisteredActionSpec['register'], + ): RegisteredActionSpec { + return { kind: base.kind, names: base.names, describe: base.describe, register }; + } + + it('binds only names declared by the injected complete registry, then seals', async () => { + const api = new ApiHandler( + {} as ApiActionContext, + undefined, + testRegistry(normal('__registry_normal__')), + ); + expect((await api.handle('__registry_normal__', {})).status).toBe('ok'); + expect(api.isStreamAction('__registry_normal__')).toBe(false); + expect(() => api.registerAction('__rogue__', handler)).toThrow(/Action registry is sealed/); + expect((await api.handle('__rogue__', {})).retcode).toBe(1404); + }); + + it('keeps stream classification bound to the sealed compiled claim', () => { + const api = new ApiHandler( + {} as ApiActionContext, + undefined, + testRegistry(stream('__registry_stream__')), + ); + expect(() => api.registerAction('__registry_stream__', handler)).toThrow( + /Action registry is sealed/, + ); + expect(api.isStreamAction('__registry_stream__')).toBe(true); + }); + + it('rejects a spec that registers an undeclared executable name', () => { + const base = normal('declared'); + const malicious = withRegistration(base, (api) => api.registerAction('rogue', handler)); + expect(() => new ApiHandler( + {} as ApiActionContext, + undefined, + testRegistry(malicious), + )).toThrow(/not declared.*canonical "rogue".*name "rogue".*kind normal/); + }); + + it('rejects a spec whose registration kind disagrees with its compiled claim', () => { + const base = normal('declared'); + const malicious = withRegistration(base, (api) => api.registerStreamAction('declared', handler)); + expect(() => new ApiHandler( + {} as ApiActionContext, + undefined, + testRegistry(malicious), + )).toThrow(/kind mismatch.*canonical "declared".*registry kind normal, registration kind stream/); + }); + + it('rejects duplicate constructor-time handler binding', () => { + const base = normal('declared'); + const malicious = withRegistration(base, (api) => { + api.registerAction('declared', handler); + api.registerAction('declared', handler); + }); + expect(() => new ApiHandler( + {} as ApiActionContext, + undefined, + testRegistry(malicious), + )).toThrow(/canonical "declared".*kind normal.*conflicts with.*canonical "declared".*kind normal/); + }); + + it('rejects a compiled claim that did not bind a handler', () => { + const base = normal('declared'); + const malicious = withRegistration(base, () => {}); + expect(() => new ApiHandler( + {} as ApiActionContext, + undefined, + testRegistry(malicious), + )).toThrow(/claim has no handler.*canonical "declared".*name "declared".*kind normal/); + }); + + it('requires the raw quick-operation reservation in an injected registry', () => { + const incomplete = compileActionRegistry(groups(normal('declared'))); + expect(() => new ApiHandler( + {} as ApiActionContext, + undefined, + incomplete, + )).toThrow(/not declared.*handle_quick_operation.*kind raw/); + }); +}); diff --git a/packages/onebot/tests/api-handler-logging.test.ts b/packages/onebot/tests/api-handler-logging.test.ts index 5aef018f..03909e70 100644 --- a/packages/onebot/tests/api-handler-logging.test.ts +++ b/packages/onebot/tests/api-handler-logging.test.ts @@ -5,13 +5,12 @@ // from blowing the line width. import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { ApiHandler } from '../src/api-handler'; import { OidbError } from '@snowluma/protocol/oidb-service'; import { subscribeLogs, type LogEntry } from '@snowluma/common/logger'; import { summarizeParams } from '@snowluma/common/log-summary'; +import { createCompiledTestHandler, testAction } from './helpers/compiled-action-handler'; -// Minimal context — we never reach the real action handlers; we -// register our own via registerAction. +// Minimal context — isolated test ActionSpecs never call these dependencies. function emptyContext(): any { return { bridge: {}, @@ -79,8 +78,9 @@ describe('summarizeParams', () => { describe('ApiHandler dispatch logging', () => { it('emits a debug entry under [Bridge.Action] when an action is called', async () => { - const handler = new ApiHandler(emptyContext(), 12345); - handler.registerAction('echo', async () => ({ status: 'ok', retcode: 0, data: null })); + const handler = createCompiledTestHandler(emptyContext(), [ + testAction('echo', async () => ({ status: 'ok', retcode: 0, data: null })), + ], 12345); await handler.handle('echo', { group_id: 67890, message: [1, 2, 3] }); @@ -93,10 +93,9 @@ describe('ApiHandler dispatch logging', () => { }); it('emits a warn line with the error stack when the handler throws', async () => { - const handler = new ApiHandler(emptyContext(), 12345); - handler.registerAction('boom', async () => { - throw new Error('kapow'); - }); + const handler = createCompiledTestHandler(emptyContext(), [ + testAction('boom', async () => { throw new Error('kapow'); }), + ], 12345); const result = await handler.handle('boom', {}); expect(result.status).toBe('failed'); @@ -113,16 +112,18 @@ describe('ApiHandler dispatch logging', () => { // maps to ONE policy here — ACTION_FAILED (100) + the error message — // instead of each action hand-rolling its own inconsistent try/catch. it('maps any handler throw to ACTION_FAILED (100) with the error message', async () => { - const handler = new ApiHandler(emptyContext(), 12345); - handler.registerAction('kaboom', async () => { throw new Error('permission denied'); }); + const handler = createCompiledTestHandler(emptyContext(), [ + testAction('kaboom', async () => { throw new Error('permission denied'); }), + ], 12345); const result = await handler.handle('kaboom', {}); expect(result).toMatchObject({ status: 'failed', retcode: 100, wording: 'permission denied' }); }); it('surfaces the OidbError code + server message through error.message (no special-casing)', async () => { - const handler = new ApiHandler(emptyContext(), 12345); - handler.registerAction('oidb_boom', async () => { throw new OidbError(34, 'no permission', 0x11ec, 2); }); + const handler = createCompiledTestHandler(emptyContext(), [ + testAction('oidb_boom', async () => { throw new OidbError(34, 'no permission', 0x11ec, 2); }), + ], 12345); const result = await handler.handle('oidb_boom', {}); expect(result).toMatchObject({ status: 'failed', retcode: 100 }); @@ -131,15 +132,16 @@ describe('ApiHandler dispatch logging', () => { }); it('renders a non-Error throw via String()', async () => { - const handler = new ApiHandler(emptyContext(), 12345); - handler.registerAction('weird', async () => { throw 'just a string'; }); + const handler = createCompiledTestHandler(emptyContext(), [ + testAction('weird', async () => { throw 'just a string'; }), + ], 12345); const result = await handler.handle('weird', {}); expect(result).toMatchObject({ status: 'failed', retcode: 100, wording: 'just a string' }); }); it('logs unknown actions at debug level', async () => { - const handler = new ApiHandler(emptyContext(), 99); + const handler = createCompiledTestHandler(emptyContext(), [], 99); await handler.handle('not_a_real_action', {}); const entry = captured.find((e) => e.scope === 'Bridge.Action' && e.message.includes('unknown action')); @@ -148,8 +150,9 @@ describe('ApiHandler dispatch logging', () => { }); it('falls back to the module-level logger (no uin slot) when uin is omitted', async () => { - const handler = new ApiHandler(emptyContext()); - handler.registerAction('ping', async () => ({ status: 'ok', retcode: 0, data: null })); + const handler = createCompiledTestHandler(emptyContext(), [ + testAction('ping', async () => ({ status: 'ok', retcode: 0, data: null })), + ]); await handler.handle('ping', {}); diff --git a/packages/onebot/tests/debug-seams.test.ts b/packages/onebot/tests/debug-seams.test.ts index 6102d230..9ac4f973 100644 --- a/packages/onebot/tests/debug-seams.test.ts +++ b/packages/onebot/tests/debug-seams.test.ts @@ -1,6 +1,7 @@ import { describe, it, expect, vi } from 'vitest'; import { OneBotNetworkManager } from '../src/network/network-manager'; -import { ApiHandler, type ApiActionContext } from '../src/api-handler'; +import type { ApiActionContext } from '../src/api-handler'; +import { createCompiledTestHandler, testAction } from './helpers/compiled-action-handler'; // ApiHandler's register* only define handlers (closures) at construction — they // don't touch ctx — so a throwing proxy is a safe minimal context. @@ -39,8 +40,9 @@ describe('OneBotNetworkManager.subscribeDebug', () => { describe('ApiHandler.setObserver', () => { it('fires after a successful action with {action, params, response, ms}', async () => { - const h = new ApiHandler(fakeCtx()); - h.registerAction('ping', async () => ({ status: 'ok', retcode: 0, data: 'pong' })); + const h = createCompiledTestHandler(fakeCtx(), [ + testAction('ping', async () => ({ status: 'ok', retcode: 0, data: 'pong' })), + ]); const recs: Array<{ action: string; response: { status: string } }> = []; h.setObserver((r) => recs.push(r as any)); const res = await h.handle('ping', { x: 1 }); @@ -51,8 +53,9 @@ describe('ApiHandler.setObserver', () => { }); it('fires on a thrown action with the failure response', async () => { - const h = new ApiHandler(fakeCtx()); - h.registerAction('boom', async () => { throw new Error('kaboom'); }); + const h = createCompiledTestHandler(fakeCtx(), [ + testAction('boom', async () => { throw new Error('kaboom'); }), + ]); const recs: any[] = []; h.setObserver((r) => recs.push(r)); await h.handle('boom', {}); @@ -61,8 +64,9 @@ describe('ApiHandler.setObserver', () => { }); it('unsubscribe stops observation', async () => { - const h = new ApiHandler(fakeCtx()); - h.registerAction('ping', async () => ({ status: 'ok', retcode: 0 })); + const h = createCompiledTestHandler(fakeCtx(), [ + testAction('ping', async () => ({ status: 'ok', retcode: 0 })), + ]); const cb = vi.fn(); const off = h.setObserver(cb); await h.handle('ping', {}); @@ -72,8 +76,9 @@ describe('ApiHandler.setObserver', () => { }); it('a throwing observer does not break handle', async () => { - const h = new ApiHandler(fakeCtx()); - h.registerAction('ping', async () => ({ status: 'ok', retcode: 0 })); + const h = createCompiledTestHandler(fakeCtx(), [ + testAction('ping', async () => ({ status: 'ok', retcode: 0 })), + ]); h.setObserver(() => { throw new Error('observer boom'); }); await expect(h.handle('ping', {})).resolves.toMatchObject({ status: 'ok' }); }); diff --git a/packages/onebot/tests/helpers/compiled-action-handler.ts b/packages/onebot/tests/helpers/compiled-action-handler.ts new file mode 100644 index 00000000..352df836 --- /dev/null +++ b/packages/onebot/tests/helpers/compiled-action-handler.ts @@ -0,0 +1,33 @@ +import { defineAction, type RegisteredActionSpec } from '../../src/action-kit'; +import { ApiHandler, type ApiActionContext } from '../../src/api-handler'; +import { compileActionRegistry, RAW_ACTION_RESERVATIONS } from '../../src/actions'; +import type { ApiResponse, JsonObject } from '../../src/types'; + +type TestActionRun = ( + params: JsonObject, + context: ApiActionContext, +) => Promise | ApiResponse; + +/** A test-only normal ActionSpec that still travels through the complete + * compiled-registry constructor path. */ +export function testAction(name: string, run: TestActionRun): RegisteredActionSpec { + return defineAction({ + name, + params: {}, + run: (_params, context, raw) => run(raw, context), + }); +} + +/** Construct an ApiHandler from an isolated but complete namespace. The raw + * quick-operation reservation is mandatory, matching the production shape. */ +export function createCompiledTestHandler( + context: ApiActionContext, + specs: readonly RegisteredActionSpec[] = [], + uin?: number, +): ApiHandler { + const registry = compileActionRegistry( + [{ category: 'test', actions: specs }], + RAW_ACTION_RESERVATIONS, + ); + return new ApiHandler(context, uin, registry); +} diff --git a/packages/onebot/tests/streaming.test.ts b/packages/onebot/tests/streaming.test.ts index 7865000f..11d141a4 100644 --- a/packages/onebot/tests/streaming.test.ts +++ b/packages/onebot/tests/streaming.test.ts @@ -4,30 +4,30 @@ // `stream:'stream-action'`), normal actions stay single-frame, and failures // terminate with an error frame. Wire format mirrors NapCat's Stream API. import { describe, it, expect } from 'vitest'; -import { ApiHandler, type ApiActionContext } from '../src/api-handler'; -import { defineAction, defineStreamAction, f } from '../src/action-kit'; +import type { ApiHandler, ApiActionContext } from '../src/api-handler'; +import { defineAction, defineStreamAction, f, type RegisteredActionSpec } from '../src/action-kit'; import { okResponse, failedResponse } from '../src/types'; import { wrapStreamFrame, wrapStreamTerminal, STREAM_MARK } from '../src/streaming'; +import { createCompiledTestHandler } from './helpers/compiled-action-handler'; -function newHandler(): ApiHandler { - // The real register* run lazily (handlers capture ctx, never call it at - // registration), so an empty ctx is enough to exercise the dispatch seam. - return new ApiHandler({} as ApiActionContext); +function newHandler(...specs: RegisteredActionSpec[]): ApiHandler { + // ActionSpecs bind during the constructor but call ctx only when dispatched. + return createCompiledTestHandler({} as ApiActionContext, specs); } const parse = (frames: string[]) => frames.map((f) => JSON.parse(f) as Record); describe('Stream API plumbing', () => { it('streams N intermediate frames + a terminal frame, all echo-tagged', async () => { - const h = newHandler(); - defineStreamAction({ + const action = defineStreamAction({ name: 'demo_stream', params: { n: f.uint() }, run: async (p, _ctx, _raw, sink) => { for (let i = 0; i < p.n; i++) await sink.send({ type: 'stream', index: i }); return okResponse({ type: 'response', total: p.n }); }, - }).register(h, {} as ApiActionContext); + }); + const h = newHandler(action); const frames: string[] = []; await h.processStreamRequest( @@ -43,17 +43,17 @@ describe('Stream API plumbing', () => { }); it('marks the action as a stream action; normal actions are not', () => { - const h = newHandler(); - defineStreamAction({ name: 'demo_stream', params: {}, run: () => okResponse({ type: 'response' }) }).register(h, {} as ApiActionContext); - defineAction({ name: 'demo_normal', params: {}, run: () => okResponse({ ok: true }) }).register(h, {} as ApiActionContext); + const streamAction = defineStreamAction({ name: 'demo_stream', params: {}, run: () => okResponse({ type: 'response' }) }); + const normalAction = defineAction({ name: 'demo_normal', params: {}, run: () => okResponse({ ok: true }) }); + const h = newHandler(streamAction, normalAction); expect(h.isStreamAction('demo_stream')).toBe(true); expect(h.isStreamAction('demo_normal')).toBe(false); expect(h.isStreamAction('nope')).toBe(false); }); it('a normal action through processStreamRequest emits exactly one un-marked frame', async () => { - const h = newHandler(); - defineAction({ name: 'demo_normal', params: {}, run: () => okResponse({ ok: true }) }).register(h, {} as ApiActionContext); + const action = defineAction({ name: 'demo_normal', params: {}, run: () => okResponse({ ok: true }) }); + const h = newHandler(action); const frames: string[] = []; await h.processStreamRequest(JSON.stringify({ action: 'demo_normal', params: {}, echo: 'e2' }), (j) => frames.push(j)); @@ -65,12 +65,12 @@ describe('Stream API plumbing', () => { }); it('a throwing stream action terminates with a single error frame', async () => { - const h = newHandler(); - defineStreamAction({ + const action = defineStreamAction({ name: 'demo_boom', params: {}, run: async () => { throw new Error('boom'); }, - }).register(h, {} as ApiActionContext); + }); + const h = newHandler(action); const frames: string[] = []; await h.processStreamRequest(JSON.stringify({ action: 'demo_boom', params: {}, echo: 'e3' }), (j) => frames.push(j)); @@ -82,15 +82,15 @@ describe('Stream API plumbing', () => { }); it('emits already-sent frames before the terminal error when a stream throws mid-way', async () => { - const h = newHandler(); - defineStreamAction({ + const action = defineStreamAction({ name: 'demo_partial', params: {}, run: async (_p, _ctx, _raw, sink) => { await sink.send({ type: 'stream', index: 0 }); throw new Error('mid'); }, - }).register(h, {} as ApiActionContext); + }); + const h = newHandler(action); const frames: string[] = []; await h.processStreamRequest(JSON.stringify({ action: 'demo_partial', params: {} }), (j) => frames.push(j)); @@ -102,8 +102,8 @@ describe('Stream API plumbing', () => { }); it('stream param validation fails terminate with an error frame', async () => { - const h = newHandler(); - defineStreamAction({ name: 'demo_needs', params: { n: f.uint() }, run: () => okResponse({ type: 'response' }) }).register(h, {} as ApiActionContext); + const action = defineStreamAction({ name: 'demo_needs', params: { n: f.uint() }, run: () => okResponse({ type: 'response' }) }); + const h = newHandler(action); const frames: string[] = []; await h.processStreamRequest(JSON.stringify({ action: 'demo_needs', params: {} }), (j) => frames.push(j)); @@ -112,16 +112,16 @@ describe('Stream API plumbing', () => { }); it('aborts a stream when isAlive turns false (client disconnect)', async () => { - const h = newHandler(); let sent = 0; - defineStreamAction({ + const action = defineStreamAction({ name: 'demo_abort', params: {}, run: async (_p, _ctx, _raw, sink) => { for (let i = 0; i < 5; i++) { await sink.send({ type: 'stream', index: i }); sent++; } return okResponse({ type: 'response' }); }, - }).register(h, {} as ApiActionContext); + }); + const h = newHandler(action); const frames: string[] = []; let alive = true;