chenyc
2025-12-09 545c24c6a711d71b65f3d4e8122fee3837fb1edc
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
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.streamBuilder = exports.browserStreamBuilder = void 0;
const buffer_1 = require("buffer");
const ws_1 = __importDefault(require("ws"));
const debug_1 = __importDefault(require("debug"));
const readable_stream_1 = require("readable-stream");
const is_browser_1 = __importDefault(require("../is-browser"));
const BufferedDuplex_1 = require("../BufferedDuplex");
const debug = (0, debug_1.default)('mqttjs:ws');
const WSS_OPTIONS = [
    'rejectUnauthorized',
    'ca',
    'cert',
    'key',
    'pfx',
    'passphrase',
];
function buildUrl(opts, client) {
    let url = `${opts.protocol}://${opts.hostname}:${opts.port}${opts.path}`;
    if (typeof opts.transformWsUrl === 'function') {
        url = opts.transformWsUrl(url, opts, client);
    }
    return url;
}
function setDefaultOpts(opts) {
    const options = opts;
    if (!opts.port) {
        if (opts.protocol === 'wss') {
            options.port = 443;
        }
        else {
            options.port = 80;
        }
    }
    if (!opts.path) {
        options.path = '/';
    }
    if (!opts.wsOptions) {
        options.wsOptions = {};
    }
    if (!is_browser_1.default && !opts.forceNativeWebSocket && opts.protocol === 'wss') {
        WSS_OPTIONS.forEach((prop) => {
            if (Object.prototype.hasOwnProperty.call(opts, prop) &&
                !Object.prototype.hasOwnProperty.call(opts.wsOptions, prop)) {
                options.wsOptions[prop] = opts[prop];
            }
        });
    }
    return options;
}
function setDefaultBrowserOpts(opts) {
    const options = setDefaultOpts(opts);
    if (!options.hostname) {
        options.hostname = options.host;
    }
    if (!options.hostname) {
        if (typeof document === 'undefined') {
            throw new Error('Could not determine host. Specify host manually.');
        }
        const parsed = new URL(document.URL);
        options.hostname = parsed.hostname;
        if (!options.port) {
            options.port = Number(parsed.port);
        }
    }
    if (options.objectMode === undefined) {
        options.objectMode = !(options.binary === true || options.binary === undefined);
    }
    return options;
}
function createWebSocket(client, url, opts) {
    debug('createWebSocket');
    debug(`protocol: ${opts.protocolId} ${opts.protocolVersion}`);
    const websocketSubProtocol = opts.protocolId === 'MQIsdp' && opts.protocolVersion === 3
        ? 'mqttv3.1'
        : 'mqtt';
    debug(`creating new Websocket for url: ${url} and protocol: ${websocketSubProtocol}`);
    let socket;
    if (opts.createWebsocket) {
        socket = opts.createWebsocket(url, [websocketSubProtocol], opts);
    }
    else {
        socket = new ws_1.default(url, [websocketSubProtocol], opts.wsOptions);
    }
    return socket;
}
function createBrowserWebSocket(client, opts) {
    const websocketSubProtocol = opts.protocolId === 'MQIsdp' && opts.protocolVersion === 3
        ? 'mqttv3.1'
        : 'mqtt';
    const url = buildUrl(opts, client);
    let socket;
    if (opts.createWebsocket) {
        socket = opts.createWebsocket(url, [websocketSubProtocol], opts);
    }
    else {
        socket = new WebSocket(url, [websocketSubProtocol]);
    }
    socket.binaryType = 'arraybuffer';
    return socket;
}
const streamBuilder = (client, opts) => {
    debug('streamBuilder');
    const options = setDefaultOpts(opts);
    options.hostname = options.hostname || options.host || 'localhost';
    const url = buildUrl(options, client);
    const socket = createWebSocket(client, url, options);
    const webSocketStream = ws_1.default.createWebSocketStream(socket, options.wsOptions);
    webSocketStream['url'] = url;
    socket.on('close', () => {
        webSocketStream.destroy();
    });
    return webSocketStream;
};
exports.streamBuilder = streamBuilder;
const browserStreamBuilder = (client, opts) => {
    debug('browserStreamBuilder');
    let stream;
    const options = setDefaultBrowserOpts(opts);
    const bufferSize = options.browserBufferSize || 1024 * 512;
    const bufferTimeout = opts.browserBufferTimeout || 1000;
    const coerceToBuffer = !opts.objectMode;
    const socket = createBrowserWebSocket(client, opts);
    const proxy = buildProxy(opts, socketWriteBrowser, socketEndBrowser);
    if (!opts.objectMode) {
        proxy._writev = BufferedDuplex_1.writev.bind(proxy);
    }
    proxy.on('close', () => {
        socket.close();
    });
    const eventListenerSupport = typeof socket.addEventListener !== 'undefined';
    if (socket.readyState === socket.OPEN) {
        stream = proxy;
        stream.socket = socket;
    }
    else {
        stream = new BufferedDuplex_1.BufferedDuplex(opts, proxy, socket);
        if (eventListenerSupport) {
            socket.addEventListener('open', onOpen);
        }
        else {
            socket.onopen = onOpen;
        }
    }
    if (eventListenerSupport) {
        socket.addEventListener('close', onClose);
        socket.addEventListener('error', onError);
        socket.addEventListener('message', onMessage);
    }
    else {
        socket.onclose = onClose;
        socket.onerror = onError;
        socket.onmessage = onMessage;
    }
    function buildProxy(pOptions, socketWrite, socketEnd) {
        const _proxy = new readable_stream_1.Transform({
            objectMode: pOptions.objectMode,
        });
        _proxy._write = socketWrite;
        _proxy._flush = socketEnd;
        return _proxy;
    }
    function onOpen() {
        debug('WebSocket onOpen');
        if (stream instanceof BufferedDuplex_1.BufferedDuplex) {
            stream.socketReady();
        }
    }
    function onClose(event) {
        debug('WebSocket onClose', event);
        stream.end();
        stream.destroy();
    }
    function onError(err) {
        debug('WebSocket onError', err);
        const error = new Error('WebSocket error');
        error['event'] = err;
        stream.destroy(error);
    }
    async function onMessage(event) {
        if (!proxy || !proxy.readable || !proxy.writable) {
            return;
        }
        let { data } = event;
        if (data instanceof ArrayBuffer)
            data = buffer_1.Buffer.from(data);
        else if (data instanceof Blob)
            data = buffer_1.Buffer.from(await new Response(data).arrayBuffer());
        else
            data = buffer_1.Buffer.from(data, 'utf8');
        proxy.push(data);
    }
    function socketWriteBrowser(chunk, enc, next) {
        if (socket.bufferedAmount > bufferSize) {
            setTimeout(socketWriteBrowser, bufferTimeout, chunk, enc, next);
            return;
        }
        if (coerceToBuffer && typeof chunk === 'string') {
            chunk = buffer_1.Buffer.from(chunk, 'utf8');
        }
        try {
            socket.send(chunk);
        }
        catch (err) {
            return next(err);
        }
        next();
    }
    function socketEndBrowser(done) {
        socket.close();
        done();
    }
    return stream;
};
exports.browserStreamBuilder = browserStreamBuilder;
//# sourceMappingURL=ws.js.map