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

View file

@ -3,6 +3,8 @@ import Device from "./device/Device.js";
import type { EndpointDefinition } from "./device/Device.js";
import { EventEmitter } from "events";
import { DisplayCategory } from "./compat/enums.js";
import type { Timers } from "./dispatcher.js";
import type { Publisher } from "./transport.js";
/** Optional settings for the bridge (1.5.1). Everything has the 1.4.0 behaviour as its default. */
export interface Alex2MQTTOptions {
/** The broker URL. Default: the public Alex2MQTT broker, mqtt://Alex2MQTT.stormysdream.club:1883. */
@ -16,6 +18,20 @@ export interface Alex2MQTTOptions {
* { type: "AlexaInterface", interface: "Alexa", version: "3" }, which Amazon requires and 1.x left out.
*/
alexaInterface?: boolean;
/**
* How long a directive may wait for its answer, in milliseconds. After that the bridge answers INTERNAL_ERROR and
* emits "unanswered". Default: 6500, before Alex2MQTT gives up at 7000. 0: the bridge never answers for a handler.
*/
answerWithinMs?: number;
/**
* true: a directive for an endpoint the bridge does not have is answered with NO_SUCH_ENDPOINT. Default: it is
* left alone, because the endpoint may belong to another bridge on the same root topic.
*/
answerUnknownEndpoints?: boolean;
/** Publish here and not to the broker: a MemoryPublisher and receive() run a bridge that never connects. */
publisher?: Publisher;
/** The timer of answerWithinMs, for a test that does not wait. Default: setTimeout, unref'd. */
timers?: Timers;
}
export declare const DEFAULT_HOST = "mqtt://Alex2MQTT.stormysdream.club:1883";
/**
@ -31,6 +47,9 @@ export declare const DEFAULT_HOST = "mqtt://Alex2MQTT.stormysdream.club:1883";
* unconditionally, and Node kills a process that has an unhandled "error" event)
* "discover" (n) a discovery request was answered with n devices
* "directive" (info) a directive was dispatched to a device: { endpointId, namespace, name }
* "unknownEndpoint" (info) a directive came for an endpoint that is not registered: { endpointId, namespace, name }
* "unanswered" (info) nothing answered a directive in time and the bridge answered INTERNAL_ERROR:
* { endpointId, namespace, name, correlationToken }
*/
declare class Alex2MQTT extends EventEmitter {
private username;
@ -39,6 +58,7 @@ declare class Alex2MQTT extends EventEmitter {
private debugLogging;
private client;
private readonly publisher;
private readonly dispatcher;
private devices;
private MqttHost;
private options;
@ -52,6 +72,15 @@ declare class Alex2MQTT extends EventEmitter {
/** Emit "error" only when somebody listens: an unhandled "error" event would crash the host process. */
private fail;
connect(): void;
/**
* What the bridge does with a message of the broker: it answers a discovery request, and it hands a directive to
* the handlers of its device. Resolves when they are done and never rejects. With the publisher option a test
* calls it in place of the broker:
*
* await bridge.receive("root/lamp-1/alexaDirective", JSON.stringify(directive));
*/
receive(topic: string, payload: Buffer | string): Promise<void>;
private answerDiscovery;
private describeDevices;
/** Close the broker connection (resolves once closed). The devices stay registered; connect() again reuses them. */
disconnect(): Promise<void>;

View file

@ -1,3 +1,5 @@
import type { DirectiveHandler } from "../dispatcher.js";
import type { Infer } from "../registry/schema.js";
import type { Declared, Directives, InterfaceDescriptor, Label, Properties, Semantics } from "../registry/types.js";
/** What a declaration can set for any interface. */
export interface CommonOptions {
@ -66,10 +68,24 @@ export declare class Capability<P extends Properties = Properties, D extends Dir
options: O;
/** What the bridge logs about the declaration, once, when it answers a discovery. */
readonly notes: string[];
private readonly handlers;
constructor(descriptor: InterfaceDescriptor<P, D, O, boolean>, declared: CommonOptions & {
options: O;
});
get namespace(): string;
/**
* What the device does on a directive of the interface:
*
* lift.on("SetRangeValue", async (ctx) => { await motor.moveTo(ctx.payload.rangeValue); return ctx.respond(); });
*
* "*" is the handler of every directive that has none of its own. A handler that throws answers the directive
* with an ErrorResponse: the AlexaError it threw, INTERNAL_ERROR for anything else. Throws a DeclarationError
* for a name that is not a directive of the interface.
*/
on<K extends keyof D & string>(name: K, handler: DirectiveHandler<Infer<D[K]["payload"]>>): this;
on(name: "*", handler: DirectiveHandler): this;
/** The handler on(name) registered, or the one of "*". */
handlerFor(name: string): DirectiveHandler<any> | undefined;
/** Mappings of "open", "close", "raise", "lower" and of states, when the declaration has any. */
get semantics(): Semantics | undefined;
/** The capability object for discovery, its fields in the order of the example on alexa-discovery-objects.html. */

View file

@ -5,6 +5,7 @@ import { AlexaStatusMessage } from "../compat/AlexaStatusMessage.js";
import { DisplayCategory } from "../compat/enums.js";
import type { AlexaInterfaceType } from "../compat/enums.js";
import type { ChangeCause } from "../messages/types.js";
import type { DirectiveHandler, Fill } from "../dispatcher.js";
import type { DisplayCategoryName } from "../registry/catalog.js";
import type { Directives, InterfaceDescriptor, Properties } from "../registry/types.js";
import type { Publisher } from "../transport.js";
@ -72,6 +73,12 @@ declare class Device extends EventEmitter {
* is null every send() resolves "" and reports why.
*/
publisher: Publisher | null;
/** Set by state(). */
stateProvider?: Fill;
/** Set by onReportState(). */
reportStateHandler?: DirectiveHandler<Record<string, never>>;
/** Set by onDirective(). */
directiveHandler?: DirectiveHandler;
/** client is ignored: in 1.x it was the broker client, and a device could only be built after connect(). */
constructor(client: unknown, rootTopic: string, name: string, endpointId: string, displayCategory: Array<DisplayCategory> | null, description?: string, manufacturerName?: string, manufacturer?: string, model?: string);
getName(): string;
@ -95,6 +102,21 @@ declare class Device extends EventEmitter {
* (1.5.1). Resolves with the topic published to, or "" when the publish failed (never rejects, 1.5.2).
*/
sendSceneResponse(correlationToken: string, activated: boolean, cause?: ChangeCause, sendAsync?: boolean): Promise<string>;
/**
* How the device reports its state, every retrievable property of it:
*
* blinds.state((s) => s.set(lift, "rangeValue", motor.position).health("OK"));
*
* ReportState is answered with it, and it is the context of every ctx.respond(), where the handler sets only what
* the directive changed. Alexa wants the whole state in both (alexa-response.html, "Synchronous response").
*/
state(fill: Fill): this;
/** Answer ReportState in a handler of its own, for a state that has to be read from the device first. */
onReportState(handler: DirectiveHandler<Record<string, never>>): this;
/** The handler for the directives of declared capabilities that have no handler of their own. */
onDirective(handler: DirectiveHandler): this;
/** The capability declared for the interface, under the instance for a generic controller. */
capability(namespace: string, instance?: string): AnyCapability | undefined;
/** The capabilities the device declared, in the order it declared them. */
getCapabilities(): AnyCapability[];
setManufacturerName(name: string): void;

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;
}

View file

@ -16,6 +16,7 @@ export type { ChangeCause, ChangeReportMessage, DeferredResponseMessage, ErrorRe
export * as topics from "./topics.js";
export { MemoryPublisher } from "./transport.js";
export type { Publisher, PublishResult } from "./transport.js";
export type { DirectiveContext, DirectiveHandler, Fill, RawDirective, Timers } from "./dispatcher.js";
export { AlexaInterface } from "./compat/AlexaInterface.js";
export type { SupportedMode } from "./compat/AlexaInterface.js";
export { ActionMapping } from "./compat/ActionMapping.js";

View file

@ -60,6 +60,8 @@ export interface ChangeReportFields extends Envelope {
/** The other properties of the endpoint, as they are now. */
context?: readonly Property[];
}
/** The same property of the same instance, whatever its value. */
export declare const sameProperty: (a: Property, b: Property) => boolean;
/**
* A change of state nobody asked for. The header has no correlationToken (message-guide.html, "Header object").
* A property that changed is left out of the context: it is reported in one of the two (same page, "Context

View file

@ -15,5 +15,7 @@ export declare function directiveEndpoint(root: string, topic: string): string |
export declare const response: (root: string, endpointId: string) => string;
/** Where the answer goes once a DeferredResponse was sent for the directive. */
export declare const deferred: (root: string, endpointId: string) => string;
/** How long Alex2MQTT waits for the answer to a directive before it tells Alexa that the endpoint did not answer. */
export declare const DIRECTIVE_BUDGET_MS = 7000;
/** Where every ChangeReport of the root goes: the backend adds the user's token and posts it to Alexa. */
export declare const changeReport: (root: string) => string;

View file

@ -12,6 +12,8 @@ export type PublishResult = {
export interface Publisher {
publish(topic: string, message: object): Promise<PublishResult>;
}
/** What was thrown, as an Error. */
export declare const asError: (err: unknown) => Error;
/**
* Publishes to the broker through the client the bridge has at the time: a new one after disconnect() and connect(),
* none before connect() and after disconnect(). Without a client the publish is refused. With a client that lost
@ -26,7 +28,7 @@ export declare class MqttPublisher implements Publisher {
* Keeps what it is asked to publish, for tests and dry runs without a broker:
*
* const sent = new MemoryPublisher();
* device.publisher = sent;
* device.publisher = sent; // or new Alex2MQTT(..., { publisher: sent }) and bridge.receive()
* await device.getStatusMessage(token, true).addPowerControllerProp(PowerController.ON).send();
* sent.published[0] // { topic: "<root>/<endpointId>/alexaResponce", message: { event, context } }
*/