import { randomUUID } from "crypto"; import { errorResponse } from "../messages/build.js"; import { AlexaErrors } from "../messages/errors.js"; import * as topics from "../topics.js"; import { send } from "../transport.js"; /** An ErrorResponse as 1.x builds it: device.getErrorMessage(token), setErrorMessage(), send(). */ export class AlexaErrorResponse { constructor(correlationToken, rootTopic, endpointId, publisher) { this.correlationToken = correlationToken; this.rootTopic = rootTopic; this.endpointId = endpointId; this.publisher = publisher; // Sent when setErrorMessage() was not called: 1.x published an empty payload, which is no ErrorResponse to Alexa this.error = AlexaErrors.of("INTERNAL_ERROR", "the device answered with an error and did not say which"); // One id for the message, however often toJSON() is called this.messageId = randomUUID(); } /** * The error to answer with. otherParams are the fields the type adds to the payload (validRange). The header * carries the namespace the type is documented under, Alexa.ThermostatController for THERMOSTAT_IS_OFF; * options.namespace names another. */ setErrorMessage(type, message, otherParams = {}, options = {}) { this.error = AlexaErrors.of(type, message, otherParams); this.namespace = options.namespace; } toJSON() { const { type, alexaMessage, extra } = this.error; return errorResponse({ endpointId: this.endpointId, messageId: this.messageId, correlationToken: this.correlationToken, type, message: alexaMessage, extra, namespace: this.namespace ?? this.error.namespace, }); } /** Resolves with the topic published to, or "" when the publish failed. Never rejects. */ send(sendAsync = false) { const answer = sendAsync ? topics.deferred : topics.response; return send(this.publisher, answer(this.rootTopic, this.endpointId), () => this.toJSON(), this.onPublishError); } }