UNPKG

2.19 kBJavaScriptView Raw
1'use strict'
2
3var websocket = require('websocket-stream')
4var urlModule = require('url')
5var WSS_OPTIONS = [
6 'rejectUnauthorized',
7 'ca',
8 'cert',
9 'key',
10 'pfx',
11 'passphrase'
12]
13var IS_BROWSER = process.title === 'browser'
14
15function buildUrl (opts, client) {
16 var url = opts.protocol + '://' + opts.hostname + ':' + opts.port + opts.path
17 if (typeof (opts.transformWsUrl) === 'function') {
18 url = opts.transformWsUrl(url, opts, client)
19 }
20 return url
21}
22
23function setDefaultOpts (opts) {
24 if (!opts.hostname) {
25 opts.hostname = 'localhost'
26 }
27 if (!opts.port) {
28 if (opts.protocol === 'wss') {
29 opts.port = 443
30 } else {
31 opts.port = 80
32 }
33 }
34 if (!opts.path) {
35 opts.path = '/'
36 }
37
38 if (!opts.wsOptions) {
39 opts.wsOptions = {}
40 }
41 if (!IS_BROWSER && opts.protocol === 'wss') {
42 // Add cert/key/ca etc options
43 WSS_OPTIONS.forEach(function (prop) {
44 if (opts.hasOwnProperty(prop) && !opts.wsOptions.hasOwnProperty(prop)) {
45 opts.wsOptions[prop] = opts[prop]
46 }
47 })
48 }
49}
50
51function createWebSocket (client, opts) {
52 var websocketSubProtocol =
53 (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
54 ? 'mqttv3.1'
55 : 'mqtt'
56
57 setDefaultOpts(opts)
58 var url = buildUrl(opts, client)
59 return websocket(url, [websocketSubProtocol], opts.wsOptions)
60}
61
62function buildBuilder (client, opts) {
63 return createWebSocket(client, opts)
64}
65
66function buildBuilderBrowser (client, opts) {
67 if (!opts.hostname) {
68 opts.hostname = opts.host
69 }
70
71 if (!opts.hostname) {
72 // Throwing an error in a Web Worker if no `hostname` is given, because we
73 // can not determine the `hostname` automatically. If connecting to
74 // localhost, please supply the `hostname` as an argument.
75 if (typeof (document) === 'undefined') {
76 throw new Error('Could not determine host. Specify host manually.')
77 }
78 var parsed = urlModule.parse(document.URL)
79 opts.hostname = parsed.hostname
80
81 if (!opts.port) {
82 opts.port = parsed.port
83 }
84 }
85 return createWebSocket(client, opts)
86}
87
88if (IS_BROWSER) {
89 module.exports = buildBuilderBrowser
90} else {
91 module.exports = buildBuilder
92}