messages: pure builders for every event the bridge sends
src/messages builds Response, StateReport, DeferredResponse, ErrorResponse, ChangeReport and the scene, doorbell and simple events from plain values; messageId and times are parameters, so a test compares whole objects. StateBuilder collects properties checked by the descriptors, AlexaError and AlexaErrors carry the payload fields of an error type. AlexaStatusMessage and AlexaErrorResponse move to src/compat and are written on the builders. On the wire, against 1.5.2: a DeferredResponse has no context key, a ChangeReport has no correlationToken, the namespace of an ErrorResponse follows its type, and a ChangeReport without a changed property is not published: send() resolves "" and the bridge reports an error that names the endpoint. 143 tests pass (108 before). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
parent
2558e21787
commit
46fa06728c
68 changed files with 3410 additions and 1208 deletions
165
test/messages/build.test.js
Normal file
165
test/messages/build.test.js
Normal file
|
|
@ -0,0 +1,165 @@
|
|||
"use strict";
|
||||
// The builders of src/messages/build.ts. Given a messageId and the times, a builder returns the same object every
|
||||
// time, so each test compares the whole message.
|
||||
const { test } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const { messages, MessageError } = require("alex2node");
|
||||
const { UUID_V4 } = require("../helpers/harness.js");
|
||||
|
||||
const AT = "2026-09-28T10:00:00.000Z";
|
||||
const messageId = "0c2bd0a4-6c1c-4b7a-9d3e-5f0a3a1b2c3d";
|
||||
const powerState = messages.property("Alexa.PowerController", "powerState", "ON", { timeOfSample: AT });
|
||||
const brightness = messages.property("Alexa.BrightnessController", "brightness", 40, { timeOfSample: AT, uncertaintyInMilliseconds: 500 });
|
||||
|
||||
test("response: the event and the state of the endpoint as its context", () => {
|
||||
assert.deepEqual(messages.response({ endpointId: "lamp-1", correlationToken: "ct", messageId, context: [powerState, brightness] }), {
|
||||
event: {
|
||||
header: { namespace: "Alexa", name: "Response", messageId, correlationToken: "ct", payloadVersion: "3" },
|
||||
endpoint: { endpointId: "lamp-1" },
|
||||
payload: {},
|
||||
},
|
||||
context: {
|
||||
properties: [
|
||||
{ namespace: "Alexa.PowerController", name: "powerState", value: "ON", timeOfSample: AT, uncertaintyInMilliseconds: 0 },
|
||||
{ namespace: "Alexa.BrightnessController", name: "brightness", value: 40, timeOfSample: AT, uncertaintyInMilliseconds: 500 },
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("response: nothing to report is an empty list of properties; an interface names its own response", () => {
|
||||
const armed = messages.response({
|
||||
namespace: "Alexa.SecurityPanelController", name: "Arm.Response", endpointId: "panel", correlationToken: "ct", messageId,
|
||||
payload: { exitDelayInSeconds: 30 },
|
||||
});
|
||||
assert.deepEqual(armed, {
|
||||
event: {
|
||||
header: { namespace: "Alexa.SecurityPanelController", name: "Arm.Response", messageId, correlationToken: "ct", payloadVersion: "3" },
|
||||
endpoint: { endpointId: "panel" },
|
||||
payload: { exitDelayInSeconds: 30 },
|
||||
},
|
||||
context: { properties: [] },
|
||||
});
|
||||
});
|
||||
|
||||
test("stateReport: a Response by the name of StateReport", () => {
|
||||
assert.deepEqual(messages.stateReport({ endpointId: "lamp-1", correlationToken: "ct", messageId, context: [powerState] }), {
|
||||
event: {
|
||||
header: { namespace: "Alexa", name: "StateReport", messageId, correlationToken: "ct", payloadVersion: "3" },
|
||||
endpoint: { endpointId: "lamp-1" },
|
||||
payload: {},
|
||||
},
|
||||
context: { properties: [powerState] },
|
||||
});
|
||||
});
|
||||
|
||||
test("deferredResponse: no context key, the estimate only when given", () => {
|
||||
const event = {
|
||||
header: { namespace: "Alexa", name: "DeferredResponse", messageId, correlationToken: "ct", payloadVersion: "3" },
|
||||
endpoint: { endpointId: "lamp-1" },
|
||||
};
|
||||
assert.deepEqual(messages.deferredResponse({ endpointId: "lamp-1", correlationToken: "ct", messageId }), {
|
||||
event: { ...event, payload: {} },
|
||||
});
|
||||
assert.deepEqual(
|
||||
messages.deferredResponse({ endpointId: "lamp-1", correlationToken: "ct", messageId, estimatedDeferralInSeconds: 20 }),
|
||||
{ event: { ...event, payload: { estimatedDeferralInSeconds: 20 } } }
|
||||
);
|
||||
});
|
||||
|
||||
test("errorResponse: the event alone, the fields of the type next to type and message", () => {
|
||||
const answer = messages.errorResponse({
|
||||
endpointId: "lamp-1", correlationToken: "ct", messageId,
|
||||
type: "VALUE_OUT_OF_RANGE", message: "too high", extra: { validRange: { minimumValue: 1, maximumValue: 10 } },
|
||||
});
|
||||
assert.deepEqual(answer, {
|
||||
event: {
|
||||
header: { namespace: "Alexa", name: "ErrorResponse", messageId, correlationToken: "ct", payloadVersion: "3" },
|
||||
endpoint: { endpointId: "lamp-1" },
|
||||
payload: { type: "VALUE_OUT_OF_RANGE", message: "too high", validRange: { minimumValue: 1, maximumValue: 10 } },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("changeReport: what changed in payload.change, the rest in the context, no correlationToken", () => {
|
||||
const report = messages.changeReport({ endpointId: "lamp-1", messageId, cause: "APP_INTERACTION", changed: [powerState], context: [brightness] });
|
||||
assert.deepEqual(report, {
|
||||
event: {
|
||||
header: { namespace: "Alexa", name: "ChangeReport", messageId, payloadVersion: "3" },
|
||||
endpoint: { endpointId: "lamp-1" },
|
||||
payload: { change: { cause: { type: "APP_INTERACTION" }, properties: [powerState] } },
|
||||
},
|
||||
context: { properties: [brightness] },
|
||||
});
|
||||
});
|
||||
|
||||
test("changeReport: a property that changed is not repeated in the context; instances are told apart", () => {
|
||||
const lift = (instance, value) => messages.property("Alexa.RangeController", "rangeValue", value, { instance, timeOfSample: AT });
|
||||
const report = messages.changeReport({
|
||||
endpointId: "blind", messageId,
|
||||
changed: [lift("Blind.Lift", 40)],
|
||||
context: [lift("Blind.Lift", 30), lift("Blind.Tilt", 5)],
|
||||
});
|
||||
assert.equal(report.event.payload.change.cause.type, "PHYSICAL_INTERACTION");
|
||||
assert.deepEqual(report.context.properties, [lift("Blind.Tilt", 5)]);
|
||||
});
|
||||
|
||||
test("changeReport: without a changed property it is refused, the error names the endpoint and what to do", () => {
|
||||
assert.throws(
|
||||
() => messages.changeReport({ endpointId: "lamp-1", changed: [], context: [brightness] }),
|
||||
(err) => {
|
||||
assert.ok(err instanceof MessageError);
|
||||
assert.equal(err.endpointId, "lamp-1");
|
||||
assert.match(err.message, /^lamp-1: a ChangeReport needs at least one property that changed/);
|
||||
assert.match(err.message, /send no report when nothing changed/);
|
||||
return true;
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
test("sceneEvent: ActivationStarted and DeactivationStarted with the cause and the time", () => {
|
||||
const started = messages.sceneEvent({ endpointId: "scene-1", correlationToken: "ct", messageId, activated: true, timestamp: AT });
|
||||
assert.deepEqual(started, {
|
||||
event: {
|
||||
header: { namespace: "Alexa.SceneController", name: "ActivationStarted", messageId, correlationToken: "ct", payloadVersion: "3" },
|
||||
endpoint: { endpointId: "scene-1" },
|
||||
payload: { cause: { type: "VOICE_INTERACTION" }, timestamp: AT },
|
||||
},
|
||||
context: {},
|
||||
});
|
||||
const stopped = messages.sceneEvent({
|
||||
endpointId: "scene-1", correlationToken: "ct", messageId, activated: false, cause: "APP_INTERACTION", timestamp: new Date(AT),
|
||||
});
|
||||
assert.equal(stopped.event.header.name, "DeactivationStarted");
|
||||
assert.deepEqual(stopped.event.payload, { cause: { type: "APP_INTERACTION" }, timestamp: AT });
|
||||
});
|
||||
|
||||
test("doorbellPress: an event without a correlationToken and without a context", () => {
|
||||
assert.deepEqual(messages.doorbellPress({ endpointId: "door", messageId, timestamp: AT }), {
|
||||
event: {
|
||||
header: { namespace: "Alexa.DoorbellEventSource", name: "DoorbellPress", messageId, payloadVersion: "3" },
|
||||
endpoint: { endpointId: "door" },
|
||||
payload: { cause: { type: "PHYSICAL_INTERACTION" }, timestamp: AT },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("simpleEvent: the instance in the header, payloadVersion 1.0", () => {
|
||||
assert.deepEqual(messages.simpleEvent({ endpointId: "button", instance: "Button.Front", id: "Button.SinglePush.1", messageId, timestamp: AT }), {
|
||||
event: {
|
||||
header: { namespace: "Alexa.SimpleEventSource", name: "Event", instance: "Button.Front", messageId, payloadVersion: "1.0" },
|
||||
endpoint: { endpointId: "button" },
|
||||
payload: { id: "Button.SinglePush.1", timestamp: AT },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("left out, the messageId is a new version 4 UUID and the time is now", () => {
|
||||
const before = Date.now();
|
||||
const first = messages.doorbellPress({ endpointId: "door" });
|
||||
const second = messages.doorbellPress({ endpointId: "door" });
|
||||
assert.match(first.event.header.messageId, UUID_V4);
|
||||
assert.notEqual(first.event.header.messageId, second.event.header.messageId);
|
||||
const at = Date.parse(first.event.payload.timestamp);
|
||||
assert.ok(at >= before && at <= Date.now(), first.event.payload.timestamp);
|
||||
});
|
||||
79
test/messages/errors.test.js
Normal file
79
test/messages/errors.test.js
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
"use strict";
|
||||
// AlexaError, the helpers of AlexaErrors and the namespace an ErrorResponse goes under.
|
||||
const { test } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const { AlexaError, AlexaErrors, AlexaErrorType, messages } = require("alex2node");
|
||||
|
||||
test("the namespace follows the type: the interface that documents it, Alexa for the rest", () => {
|
||||
const namespaces = Object.fromEntries(
|
||||
["ENDPOINT_UNREACHABLE", "THERMOSTAT_IS_OFF", "UNAUTHORIZED", "OBSTACLE_DETECTED", "SAFETY_BEAM_BREACHED", "NOT_A_TYPE", "constructor"]
|
||||
.map((type) => [type, messages.errorNamespace(type)])
|
||||
);
|
||||
assert.deepEqual(namespaces, {
|
||||
ENDPOINT_UNREACHABLE: "Alexa",
|
||||
THERMOSTAT_IS_OFF: "Alexa.ThermostatController",
|
||||
UNAUTHORIZED: "Alexa.SecurityPanelController",
|
||||
OBSTACLE_DETECTED: "Alexa.Safety",
|
||||
SAFETY_BEAM_BREACHED: "Alexa.Safety",
|
||||
NOT_A_TYPE: "Alexa",
|
||||
constructor: "Alexa",
|
||||
});
|
||||
});
|
||||
|
||||
test("every type of the 1.x enum has a namespace that starts with Alexa", () => {
|
||||
for (const type of Object.values(AlexaErrorType)) assert.match(messages.errorNamespace(type), /^Alexa(\.[A-Za-z]+)*$/, type);
|
||||
});
|
||||
|
||||
test("AlexaError: an Error with the type, the message for Alexa, the fields of the payload and the namespace", () => {
|
||||
const error = AlexaErrors.of("THERMOSTAT_IS_OFF", "the thermostat is off");
|
||||
assert.ok(error instanceof AlexaError && error instanceof Error);
|
||||
assert.equal(error.name, "AlexaError");
|
||||
assert.equal(error.message, "THERMOSTAT_IS_OFF: the thermostat is off");
|
||||
assert.deepEqual(
|
||||
{ type: error.type, alexaMessage: error.alexaMessage, extra: error.extra, namespace: error.namespace },
|
||||
{ type: "THERMOSTAT_IS_OFF", alexaMessage: "the thermostat is off", extra: {}, namespace: "Alexa.ThermostatController" }
|
||||
);
|
||||
assert.equal(new AlexaError("THERMOSTAT_IS_OFF", "off", {}, "Alexa").namespace, "Alexa");
|
||||
});
|
||||
|
||||
test("the helpers: the type, the namespace and the payload fields as the pages spell them", () => {
|
||||
const celsius = (value) => ({ value, scale: "CELSIUS" });
|
||||
const cases = [
|
||||
[AlexaErrors.valueOutOfRange("m", { minimumValue: 1, maximumValue: 10 }),
|
||||
"Alexa", "VALUE_OUT_OF_RANGE", { validRange: { minimumValue: 1, maximumValue: 10 } }],
|
||||
[AlexaErrors.temperatureOutOfRange("m", { minimumValue: celsius(15), maximumValue: celsius(30) }),
|
||||
"Alexa", "TEMPERATURE_VALUE_OUT_OF_RANGE", { validRange: { minimumValue: celsius(15), maximumValue: celsius(30) } }],
|
||||
[AlexaErrors.notSupportedInCurrentMode("m", "COLOR"), "Alexa", "NOT_SUPPORTED_IN_CURRENT_MODE", { currentDeviceMode: "COLOR" }],
|
||||
[AlexaErrors.endpointLowPower("m", 5), "Alexa", "ENDPOINT_LOW_POWER", { percentageState: 5 }],
|
||||
[AlexaErrors.endpointLowPower("m"), "Alexa", "ENDPOINT_LOW_POWER", {}],
|
||||
[AlexaErrors.endpointControlUnavailable("m", "DEEP_SLEEP_MODE"), "Alexa", "ENDPOINT_CONTROL_UNAVAILABLE", { reason: "DEEP_SLEEP_MODE" }],
|
||||
[AlexaErrors.notSupportedWithCurrentBatteryChargeState("m", "NOT_CONNECTED_TO_POWER", 75),
|
||||
"Alexa", "NOT_SUPPORTED_WITH_CURRENT_BATTERY_CHARGE_STATE",
|
||||
{ currentChargeState: "NOT_CONNECTED_TO_POWER", currentChargeLevelInPercentage: 75 }],
|
||||
[AlexaErrors.notSupportedWithCurrentBatteryChargeState("m", "FULLY_CHARGED"),
|
||||
"Alexa", "NOT_SUPPORTED_WITH_CURRENT_BATTERY_CHARGE_STATE", { currentChargeState: "FULLY_CHARGED" }],
|
||||
[AlexaErrors.insufficientResource("m", "WATER"), "Alexa", "INSUFFICIENT_RESOURCE", { resourceType: "WATER" }],
|
||||
[AlexaErrors.maintenanceRequired("m", "EMPTY_BIN"), "Alexa", "MAINTENANCE_REQUIRED", { maintenanceAction: "EMPTY_BIN" }],
|
||||
[AlexaErrors.maintenanceRequired("m"), "Alexa", "MAINTENANCE_REQUIRED", {}],
|
||||
[AlexaErrors.setpointsTooClose("m", celsius(2)),
|
||||
"Alexa.ThermostatController", "REQUESTED_SETPOINTS_TOO_CLOSE", { minimumTemperatureDelta: celsius(2) }],
|
||||
[AlexaErrors.bypassNeeded("m", [{ friendlyName: "Front door" }]),
|
||||
"Alexa.SecurityPanelController", "BYPASS_NEEDED", { endpointsNeedingBypass: [{ friendlyName: "Front door" }] }],
|
||||
[AlexaErrors.of("OBSTACLE_DETECTED", "m"), "Alexa.Safety", "OBSTACLE_DETECTED", {}],
|
||||
];
|
||||
for (const [error, namespace, type, extra] of cases) {
|
||||
assert.deepEqual(
|
||||
{ namespace: error.namespace, type: error.type, alexaMessage: error.alexaMessage, extra: error.extra },
|
||||
{ namespace, type, alexaMessage: "m", extra },
|
||||
type
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("errorResponse: the namespace of the type, or the one the caller names", () => {
|
||||
const fields = { endpointId: "thermostat", correlationToken: "ct", messageId: "m", type: "THERMOSTAT_IS_OFF", message: "off" };
|
||||
assert.deepEqual(messages.errorResponse(fields).event.header, {
|
||||
namespace: "Alexa.ThermostatController", name: "ErrorResponse", messageId: "m", correlationToken: "ct", payloadVersion: "3",
|
||||
});
|
||||
assert.equal(messages.errorResponse({ ...fields, namespace: "Alexa" }).event.header.namespace, "Alexa");
|
||||
});
|
||||
91
test/messages/state.test.js
Normal file
91
test/messages/state.test.js
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
"use strict";
|
||||
// StateBuilder: the properties of one message, checked by the descriptors of the registry.
|
||||
const { test } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const {
|
||||
BrightnessController, Capability, EndpointHealth, PowerController, RangeController, SchemaError, StateBuilder,
|
||||
TemperatureSensor, messages,
|
||||
} = require("alex2node");
|
||||
|
||||
const AT = "2026-09-28T10:00:00.000Z";
|
||||
const now = () => new Date(AT);
|
||||
|
||||
test("set: the property of a described interface, its time from the clock of the builder", () => {
|
||||
const state = new StateBuilder({ now }).set(PowerController, "powerState", "ON").set(BrightnessController, "brightness", 40);
|
||||
assert.deepEqual(state.context, [
|
||||
{ namespace: "Alexa.PowerController", name: "powerState", value: "ON", timeOfSample: AT, uncertaintyInMilliseconds: 0 },
|
||||
{ namespace: "Alexa.BrightnessController", name: "brightness", value: 40, timeOfSample: AT, uncertaintyInMilliseconds: 0 },
|
||||
]);
|
||||
assert.deepEqual(state.change, []);
|
||||
});
|
||||
|
||||
test("set: a property has the time and the uncertainty it is given", () => {
|
||||
const changedAt = "2026-09-28T09:12:00.000Z";
|
||||
const [property] = new StateBuilder({ now })
|
||||
.set(PowerController, "powerState", "OFF", { timeOfSample: changedAt, uncertaintyInMilliseconds: 6000 }).context;
|
||||
assert.equal(property.timeOfSample, changedAt);
|
||||
assert.equal(property.uncertaintyInMilliseconds, 6000);
|
||||
});
|
||||
|
||||
test("set: a temperature is reported in the scale it is given in", () => {
|
||||
const [property] = new StateBuilder({ now }).set(TemperatureSensor, "temperature", { value: 70, scale: "FAHRENHEIT" }).context;
|
||||
assert.deepEqual(property.value, { value: 70, scale: "FAHRENHEIT" });
|
||||
});
|
||||
|
||||
test("set: a value Alexa would not take is refused, the error names the interface and the property", () => {
|
||||
const state = new StateBuilder({ now });
|
||||
assert.throws(() => state.set(PowerController, "powerState", "on"), (err) => {
|
||||
assert.ok(err instanceof SchemaError);
|
||||
assert.match(err.message, /^Alexa\.PowerController: powerState: expected .*ON.*got "on"$/);
|
||||
return true;
|
||||
});
|
||||
assert.throws(() => state.set(PowerController, "power", "ON"), /Alexa\.PowerController: power: not a property of the interface, which has powerState/);
|
||||
assert.deepEqual(state.context, []);
|
||||
});
|
||||
|
||||
test("set: a generic controller needs its instance, given with the property or by the capability", () => {
|
||||
const state = new StateBuilder({ now });
|
||||
assert.throws(() => state.set(RangeController, "rangeValue", 3), /Alexa\.RangeController: rangeValue: the interface has instances/);
|
||||
|
||||
const lift = new Capability(RangeController, { instance: "Blind.Lift", options: {} });
|
||||
state.set(RangeController, "rangeValue", 3, { instance: "Blind.Tilt" }).set(lift, "rangeValue", 40);
|
||||
assert.deepEqual(state.context, [
|
||||
{ namespace: "Alexa.RangeController", instance: "Blind.Tilt", name: "rangeValue", value: 3, timeOfSample: AT, uncertaintyInMilliseconds: 0 },
|
||||
{ namespace: "Alexa.RangeController", instance: "Blind.Lift", name: "rangeValue", value: 40, timeOfSample: AT, uncertaintyInMilliseconds: 0 },
|
||||
]);
|
||||
});
|
||||
|
||||
test("setRaw: a property of an interface the library does not describe, nothing checked", () => {
|
||||
const state = new StateBuilder({ now }).setRaw("Alexa.Vendor.Thing", "level", { anything: true }, { instance: "Thing.One" });
|
||||
assert.deepEqual(state.context, [
|
||||
{ namespace: "Alexa.Vendor.Thing", instance: "Thing.One", name: "level", value: { anything: true }, timeOfSample: AT, uncertaintyInMilliseconds: 0 },
|
||||
]);
|
||||
});
|
||||
|
||||
test("health: the connectivity of Alexa.EndpointHealth, with the reason when there is one", () => {
|
||||
const state = new StateBuilder({ now }).health("OK").health("UNREACHABLE", "WIFI_AP_NOT_FOUND");
|
||||
assert.deepEqual(state.context.map((property) => [property.namespace, property.name, property.value]), [
|
||||
[EndpointHealth.namespace, "connectivity", { value: "OK" }],
|
||||
[EndpointHealth.namespace, "connectivity", { value: "UNREACHABLE", reason: "WIFI_AP_NOT_FOUND" }],
|
||||
]);
|
||||
assert.throws(() => new StateBuilder().health("ASLEEP"), SchemaError);
|
||||
});
|
||||
|
||||
test("changed and unchanged: the list the properties that follow go to; add() names one", () => {
|
||||
const state = new StateBuilder({ now, target: "change" })
|
||||
.set(PowerController, "powerState", "ON")
|
||||
.unchanged()
|
||||
.set(BrightnessController, "brightness", 40)
|
||||
.changed()
|
||||
.health("OK")
|
||||
.add(messages.property("Alexa.Vendor.Thing", "level", 1, { timeOfSample: AT }), "context");
|
||||
assert.deepEqual(state.change.map((property) => property.name), ["powerState", "connectivity"]);
|
||||
assert.deepEqual(state.context.map((property) => property.name), ["brightness", "level"]);
|
||||
});
|
||||
|
||||
test("context and change are copies: the message built from them does not change with the builder", () => {
|
||||
const state = new StateBuilder({ now }).set(PowerController, "powerState", "ON");
|
||||
const report = messages.stateReport({ endpointId: "lamp-1", correlationToken: "ct", messageId: "m", context: state.context });
|
||||
state.set(BrightnessController, "brightness", 40);
|
||||
assert.equal(report.context.properties.length, 1);
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue