dispatch: typed handlers, respond/defer/error, automatic ErrorResponse, watchdog

src/dispatcher.ts routes a directive to capability.on(name | "*"), device.onDirective() or
device.onReportState(), with the payload checked by the descriptor of the interface. The
DirectiveContext answers with respond/report/defer/error; respond() and report() start from
device.state(). A handler or 1.x listener that throws or rejects is answered with INTERNAL_ERROR
(an AlexaError with itself) and reported through "error", never as an unhandled rejection.
Undeclared interface, unknown directive, AdjustMode on an unordered mode and a missing handler
get INVALID_DIRECTIVE, a bad payload INVALID_VALUE; a device with an "Event" or "ReportState"
listener keeps the answer to itself. Every answer passes the dispatcher: the first one per
correlationToken is published, a second is refused. No answer within answerWithinMs (6500,
0 = off, unref'd timer) sends INTERNAL_ERROR and emits "unanswered". A messageId that arrived
in the last 60 s is dropped. New: "unknownEndpoint", options answerUnknownEndpoints, publisher,
timers, and bridge.receive() to run a bridge without a broker. 168 tests pass (18 new).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
David 2026-09-28 19:49:41 +00:00
parent e0fe9d2812
commit feff828ec1
40 changed files with 2149 additions and 136 deletions

103
dist/types/dispatcher.d.ts vendored Normal file
View file

@ -0,0 +1,103 @@
import type Device from "./device/Device.js";
import { StateBuilder } from "./messages/StateBuilder.js";
import type { Publisher, PublishResult } from "./transport.js";
/** A directive as Alex2MQTT publishes it: the directive of Alexa without endpoint.scope, the token of the user. */
export interface RawDirective {
header: {
namespace: string;
name: string;
instance?: string;
messageId?: string;
correlationToken?: string;
payloadVersion?: string;
};
endpoint?: {
endpointId?: string;
cookie?: Record<string, string>;
};
payload?: unknown;
}
/** Sets the properties of a message. */
export type Fill = (state: StateBuilder) => void;
/** One directive, and the ways to answer it. Each method resolves with what became of the publish, none rejects. */
export interface DirectiveContext<T = unknown> {
readonly endpointId: string;
readonly namespace: string;
readonly name: string;
/** The instance of a generic controller, "" without one. */
readonly instance: string;
/** "" when the directive came without one; it can then not be answered. */
readonly correlationToken: string;
/** The payload, checked by the descriptor of the interface. As it arrived for an interface the library only names. */
readonly payload: T;
readonly raw: RawDirective;
/** Date.now() when the directive arrived. */
readonly receivedAt: number;
/** A Response, a StateReport or an ErrorResponse was sent. */
readonly answered: boolean;
/** A DeferredResponse was sent: the answer goes to <root>/<endpointId>/deferredResponse. */
readonly deferred: boolean;
/**
* Answer with a Response, or with the response the interface has of its own. The context is the state of
* device.state(), and what fill sets replaces the same property of it.
*/
respond(fill?: Fill, options?: {
payload?: Record<string, unknown>;
}): Promise<PublishResult>;
/** Answer ReportState with a StateReport, its properties as for respond(). */
report(fill?: Fill): Promise<PublishResult>;
/** Send a DeferredResponse now, when the answer takes longer than the 7 s Alex2MQTT waits for it. */
defer(estimatedDeferralInSeconds?: number): Promise<PublishResult>;
/** Answer with an ErrorResponse. An error that is not an AlexaError is sent as INTERNAL_ERROR. */
error(type: string, message: string, extra?: Record<string, unknown>): Promise<PublishResult>;
error(err: Error): Promise<PublishResult>;
}
/** What a handler returns is awaited and otherwise ignored; what it throws answers the directive. */
export type DirectiveHandler<T = unknown> = (ctx: DirectiveContext<T>) => unknown;
/** The clock of the watchdog, replaced in tests. */
export interface Timers {
setTimeout(run: () => void, ms: number): unknown;
clearTimeout(timer: unknown): void;
}
/** What the dispatcher needs of its bridge. */
export interface DispatcherOptions {
rootTopic: string;
/** Where the answers go. */
publisher: Publisher;
getDevice(endpointId: string): Device | undefined;
log(message: string, detail?: unknown): void;
/** Reports an error: the "error" event of the bridge. */
fail(err: Error): void;
emit(event: string, ...args: unknown[]): void;
answerWithinMs?: number;
answerUnknownEndpoints?: boolean;
timers?: Timers;
}
/** Alex2MQTT gives up on a directive after DIRECTIVE_BUDGET_MS: the answer of the watchdog has to be there before. */
export declare const ANSWER_WITHIN_MS: number;
export declare class Dispatcher {
private readonly options;
readonly rootTopic: string;
/**
* What the devices of the bridge publish through. An answer to a directive that waits is let through once, and a
* DeferredResponse once before it; everything else passes.
*/
readonly publisher: Publisher;
private readonly answerWithinMs;
private readonly timers;
private readonly exchanges;
private readonly arrived;
private readonly deferralNoted;
constructor(options: DispatcherOptions);
/** Publish an answer; one that is not published is reported to the bridge. */
send(topic: string, message: object): Promise<PublishResult>;
/** defer() for an interface Amazon documents no DeferredResponse for: said once, the DeferredResponse is sent. */
noteDeferral(namespace: string): void;
/** The text of a message on the directive topic of endpointId. Resolves when the handlers are done. */
dispatch(endpointId: string, text: string): Promise<void>;
private route;
private isolated;
private watch;
private publish;
private forget;
}