All files / common client.js

96.48% Statements 329/341
94.57% Branches 244/258
100% Functions 52/52
96.48% Lines 329/341

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603    25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x   270x   25x       115x 115x 115x 115x 114x 114x 104x 104x 104x 104x 104x 104x     8757x     10x     19x     155x 1x   154x 154x 152x 152x     158x 6x   152x 152x 152x 152x 152x 152x     23x 23x 2x   21x 21x 21x 1x 1x 1x   20x 1x 1x 1x   19x 19x 1x 1x     18x 18x           22x 22x     13x     1625x     5x             27x       1429x 1429x 2x   1427x 1397x 1384x 1384x 1296x   1328x 1328x 1326x 1325x   1325x 1325x 2x 1x 1x 1x     1x 1x 1x 1x     1323x 1323x 1x 1x     1322x 1322x           203x 203x 2x   201x 171x 160x 158x 158x 4x 4x 4x   154x 154x 2x 2x 2x   152x 152x 1x 1x     151x 151x               1598x 2x   1596x 1x   1595x 8x   1587x 2x   1585x 1x   1584x   10x       2812x 1x   2811x 14x   2797x   177x   83x 3x   80x   35x 2x   33x   29x 1x   28x   30x 3x   27x       168x   131x   43x 4x   39x   30x 3x   27x   30x 4x   26x   28x 2x   26x       118x   304x   117x 6x   111x   61x 3x   58x   63x 3x   60x   63x 2x   61x       290x   1869x   684x 6x   678x   420x 2x   418x   451x 4x   447x   314x 7x   307x       1850x   264x   81x 1x   80x   66x     66x   59x     59x   58x     58x       263x   16x   5x     5x   4x     4x   4x 1x   3x   3x   12x   8x 4x   4x   9x 4x   5x   19x 19x 18x       152x       154x 154x                                   154x 154x 1x   154x 154x 154x 154x 4x 4x 4x     154x       152x 152x 152x     153x 153x 153x 1x 1x       153x     1x     155x 155x     1x 1x     2x 2x     1675x         152x     152x 152x 152x 152x 152x 152x         437x 437x 437x 47x         1675x 1675x 1675x 1675x 1675x 1673x 1672x 1672x 1292x   1658x 1658x 1711x       18x 1x 1x   17x 17x         114x 1x   113x 4x   109x 2x   107x     107x 3x       107x     1628x 4x   1624x 8x   1616x 27x 2x   25x 25x 3x   22x 3x       1589x       4827x     154x 154x 127x 127x           27x     1452x 1452x   1x       1x     1451x   1452x     1511x 1511x 1510x   1511x 1511x 1511x 1511x 1511x       1511x 1511x 1511x     25x 25x 25x  
"use strict";
/*! Copyright (c) 2021 Siemens AG. Licensed under the MIT License. */
Object.defineProperty(exports, "__esModule", { value: true });
exports.Client = exports.createUuid = void 0;
const debug_1 = require("debug");
const mqtt_1 = require("mqtt");
const uuid_1 = require("uuid");
const __1 = require("..");
const mqtt_utils_1 = require("./mqtt-utils");
const subscription_manager_1 = require("./subscription-manager");
const vda_5050_validators_1_1_1 = require("./vda-5050-validators-1.1");
const vda_5050_validators_2_0_1 = require("./vda-5050-validators-2.0");
const vda_5050_validators_2_1_1 = require("./vda-5050-validators-2.1");
const vda_5050_validators_3_0_1 = require("./vda-5050-validators-3.0");
function createUuid() {
    return (0, uuid_1.v4)();
}
exports.createUuid = createUuid;
class Client {
    constructor(options) {
        var _a;
        this._isStarted = false;
        this._isStopping = false;
        this._clientOptions = options;
        this.clientId = (_a = options.transport.clientId) !== null && _a !== void 0 ? _a : `${(0, uuid_1.v4)().replace(/-/g, "").substr(0, 23)}`;
        this.debug = (0, debug_1.default)(`vda-5050:${this.clientId.substr(0, 10)}`).extend(this.constructor.name);
        this._validateOptions(options);
        this._headerIds = new Map();
        this._subscriptionManager = new subscription_manager_1.SubscriptionManager(options.transport.topicFormat || Client.DEFAULT_MQTT_TOPIC_FORMAT, this.clientOptions.interfaceName, this.getProtocolVersion());
        this._isWebPlatform = new Function("try {return this===window;}catch(e){return false;}")();
        this._extensionTopics = new Map();
        this._emitConnectionStateChange("offline");
        this.debug("Create instance with clientOptions %o", options);
    }
    get clientOptions() {
        return this._clientOptions;
    }
    get protocolVersion() {
        return this.getProtocolVersion();
    }
    createUuid() {
        return createUuid();
    }
    async start() {
        if (this._isStarted) {
            return;
        }
        this.debug("Starting client");
        await this._connect();
        this._isStarted = true;
        await this.onStarted();
    }
    async stop() {
        if (!this._isStarted || this._isStopping) {
            return;
        }
        this.debug("Stopping client");
        this._isStopping = true;
        await this.onStopping();
        this._isStarted = false;
        this._isStopping = false;
        await this._disconnect();
    }
    unsubscribe(subscriptionId) {
        this.debug("Unsubscribing subscription ID %s", subscriptionId);
        if (!this._isStarted) {
            throw new Error("Client is not started");
        }
        return new Promise((resolve, reject) => {
            const { mqttTopic, requiresUnsubscribe } = this._subscriptionManager.remove(subscriptionId);
            if (!requiresUnsubscribe) {
                this.debug("Unsubscribed id %s, more subscriptions on MQTT topic %s", subscriptionId, mqttTopic);
                resolve();
                return;
            }
            if (!this._mqtt.connected) {
                this.debug("Unsubscribe on MQTT topic %s for id %s while offline", mqttTopic, subscriptionId);
                resolve();
                return;
            }
            this._mqtt.unsubscribe(mqttTopic, err => {
                if (err) {
                    this.debug("Unsubscribe on MQTT topic %s for id %s failed: %s", mqttTopic, subscriptionId, err);
                    reject(err);
                }
                else {
                    this.debug("Unsubscribed on MQTT topic %s for id %s", mqttTopic, subscriptionId);
                    resolve();
                }
            });
        });
    }
    registerConnectionStateChange(callback) {
        this._connectionStateChangeCallback = callback;
        this._emitConnectionStateChange(this._connectionState);
    }
    registerExtensionTopic(extensionTopic, asInbound, asOutbound, validator) {
        this._extensionTopics.set(extensionTopic, [asInbound, asOutbound, validator]);
    }
    getProtocolVersion() {
        return this._clientOptions.vdaVersion;
    }
    get isStarted() {
        return this._isStarted;
    }
    onStarted() {
    }
    onStopping() {
    }
    getLastWillTopic() {
        return undefined;
    }
    publishTopic(topic, subject, object, options) {
        var _a;
        this.debug("Publishing on topic %s for subject %o with object %j", topic, subject, object);
        if (!this._isStarted) {
            throw new Error("Client is not started");
        }
        this._validateTopic(topic, false);
        this.validateAgvId(subject, false);
        const headerfullObject = this._withObjectHeader(topic, subject, object);
        if (((_a = this.clientOptions.topicObjectValidation) === null || _a === void 0 ? void 0 : _a.outbound) !== false) {
            this.validateTopicObject(topic, headerfullObject, this.clientOptions.vdaVersion);
        }
        const mqttTopic = this._subscriptionManager.getMqttTopic(topic, subject);
        (0, mqtt_utils_1.assertMqttTopicLength)(mqttTopic);
        const mqttPayload = JSON.stringify(headerfullObject);
        return new Promise((resolve, reject) => {
            var _a;
            const mqttOptions = this._withMqttProperties({ retain: (_a = options === null || options === void 0 ? void 0 : options.retainMessage) !== null && _a !== void 0 ? _a : false });
            if (!this._mqtt.connected) {
                if (options === null || options === void 0 ? void 0 : options.dropIfOffline) {
                    this.debug("Drop offline publish on topic %s", mqttTopic);
                    resolve(undefined);
                    return;
                }
                else {
                    this.debug("Publish on MQTT topic %s while offline with retain %s with object %j", mqttTopic, mqttOptions.retain, headerfullObject);
                    this._mqtt.publish(mqttTopic, mqttPayload, mqttOptions);
                    resolve(headerfullObject);
                    return;
                }
            }
            this._mqtt.publish(mqttTopic, mqttPayload, mqttOptions, err => {
                if (err) {
                    this.debug("Publish on MQTT topic %s failed: %s", mqttTopic, err);
                    reject(err);
                }
                else {
                    this.debug("Published on MQTT topic %s with retain %s with object %j", mqttTopic, mqttOptions.retain, headerfullObject);
                    resolve(headerfullObject);
                }
            });
        });
    }
    subscribeTopic(topic, subject, handler) {
        this.debug("Subscribing on topic %s for subject %o", topic, subject);
        if (!this._isStarted) {
            throw new Error("Client is not started");
        }
        this._validateTopic(topic, true);
        this.validateAgvId(subject, true);
        const { id, mqttTopic, requiresSubscribe } = this._subscriptionManager.add(topic, subject, handler);
        return new Promise((resolve, reject) => {
            if (!requiresSubscribe) {
                this.debug("Already subscribed on MQTT topic %s with id %s", mqttTopic, id);
                resolve(id);
                return;
            }
            const mqttOptions = { qos: 0, rap: true, rh: 0 };
            if (!this._mqtt.connected) {
                this.debug("Subscribe on MQTT topic %s with id %s while offline", mqttTopic, id);
                resolve(id);
                return;
            }
            this._mqtt.subscribe(mqttTopic, mqttOptions, err => {
                if (err) {
                    this.debug("Subscribe on MQTT topic %s with id %s failed: %s", mqttTopic, id, err);
                    reject(err);
                }
                else {
                    this.debug("Subscribed on MQTT topic %s with id %s", mqttTopic, id);
                    resolve(id);
                }
            });
        });
    }
    validateTopicDirection(topic, forSubscription) {
    }
    validateAgvId(agvId, forSubscription) {
        if (agvId.manufacturer === "") {
            throw new TypeError("Empty string passed in AgvId.manufacturer.");
        }
        if (!forSubscription && !agvId.manufacturer) {
            throw new TypeError("AgvId.manufacturer not specified for publication");
        }
        if (agvId.manufacturer && !this._isValidTopicLevel(agvId.manufacturer)) {
            throw new TypeError("AgvId.manufacturer is not a valid MQTT topic level");
        }
        if (agvId.serialNumber === "") {
            throw new TypeError("Empty string passed in AgvId.serialNumber.");
        }
        if (!forSubscription && !agvId.serialNumber) {
            throw new TypeError("AgvId.serialNumber not specified for publication");
        }
        if (agvId.serialNumber &&
            (!this._isValidTopicLevel(agvId.serialNumber) || /[^A-Za-z0-9_.:-]/.test(agvId.serialNumber))) {
            throw new TypeError("AgvId.serialNumber is not a valid MQTT topic level or not restricted to A-Z a-z 0-9 _ . : -");
        }
    }
    validateTopicObject(topic, object, vdaVersion) {
        if (!object || typeof object !== "object") {
            throw new TypeError(`Invalid VDA 5050 object ${object}`);
        }
        if (object.version !== vdaVersion) {
            throw new TypeError(`Invalid VDA 5050 Version. ${topic} version: ${object.version} is not compatible with client verion: ${vdaVersion}`);
        }
        switch (topic) {
            case __1.Topic.Connection:
                switch (vdaVersion) {
                    case "1.1.0":
                        if (!(0, vda_5050_validators_1_1_1.validateConnection)(object)) {
                            throw new TypeError(`Invalid VDA 5050 Connection at ${vda_5050_validators_1_1_1.validateConnection.errors[0].keywordLocation}, ${vda_5050_validators_1_1_1.validateConnection.errors[0].instanceLocation}`);
                        }
                        break;
                    case "2.0.0":
                        if (!(0, vda_5050_validators_2_0_1.validateConnection)(object)) {
                            throw new TypeError(`Invalid VDA 5050 Connection at ${vda_5050_validators_2_0_1.validateConnection.errors[0].keywordLocation}, ${vda_5050_validators_2_0_1.validateConnection.errors[0].instanceLocation}`);
                        }
                        break;
                    case "2.1.0":
                        if (!(0, vda_5050_validators_2_1_1.validateConnection)(object)) {
                            throw new TypeError(`Invalid VDA 5050 Connection at ${vda_5050_validators_2_1_1.validateConnection.errors[0].keywordLocation}, ${vda_5050_validators_2_1_1.validateConnection.errors[0].instanceLocation}`);
                        }
                        break;
                    case "3.0.0":
                        if (!(0, vda_5050_validators_3_0_1.validateConnection)(object)) {
                            throw new TypeError(`Invalid VDA 5050 Connection at ${vda_5050_validators_3_0_1.validateConnection.errors[0].keywordLocation}, ${vda_5050_validators_3_0_1.validateConnection.errors[0].instanceLocation}`);
                        }
                        break;
                    default:
                        throw new TypeError(`Connection Topic not supported with VDA 5050 Version ${vdaVersion}`);
                }
                break;
            case __1.Topic.InstantActions:
                switch (vdaVersion) {
                    case "1.1.0":
                        if (!(0, vda_5050_validators_1_1_1.validateInstantActions)(object)) {
                            throw new TypeError(`Invalid VDA 5050 InstantActions at ${vda_5050_validators_1_1_1.validateInstantActions.errors[0].keywordLocation}, ${vda_5050_validators_1_1_1.validateInstantActions.errors[0].instanceLocation}`);
                        }
                        break;
                    case "2.0.0":
                        if (!(0, vda_5050_validators_2_0_1.validateInstantActions)(object)) {
                            throw new TypeError(`Invalid VDA 5050 InstantActions at ${vda_5050_validators_2_0_1.validateInstantActions.errors[0].keywordLocation}, ${vda_5050_validators_2_0_1.validateInstantActions.errors[0].instanceLocation}`);
                        }
                        break;
                    case "2.1.0":
                        if (!(0, vda_5050_validators_2_1_1.validateInstantActions)(object)) {
                            throw new TypeError(`Invalid VDA 5050 InstantActions at ${vda_5050_validators_2_1_1.validateInstantActions.errors[0].keywordLocation}, ${vda_5050_validators_2_1_1.validateInstantActions.errors[0].instanceLocation}`);
                        }
                        break;
                    case "3.0.0":
                        if (!(0, vda_5050_validators_3_0_1.validateInstantActions)(object)) {
                            throw new TypeError(`Invalid VDA 5050 InstantActions at ${vda_5050_validators_3_0_1.validateInstantActions.errors[0].keywordLocation}, ${vda_5050_validators_3_0_1.validateInstantActions.errors[0].instanceLocation}`);
                        }
                        break;
                    default:
                        throw new TypeError(`InstantAction Topic not supported with VDA 5050 Version ${vdaVersion}`);
                }
                break;
            case __1.Topic.Order:
                switch (vdaVersion) {
                    case "1.1.0":
                        if (!(0, vda_5050_validators_1_1_1.validateOrder)(object)) {
                            throw new TypeError(`Invalid VDA 5050 Order at ${vda_5050_validators_1_1_1.validateOrder.errors[0].keywordLocation}, ${vda_5050_validators_1_1_1.validateOrder.errors[0].instanceLocation}`);
                        }
                        break;
                    case "2.0.0":
                        if (!(0, vda_5050_validators_2_0_1.validateOrder)(object)) {
                            throw new TypeError(`Invalid VDA 5050 Order at ${vda_5050_validators_2_0_1.validateOrder.errors[0].keywordLocation}, ${vda_5050_validators_2_0_1.validateOrder.errors[0].instanceLocation}`);
                        }
                        break;
                    case "2.1.0":
                        if (!(0, vda_5050_validators_2_1_1.validateOrder)(object)) {
                            throw new TypeError(`Invalid VDA 5050 Order at ${vda_5050_validators_2_1_1.validateOrder.errors[0].keywordLocation}, ${vda_5050_validators_2_1_1.validateOrder.errors[0].instanceLocation}`);
                        }
                        break;
                    case "3.0.0":
                        if (!(0, vda_5050_validators_3_0_1.validateOrder)(object)) {
                            throw new TypeError(`Invalid VDA 5050 Order at ${vda_5050_validators_3_0_1.validateOrder.errors[0].keywordLocation}, ${vda_5050_validators_3_0_1.validateOrder.errors[0].instanceLocation}`);
                        }
                        break;
                    default:
                        throw new TypeError(`Order Topic not supported with VDA 5050 Version ${vdaVersion}`);
                }
                break;
            case __1.Topic.State:
                switch (vdaVersion) {
                    case "1.1.0":
                        if (!(0, vda_5050_validators_1_1_1.validateState)(object)) {
                            throw new TypeError(`Invalid VDA 5050 State at ${vda_5050_validators_1_1_1.validateState.errors[0].keywordLocation}, ${vda_5050_validators_1_1_1.validateState.errors[0].instanceLocation}`);
                        }
                        break;
                    case "2.0.0":
                        if (!(0, vda_5050_validators_2_0_1.validateState)(object)) {
                            throw new TypeError(`Invalid VDA 5050 State at ${vda_5050_validators_2_0_1.validateState.errors[0].keywordLocation}, ${vda_5050_validators_2_0_1.validateState.errors[0].instanceLocation}`);
                        }
                        break;
                    case "2.1.0":
                        if (!(0, vda_5050_validators_2_1_1.validateState)(object)) {
                            throw new TypeError(`Invalid VDA 5050 State at ${vda_5050_validators_2_1_1.validateState.errors[0].keywordLocation}, ${vda_5050_validators_2_1_1.validateState.errors[0].instanceLocation}`);
                        }
                        break;
                    case "3.0.0":
                        if (!(0, vda_5050_validators_3_0_1.validateState)(object)) {
                            throw new TypeError(`Invalid VDA 5050 State at ${vda_5050_validators_3_0_1.validateState.errors[0].keywordLocation}, ${vda_5050_validators_3_0_1.validateState.errors[0].instanceLocation}`);
                        }
                        break;
                    default:
                        throw new TypeError(`State Topic not supported with VDA 5050 Version ${vdaVersion}`);
                }
                break;
            case __1.Topic.Visualization:
                switch (vdaVersion) {
                    case "1.1.0":
                        if (!(0, vda_5050_validators_1_1_1.validateVisualization)(object)) {
                            throw new TypeError(`Invalid VDA 5050 Visualization at ${vda_5050_validators_1_1_1.validateVisualization.errors[0].keywordLocation}, ${vda_5050_validators_1_1_1.validateVisualization.errors[0].instanceLocation}`);
                        }
                        break;
                    case "2.0.0":
                        Iif (!(0, vda_5050_validators_2_0_1.validateVisualization)(object)) {
                            throw new TypeError(`Invalid VDA 5050 Visualization at ${vda_5050_validators_2_0_1.validateVisualization.errors[0].keywordLocation}, ${vda_5050_validators_2_0_1.validateVisualization.errors[0].instanceLocation}`);
                        }
                        break;
                    case "2.1.0":
                        Iif (!(0, vda_5050_validators_2_1_1.validateVisualization)(object)) {
                            throw new TypeError(`Invalid VDA 5050 Visualization at ${vda_5050_validators_2_1_1.validateVisualization.errors[0].keywordLocation}, ${vda_5050_validators_2_1_1.validateVisualization.errors[0].instanceLocation}`);
                        }
                        break;
                    case "3.0.0":
                        Iif (!(0, vda_5050_validators_3_0_1.validateVisualization)(object)) {
                            throw new TypeError(`Invalid VDA 5050 Visualization at ${vda_5050_validators_3_0_1.validateVisualization.errors[0].keywordLocation}, ${vda_5050_validators_3_0_1.validateVisualization.errors[0].instanceLocation}`);
                        }
                        break;
                    default:
                        throw new TypeError(`Visualization Topic not supported with VDA 5050 Version ${vdaVersion}`);
                }
                break;
            case __1.Topic.Factsheet:
                switch (vdaVersion) {
                    case "2.0.0":
                        Iif (!(0, vda_5050_validators_2_0_1.validateFactsheet)(object)) {
                            throw new TypeError(`Invalid VDA 5050 Factsheet at ${vda_5050_validators_2_0_1.validateFactsheet.errors[0].keywordLocation}, ${vda_5050_validators_2_0_1.validateFactsheet.errors[0].instanceLocation}`);
                        }
                        break;
                    case "2.1.0":
                        Iif (!(0, vda_5050_validators_2_1_1.validateFactsheet)(object)) {
                            throw new TypeError(`Invalid VDA 5050 Factsheet at ${vda_5050_validators_2_1_1.validateFactsheet.errors[0].keywordLocation}, ${vda_5050_validators_2_1_1.validateFactsheet.errors[0].instanceLocation}`);
                        }
                        break;
                    case "3.0.0":
                        if (!(0, vda_5050_validators_3_0_1.validateFactsheet)(object)) {
                            throw new TypeError(`Invalid VDA 5050 Factsheet at ${vda_5050_validators_3_0_1.validateFactsheet.errors[0].keywordLocation}, ${vda_5050_validators_3_0_1.validateFactsheet.errors[0].instanceLocation}`);
                        }
                        break;
                    default:
                        throw new TypeError(`Factsheet Topic not supported with VDA 5050 Version ${vdaVersion}`);
                }
                break;
            case __1.Topic.ZoneSet:
                if (!(0, vda_5050_validators_3_0_1.validateZoneSet)(object)) {
                    throw new TypeError(`Invalid VDA 5050 ZoneSet at ${vda_5050_validators_3_0_1.validateZoneSet.errors[0].keywordLocation}, ${vda_5050_validators_3_0_1.validateZoneSet.errors[0].instanceLocation}`);
                }
                break;
            case __1.Topic.Responses:
                if (!(0, vda_5050_validators_3_0_1.validateResponses)(object)) {
                    throw new TypeError(`Invalid VDA 5050 Responses at ${vda_5050_validators_3_0_1.validateResponses.errors[0].keywordLocation}, ${vda_5050_validators_3_0_1.validateResponses.errors[0].instanceLocation}`);
                }
                break;
            default:
                const [, , validator] = this._extensionTopics.get(topic);
                validator(topic, object);
                break;
        }
    }
    reset() {
        this._subscriptionManager.clear();
    }
    _connect() {
        var _a, _b, _c, _d, _e;
        const transOpts = this.clientOptions.transport;
        const mqttOpts = {
            keepalive: (_a = transOpts.heartbeat) !== null && _a !== void 0 ? _a : 15,
            reschedulePings: false,
            clientId: this.clientId,
            protocolId: "MQTT",
            protocolVersion: transOpts.protocolVersion === "5.0" ? 5 : 4,
            reconnectPeriod: (_b = transOpts.reconnectPeriod) !== null && _b !== void 0 ? _b : 1000,
            connectTimeout: (_c = transOpts.connectTimeout) !== null && _c !== void 0 ? _c : 30000,
            clean: true,
            resubscribe: false,
            queueQoSZero: true,
            username: transOpts.username,
            password: transOpts.password,
            ...(_d = transOpts.tlsOptions) !== null && _d !== void 0 ? _d : {},
            wsOptions: (_e = transOpts.wsOptions) !== null && _e !== void 0 ? _e : {},
            transformWsUrl: transOpts.transformWsUrl,
            will: this._createLastWill(),
        };
        let connectionUrl = this.clientOptions.transport.brokerUrl;
        if (this._isWebPlatform) {
            connectionUrl = connectionUrl.replace(/^mqtt/, "ws");
        }
        return new Promise((resolve, reject) => {
            this.debug("Connecting to %s", connectionUrl);
            const mqtt = this._mqtt = (0, mqtt_1.connect)(connectionUrl, mqttOpts);
            const onceFailureListener = error => {
                this._mqtt = undefined;
                mqtt.end(true, () => {
                    reject(error);
                });
            };
            mqtt
                .once("error", onceFailureListener)
                .once("close", onceFailureListener)
                .once("connect", () => {
                mqtt.removeListener("error", onceFailureListener);
                mqtt.removeListener("close", onceFailureListener);
                resolve();
            })
                .prependListener("connect", () => {
                this.debug("Connected to %s", connectionUrl);
                const resubscribes = this._subscriptionManager.getAll();
                if (resubscribes.length > 0) {
                    this.debug("Resubscribe %d subscription topics", resubscribes.length);
                    mqtt.subscribe(resubscribes);
                }
            })
                .on("connect", () => {
                this._emitConnectionStateChange("online");
            })
                .on("reconnect", () => {
                this.debug("Reconnecting to %s", connectionUrl);
            })
                .on("close", () => {
                this._emitConnectionStateChange("offline");
                this.debug("Disconnected");
            })
                .on("offline", () => {
                this._emitConnectionStateChange("offline");
                this.debug("Offline - connection broken - reconnection pending");
            })
                .on("error", error => {
                this._emitConnectionStateChange("offline");
                this.debug("Error on connect: %s", error);
            })
                .on("message", (topic, payload) => {
                this._dispatchMessage(topic, payload);
            });
        });
    }
    _disconnect() {
        Iif (!this._mqtt) {
            return;
        }
        const mqtt = this._mqtt;
        this._mqtt = undefined;
        return new Promise(resolve => {
            mqtt.end(false, () => {
                this.reset();
                resolve();
            });
        });
    }
    _emitConnectionStateChange(connectionState) {
        const previousConnectionState = this._connectionState;
        this._connectionState = connectionState;
        if (this._connectionStateChangeCallback) {
            this._connectionStateChangeCallback(connectionState, previousConnectionState);
        }
    }
    _dispatchMessage(mqttTopic, mqttPayload) {
        var _a;
        let rethrowError = false;
        try {
            const payloadString = mqttPayload.toString();
            this.debug("Inbound message on MQTT topic %s with payload %s", mqttTopic, payloadString);
            const object = JSON.parse(payloadString);
            const subject = { manufacturer: object.manufacturer, serialNumber: object.serialNumber };
            const [idAndHandlers, topic] = this._subscriptionManager.find(mqttTopic, subject);
            if (((_a = this.clientOptions.topicObjectValidation) === null || _a === void 0 ? void 0 : _a.inbound) !== false) {
                this.validateTopicObject(topic, object, this.clientOptions.vdaVersion);
            }
            rethrowError = true;
            for (const [id, handler] of idAndHandlers) {
                handler(object, subject, topic, id);
            }
        }
        catch (error) {
            if (rethrowError) {
                this.debug("Uncaught error in handler for inbound message on MQTT topic %s: %s", mqttTopic, error.message);
                throw error;
            }
            console.error("Drop inbound message on MQTT topic %s with error: %s", mqttTopic, error.message);
            this.debug("Drop inbound message on MQTT topic %s with error: %s", mqttTopic, error.message);
        }
    }
    _validateOptions(options) {
        var _a;
        if (options.interfaceName === undefined) {
            throw new TypeError("ClientOption interfaceName is required");
        }
        if (!this._isValidTopicLevel(options.interfaceName)) {
            throw new TypeError("ClientOption interfaceName is not a valid MQTT topic level");
        }
        if (!((_a = options.transport) === null || _a === void 0 ? void 0 : _a.brokerUrl)) {
            throw new TypeError("MqttTransportOption brokerUrl is missing");
        }
        Iif (options.vdaVersion === undefined) {
            throw new TypeError(`Vda Version is required`);
        }
        if (!this._isValidVdaVersion(options.vdaVersion)) {
            throw new TypeError(`Vda ${options.vdaVersion} Version not supported`);
        }
    }
    _isValidVdaVersion(version) {
        return version === "1.1.0" || version === "1.1" || version === "2.0" || version === "2.0.0" || version === "2.1" || version === "2.1.0" || version === "3.0" || version === "3.0.0";
    }
    _validateTopic(topic, forSubscription) {
        if (!topic) {
            throw new TypeError("Topic undefined or empty");
        }
        if (!this._isValidTopicLevel(topic)) {
            throw new TypeError(`Topic ${topic} is not a valid MQTT topic level`);
        }
        if ((0, __1.isExtensionTopic)(topic)) {
            if (!this._extensionTopics.has(topic)) {
                throw new TypeError(`Extension topic ${topic} is not registered`);
            }
            const [asInbound, asOutbound] = this._extensionTopics.get(topic);
            if (forSubscription && !asInbound) {
                throw new TypeError(`Extension topic ${topic} is not registered for inbound communication`);
            }
            if (!forSubscription && !asOutbound) {
                throw new TypeError(`Extension topic ${topic} is not registered for outbound communication`);
            }
        }
        else {
            this.validateTopicDirection(topic, forSubscription);
        }
    }
    _isValidTopicLevel(name) {
        return !Client.ILLEGAL_TOPIC_LEVEL_CHARS_REGEX.test(name);
    }
    _createLastWill() {
        const lastWill = this.getLastWillTopic();
        if (lastWill) {
            const mqttTopic = this._subscriptionManager.getMqttTopic(lastWill.topic, lastWill.subject);
            return this._withMqttProperties({
                topic: mqttTopic,
                payload: JSON.stringify(this._withObjectHeader(lastWill.topic, lastWill.subject, lastWill.object)),
                retain: lastWill.retainMessage,
            });
        }
        return undefined;
    }
    _withMqttProperties(pub) {
        pub.qos = 0;
        switch (this.clientOptions.transport.protocolVersion) {
            case "5.0":
                pub.properties = {
                    payloadFormatIndicator: true,
                    contentType: "application/json",
                };
                break;
            case "3.1.1":
            default:
                break;
        }
        return pub;
    }
    _withObjectHeader(topic, subject, object) {
        const obj = Object.assign({}, object);
        if (obj.timestamp === undefined) {
            obj.timestamp = new Date().toISOString();
        }
        obj.headerId = this._nextHeaderId(topic);
        obj.manufacturer = subject.manufacturer;
        obj.serialNumber = subject.serialNumber;
        obj.version = this.getProtocolVersion();
        return obj;
    }
    _nextHeaderId(topic) {
        var _a;
        const id = (_a = this._headerIds.get(topic)) !== null && _a !== void 0 ? _a : 0;
        this._headerIds.set(topic, id < 0xFFFFFFFF ? id + 1 : 0);
        return id;
    }
}
exports.Client = Client;
Client.ILLEGAL_TOPIC_LEVEL_CHARS_REGEX = /[\u0000+#/]/;
Client.DEFAULT_MQTT_TOPIC_FORMAT = "%interfaceName%/%majorVersion%/%manufacturer%/%serialNumber%/%topic%";