File Explorer

/var/runtime/node_modules/@aws-sdk/node_modules/aws-crt/dist.browser/browser

This explorer reads the filesystem of the server it runs on, so /workspace/user isn't present here. Browsing and the terminal still work against this server's own disk from /.

mqtt5.js25.3 KB · 542 lines
"use strict";/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */var __extends = (this && this.__extends) || (function () {    var extendStatics = function (d, b) {        extendStatics = Object.setPrototypeOf ||            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };        return extendStatics(d, b);    };    return function (d, b) {        if (typeof b !== "function" && b !== null)            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");        extendStatics(d, b);        function __() { this.constructor = d; }        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());    };})();var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {    if (k2 === undefined) k2 = k;    var desc = Object.getOwnPropertyDescriptor(m, k);    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {      desc = { enumerable: true, get: function() { return m[k]; } };    }    Object.defineProperty(o, k2, desc);}) : (function(o, m, k, k2) {    if (k2 === undefined) k2 = k;    o[k2] = m[k];}));var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {    Object.defineProperty(o, "default", { enumerable: true, value: v });}) : function(o, v) {    o["default"] = v;});var __importStar = (this && this.__importStar) || function (mod) {    if (mod && mod.__esModule) return mod;    var result = {};    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);    __setModuleDefault(result, mod);    return result;};var __exportStar = (this && this.__exportStar) || function(m, exports) {    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);};var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }    return new (P || (P = Promise))(function (resolve, reject) {        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }        step((generator = generator.apply(thisArg, _arguments || [])).next());    });};var __generator = (this && this.__generator) || function (thisArg, body) {    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;    function verb(n) { return function (v) { return step([n, v]); }; }    function step(op) {        if (f) throw new TypeError("Generator is already executing.");        while (g && (g = 0, op[0] && (_ = 0)), _) try {            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;            if (y = 0, t) op = [op[0] & 2, t.value];            switch (op[0]) {                case 0: case 1: t = op; break;                case 4: _.label++; return { value: op[1], done: false };                case 5: _.label++; y = op[1]; op = [0]; continue;                case 7: op = _.ops.pop(); _.trys.pop(); continue;                default:                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }                    if (t[2]) _.ops.pop();                    _.trys.pop(); continue;            }            op = body.call(thisArg, _);        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };    }};Object.defineProperty(exports, "__esModule", { value: true });exports.Mqtt5Client = exports.Mqtt5WebsocketUrlFactoryType = void 0;/** * Browser specific MQTT5 client implementation * * @packageDocumentation * @module mqtt5 * @mergeTarget * */var event_1 = require("../common/event");var internal_mqtt_client = __importStar(require("./mqtt_internal/client"));var client_1 = require("./mqtt_internal/client");var mqtt5 = __importStar(require("../common/mqtt5"));var mqtt5_packet = __importStar(require("../common/mqtt5_packet"));var error_1 = require("./error");var ws = __importStar(require("./ws"));var mqtt_shared = __importStar(require("../common/mqtt_shared"));var mqtt_shared_browser = __importStar(require("./mqtt_shared_browser"));var aws_iot_metrics = __importStar(require("./aws_iot_metrics"));var validate = __importStar(require("./mqtt_internal/validate"));__exportStar(require("../common/mqtt5"), exports);__exportStar(require("../common/mqtt5_packet"), exports);/** * Type of url to construct when establishing an MQTT5 connection over websockets */var Mqtt5WebsocketUrlFactoryType;(function (Mqtt5WebsocketUrlFactoryType) {    /**     * Websocket connection over plain-text with no additional handshake transformation     */    Mqtt5WebsocketUrlFactoryType[Mqtt5WebsocketUrlFactoryType["Ws"] = 1] = "Ws";    /**     * Websocket connection over TLS with no additional handshake transformation     */    Mqtt5WebsocketUrlFactoryType[Mqtt5WebsocketUrlFactoryType["Wss"] = 2] = "Wss";    /**     * Websocket connection over TLS with a handshake signed by the Aws Sigv4 signing process     */    Mqtt5WebsocketUrlFactoryType[Mqtt5WebsocketUrlFactoryType["Sigv4"] = 3] = "Sigv4";    /**     * Websocket connection whose url is formed by a user-supplied callback function     */    Mqtt5WebsocketUrlFactoryType[Mqtt5WebsocketUrlFactoryType["Custom"] = 4] = "Custom";})(Mqtt5WebsocketUrlFactoryType = exports.Mqtt5WebsocketUrlFactoryType || (exports.Mqtt5WebsocketUrlFactoryType = {}));;;;function convertSessionBehaviorToSessionPolicy(behavior) {    switch (behavior) {        case mqtt5.ClientSessionBehavior.Default:        case mqtt5.ClientSessionBehavior.Clean:            return internal_mqtt_client.ResumeSessionPolicyType.Never;        case mqtt5.ClientSessionBehavior.RejoinPostSuccess:            return internal_mqtt_client.ResumeSessionPolicyType.PostSuccess;        case mqtt5.ClientSessionBehavior.RejoinAlways:            return internal_mqtt_client.ResumeSessionPolicyType.Always;        default:            return internal_mqtt_client.ResumeSessionPolicyType.Default;    }}function buildInternalConnectOptions(internalConnectOptions, clientConfig, connectProperties) {    if (clientConfig.disableMetrics) {        if (connectProperties === null || connectProperties === void 0 ? void 0 : connectProperties.username) {            internalConnectOptions.username = connectProperties.username;        }    }    else {        internalConnectOptions.username = mqtt_shared_browser.buildFinalUsernameFromMetrics(aws_iot_metrics.create_metrics_mqtt5(clientConfig), connectProperties === null || connectProperties === void 0 ? void 0 : connectProperties.username);    }    if (!connectProperties) {        return;    }    if (connectProperties.clientId !== undefined) {        internalConnectOptions.clientId = connectProperties.clientId;    }    if (connectProperties.password !== undefined) {        internalConnectOptions.password = connectProperties.password;    }    if (connectProperties.sessionExpiryIntervalSeconds !== undefined) {        internalConnectOptions.sessionExpiryIntervalSeconds = connectProperties.sessionExpiryIntervalSeconds;    }    if (connectProperties.requestResponseInformation !== undefined) {        internalConnectOptions.requestResponseInformation = connectProperties.requestResponseInformation;    }    if (connectProperties.requestProblemInformation !== undefined) {        internalConnectOptions.requestProblemInformation = connectProperties.requestProblemInformation;    }    if (connectProperties.receiveMaximum !== undefined) {        internalConnectOptions.receiveMaximum = connectProperties.receiveMaximum;    }    if (connectProperties.maximumPacketSizeBytes !== undefined) {        internalConnectOptions.maximumPacketSizeBytes = connectProperties.maximumPacketSizeBytes;    }    if (connectProperties.willDelayIntervalSeconds !== undefined) {        internalConnectOptions.willDelayIntervalSeconds = connectProperties.willDelayIntervalSeconds;    }    if (connectProperties.will !== undefined) {        internalConnectOptions.will = connectProperties.will;    }    if (connectProperties.userProperties !== undefined) {        internalConnectOptions.userProperties = connectProperties.userProperties;    }}var DEFAULT_MQTT_PING_TIMEOUT_MS = 30 * 1000;var DEFAULT_CONNECT_TIMEOUT_MS = 10 * 1000;/** * Browser specific MQTT5 client implementation */var Mqtt5Client = /** @class */ (function (_super) {    __extends(Mqtt5Client, _super);    /**     * Client constructor     *     * @param config The configuration for this client     */    function Mqtt5Client(config) {        var _this = this;        var _a, _b, _c;        _this = _super.call(this) || this;        _this.config = config;        _this.connected = false;        _this.on_publish_received = function (event) {            var messageReceivedEvent = {                message: event.publish            };            mqtt_shared.queueAcknowledgeableEvent(_this, Mqtt5Client.MESSAGE_RECEIVED, messageReceivedEvent, "acknowledgementControl", event.acknowledgementControl);        };        if (!config) {            throw new error_1.CrtError("Mqtt5Client constructor: config not defined");        }        var internalConnectOptions = {            keepAliveIntervalSeconds: (_b = (_a = _this.config.connectProperties) === null || _a === void 0 ? void 0 : _a.keepAliveIntervalSeconds) !== null && _b !== void 0 ? _b : 1200,            resumeSessionPolicy: convertSessionBehaviorToSessionPolicy(_this.config.sessionBehavior),        };        buildInternalConnectOptions(internalConnectOptions, config, config.connectProperties);        var provider = undefined;        if (_this.config.websocketOptions) {            if (_this.config.websocketOptions.urlFactoryOptions.urlFactory == Mqtt5WebsocketUrlFactoryType.Sigv4) {                var sigv4Options = _this.config.websocketOptions.urlFactoryOptions;                provider = sigv4Options.credentialsProvider;            }        }        var thisConfig = _this.config;        var connectionFactory = function () {            var _this = this;            return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {                var conn;                return __generator(this, function (_a) {                    switch (_a.label) {                        case 0:                            if (!provider) return [3 /*break*/, 2];                            return [4 /*yield*/, provider.refreshCredentials()];                        case 1:                            _a.sent();                            _a.label = 2;                        case 2:                            conn = ws.create_mqtt5_websocket_stream(thisConfig);                            conn.on('error', function (err) {                                reject(err);                            });                            conn.on('connect', function () {                                resolve(conn);                            });                            return [2 /*return*/];                    }                });            }); });        };        var internalConfig = {            protocolVersion: mqtt_shared.ProtocolMode.Mqtt5,            offlineQueuePolicy: internal_mqtt_client.OfflineQueuePolicy.PreserveQos1PlusPublishes,            connectOptions: internalConnectOptions,            pingTimeoutMillis: DEFAULT_MQTT_PING_TIMEOUT_MS,            connectionFactory: connectionFactory,            connectTimeoutMillis: (_c = config.connectTimeoutMs) !== null && _c !== void 0 ? _c : DEFAULT_CONNECT_TIMEOUT_MS,            retryJitterMode: mqtt5.RetryJitterType.Default,        };        if (config.minReconnectDelayMs !== undefined) {            internalConfig.minReconnectDelayMs = config.minReconnectDelayMs;        }        if (config.maxReconnectDelayMs !== undefined) {            internalConfig.maxReconnectDelayMs = config.maxReconnectDelayMs;        }        if (config.minConnectedTimeToResetReconnectDelayMs !== undefined) {            internalConfig.resetConnectionFailureCountMillis = config.minConnectedTimeToResetReconnectDelayMs;        }        _this.internalClient = new internal_mqtt_client.Client(internalConfig);        _this.internalClient.on("connectionSuccess", _this.on_connection_success.bind(_this));        _this.internalClient.on("connectionFailure", _this.on_connection_failure.bind(_this));        _this.internalClient.on("disconnection", _this.on_disconnection.bind(_this));        _this.internalClient.on("publishReceived", _this.on_publish_received.bind(_this));        _this.internalClient.on("stopped", _this.on_stopped.bind(_this));        _this.internalClient.on("connecting", _this.on_connecting.bind(_this));        return _this;    }    /**     * Triggers cleanup of native resources associated with the MQTT5 client.  On the browser, the implementation is     * an empty function.     */    Mqtt5Client.prototype.close = function () { };    /**     * Notifies the MQTT5 client that you want it to maintain connectivity to the configured endpoint.     * The client will attempt to stay connected using the properties of the reconnect-related parameters     * in the mqtt5 client configuration.     *     * This is an asynchronous operation.     */    Mqtt5Client.prototype.start = function () {        this.internalClient.start();    };    /**     * Notifies the MQTT5 client that you want it to end connectivity to the configured endpoint, disconnecting any     * existing connection and halting reconnection attempts.     *     * This is an asynchronous operation.  Once the process completes, no further events will be emitted until the client     * has {@link start} invoked.  Invoking {@link start start()} after a {@link stop stop()} will always result in     * a new MQTT session.     *     * @param disconnectPacket (optional) properties of a DISCONNECT packet to send as part of the shutdown process     */    Mqtt5Client.prototype.stop = function (disconnectPacket) {        // maintain backwards comaptibility with previous implementation which let validation errors        // trump the stop request        if (disconnectPacket) {            disconnectPacket.type = mqtt5_packet.PacketType.Disconnect;            validate.validateInitialOutboundPacket(disconnectPacket, mqtt_shared.ProtocolMode.Mqtt5);        }        this.internalClient.stop(disconnectPacket);    };    /**     * Subscribe to one or more topic filters by queuing a SUBSCRIBE packet to be sent to the server.     *     * @param packet SUBSCRIBE packet to send to the server     * @returns a promise that will be rejected with an error or resolved with the SUBACK response     */    Mqtt5Client.prototype.subscribe = function (packet) {        return __awaiter(this, void 0, void 0, function () {            return __generator(this, function (_a) {                switch (_a.label) {                    case 0:                        if (!packet) {                            throw new error_1.CrtError("Invalid subscribe packet");                        }                        return [4 /*yield*/, this.internalClient.subscribe(packet)];                    case 1: return [2 /*return*/, _a.sent()];                }            });        });    };    /**     * Unsubscribe from one or more topic filters by queuing an UNSUBSCRIBE packet to be sent to the server.     *     * @param packet UNSUBSCRIBE packet to send to the server     * @returns a promise that will be rejected with an error or resolved with the UNSUBACK response     */    Mqtt5Client.prototype.unsubscribe = function (packet) {        return __awaiter(this, void 0, void 0, function () {            return __generator(this, function (_a) {                switch (_a.label) {                    case 0:                        if (!packet) {                            throw new error_1.CrtError("Invalid unsubscribe packet");                        }                        return [4 /*yield*/, this.internalClient.unsubscribe(packet)];                    case 1: return [2 /*return*/, _a.sent()];                }            });        });    };    /**     * Send a message to subscribing clients by queuing a PUBLISH packet to be sent to the server.     *     * @param packet PUBLISH packet to send to the server     * @returns a promise that will be rejected with an error or resolved with the PUBACK response (QoS 1), or     * undefined (QoS 0)     */    Mqtt5Client.prototype.publish = function (packet) {        return __awaiter(this, void 0, void 0, function () {            var publishResult;            return __generator(this, function (_a) {                switch (_a.label) {                    case 0:                        if (!packet) {                            throw new error_1.CrtError("Invalid publish packet");                        }                        return [4 /*yield*/, this.internalClient.publish(packet)];                    case 1:                        publishResult = _a.sent();                        switch (publishResult.type) {                            case client_1.PublishResultType.Qos1:                                return [2 /*return*/, publishResult.packet];                            default:                                return [2 /*return*/, undefined];                        }                        return [2 /*return*/];                }            });        });    };    /**     * Queries whether the client is currently connected     *     * @returns whether the client is currently connected     */    Mqtt5Client.prototype.isConnected = function () {        return this.connected;    };    Mqtt5Client.prototype.on = function (event, listener) {        _super.prototype.on.call(this, event, listener);        return this;    };    Mqtt5Client.prototype.on_connecting = function (event) {        var _this = this;        var attemptingConnectEvent = {};        setTimeout(function () {            _this.emit(Mqtt5Client.ATTEMPTING_CONNECT, attemptingConnectEvent);        }, 0);    };    Mqtt5Client.prototype.on_connection_success = function (event) {        var _this = this;        this.connected = true;        var settings = create_negotiated_settings(this.config, event.connack);        var connectionSuccessEvent = {            connack: event.connack,            settings: settings        };        setTimeout(function () {            _this.emit(Mqtt5Client.CONNECTION_SUCCESS, connectionSuccessEvent);        }, 0);    };    Mqtt5Client.prototype.on_connection_failure = function (event) {        var _this = this;        var connectionFailureEvent = {            error: event.error        };        if (event.connack) {            connectionFailureEvent.connack = event.connack;        }        setTimeout(function () {            _this.emit(Mqtt5Client.CONNECTION_FAILURE, connectionFailureEvent);        }, 0);    };    Mqtt5Client.prototype.on_disconnection = function (event) {        var _this = this;        this.connected = false;        var disconnectionEvent = {            error: event.error        };        if (event.disconnect) {            disconnectionEvent.disconnect = event.disconnect;        }        setTimeout(function () {            _this.emit(Mqtt5Client.DISCONNECTION, disconnectionEvent);        }, 0);    };    Mqtt5Client.prototype.on_stopped = function (event) {        var _this = this;        var stoppedEvent = {};        setTimeout(function () {            _this.emit(Mqtt5Client.STOPPED, stoppedEvent);        }, 0);    };    /**     * Event emitted when the client encounters a disruptive error condition.  Not currently used.     *     * Listener type: {@link ErrorEventListener}     *     * @event     */    Mqtt5Client.ERROR = 'error';    /**     * Event emitted when the client encounters a transient error event that will not disrupt promises based on     * lifecycle events.  Currently, mqtt-js client error events are relayed to this event.     *     * Listener type: {@link ErrorEventListener}     *     * @event     * @group Browser-only     */    Mqtt5Client.INFO = 'info';    /**     * Event emitted when an MQTT PUBLISH packet is received by the client.     *     * Listener type: {@link MessageReceivedEventListener}     *     * @event     */    Mqtt5Client.MESSAGE_RECEIVED = 'messageReceived';    /**     * Event emitted when the client begins a connection attempt.     *     * Listener type: {@link AttemptingConnectEventListener}     *     * @event     */    Mqtt5Client.ATTEMPTING_CONNECT = 'attemptingConnect';    /**     * Event emitted when the client successfully establishes an MQTT connection.  Only emitted after     * an {@link ATTEMPTING_CONNECT attemptingConnect} event.     *     * Listener type: {@link ConnectionSuccessEventListener}     *     * @event     */    Mqtt5Client.CONNECTION_SUCCESS = 'connectionSuccess';    /**     * Event emitted when the client fails to establish an MQTT connection.  Only emitted after     * an {@link ATTEMPTING_CONNECT attemptingConnect} event.     *     * Listener type: {@link ConnectionFailureEventListener}     *     * @event     */    Mqtt5Client.CONNECTION_FAILURE = 'connectionFailure';    /**     * Event emitted when the client's current connection is closed for any reason.  Only emitted after     * a {@link CONNECTION_SUCCESS connectionSuccess} event.     *     * Listener type: {@link DisconnectionEventListener}     *     * @event     */    Mqtt5Client.DISCONNECTION = 'disconnection';    /**     * Event emitted when the client finishes shutdown as a result of the user invoking {@link stop}.     *     * Listener type: {@link StoppedEventListener}     *     * @event     */    Mqtt5Client.STOPPED = 'stopped';    return Mqtt5Client;}(event_1.BufferedEventEmitter));exports.Mqtt5Client = Mqtt5Client;function create_negotiated_settings(config, connack) {    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w;    if (config == null || config == undefined) {        throw new error_1.CrtError("create_negotiated_settings: config not defined");    }    if (connack == null || connack == undefined) {        throw new error_1.CrtError("create_negotiated_settings: connack not defined");    }    return {        maximumQos: Math.min((_a = connack.maximumQos) !== null && _a !== void 0 ? _a : mqtt5_packet.QoS.ExactlyOnce, mqtt5_packet.QoS.AtLeastOnce),        sessionExpiryInterval: (_d = (_b = connack.sessionExpiryInterval) !== null && _b !== void 0 ? _b : (_c = config.connectProperties) === null || _c === void 0 ? void 0 : _c.sessionExpiryIntervalSeconds) !== null && _d !== void 0 ? _d : 0,        receiveMaximumFromServer: (_e = connack.receiveMaximum) !== null && _e !== void 0 ? _e : mqtt_shared.DEFAULT_RECEIVE_MAXIMUM,        maximumPacketSizeToServer: (_f = connack.maximumPacketSize) !== null && _f !== void 0 ? _f : mqtt_shared.MAXIMUM_PACKET_SIZE,        topicAliasMaximumToServer: Math.min((_h = (_g = config.topicAliasingOptions) === null || _g === void 0 ? void 0 : _g.outboundCacheMaxSize) !== null && _h !== void 0 ? _h : 0, (_j = connack.topicAliasMaximum) !== null && _j !== void 0 ? _j : 0),        topicAliasMaximumToClient: (_l = (_k = config.topicAliasingOptions) === null || _k === void 0 ? void 0 : _k.inboundCacheMaxSize) !== null && _l !== void 0 ? _l : 0,        serverKeepAlive: (_p = (_m = connack.serverKeepAlive) !== null && _m !== void 0 ? _m : (_o = config.connectProperties) === null || _o === void 0 ? void 0 : _o.keepAliveIntervalSeconds) !== null && _p !== void 0 ? _p : mqtt_shared.DEFAULT_KEEP_ALIVE,        retainAvailable: (_q = connack.retainAvailable) !== null && _q !== void 0 ? _q : true,        wildcardSubscriptionsAvailable: (_r = connack.wildcardSubscriptionsAvailable) !== null && _r !== void 0 ? _r : true,        subscriptionIdentifiersAvailable: (_s = connack.subscriptionIdentifiersAvailable) !== null && _s !== void 0 ? _s : true,        sharedSubscriptionsAvailable: (_t = connack.sharedSubscriptionsAvailable) !== null && _t !== void 0 ? _t : true,        rejoinedSession: connack.sessionPresent,        clientId: (_w = (_u = connack.assignedClientIdentifier) !== null && _u !== void 0 ? _u : (_v = config.connectProperties) === null || _v === void 0 ? void 0 : _v.clientId) !== null && _w !== void 0 ? _w : ""    };}//# sourceMappingURL=mqtt5.js.map