mqtt 5.0.0-beta.2 → 5.0.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,129 +1,126 @@
1
- 'use strict'
2
-
3
1
  const { Buffer } = require('buffer')
4
- const Transform = require('readable-stream').Transform
2
+ const { Transform } = require('readable-stream')
5
3
  const duplexify = require('duplexify')
6
4
 
7
- /* global FileReader */
8
5
  let my
9
6
  let proxy
10
7
  let stream
11
8
  let isInitialized = false
12
9
 
13
- function buildProxy () {
14
- const proxy = new Transform()
15
- proxy._write = function (chunk, encoding, next) {
16
- my.sendSocketMessage({
17
- data: chunk.buffer,
18
- success: function () {
19
- next()
20
- },
21
- fail: function () {
22
- next(new Error())
23
- }
24
- })
25
- }
26
- proxy._flush = function socketEnd (done) {
27
- my.closeSocket({
28
- success: function () {
29
- done()
30
- }
31
- })
32
- }
33
-
34
- return proxy
10
+ function buildProxy() {
11
+ const _proxy = new Transform()
12
+ _proxy._write = (chunk, encoding, next) => {
13
+ my.sendSocketMessage({
14
+ data: chunk.buffer,
15
+ success() {
16
+ next()
17
+ },
18
+ fail() {
19
+ next(new Error())
20
+ },
21
+ })
22
+ }
23
+ _proxy._flush = (done) => {
24
+ my.closeSocket({
25
+ success() {
26
+ done()
27
+ },
28
+ })
29
+ }
30
+
31
+ return _proxy
35
32
  }
36
33
 
37
- function setDefaultOpts (opts) {
38
- if (!opts.hostname) {
39
- opts.hostname = 'localhost'
40
- }
41
- if (!opts.path) {
42
- opts.path = '/'
43
- }
44
-
45
- if (!opts.wsOptions) {
46
- opts.wsOptions = {}
47
- }
34
+ function setDefaultOpts(opts) {
35
+ if (!opts.hostname) {
36
+ opts.hostname = 'localhost'
37
+ }
38
+ if (!opts.path) {
39
+ opts.path = '/'
40
+ }
41
+
42
+ if (!opts.wsOptions) {
43
+ opts.wsOptions = {}
44
+ }
48
45
  }
49
46
 
50
- function buildUrl (opts, client) {
51
- const protocol = opts.protocol === 'alis' ? 'wss' : 'ws'
52
- let url = protocol + '://' + opts.hostname + opts.path
53
- if (opts.port && opts.port !== 80 && opts.port !== 443) {
54
- url = protocol + '://' + opts.hostname + ':' + opts.port + opts.path
55
- }
56
- if (typeof (opts.transformWsUrl) === 'function') {
57
- url = opts.transformWsUrl(url, opts, client)
58
- }
59
- return url
47
+ function buildUrl(opts, client) {
48
+ const protocol = opts.protocol === 'alis' ? 'wss' : 'ws'
49
+ let url = `${protocol}://${opts.hostname}${opts.path}`
50
+ if (opts.port && opts.port !== 80 && opts.port !== 443) {
51
+ url = `${protocol}://${opts.hostname}:${opts.port}${opts.path}`
52
+ }
53
+ if (typeof opts.transformWsUrl === 'function') {
54
+ url = opts.transformWsUrl(url, opts, client)
55
+ }
56
+ return url
60
57
  }
61
58
 
62
- function bindEventHandler () {
63
- if (isInitialized) return
64
-
65
- isInitialized = true
66
-
67
- my.onSocketOpen(function () {
68
- stream.setReadable(proxy)
69
- stream.setWritable(proxy)
70
- stream.emit('connect')
71
- })
72
-
73
- my.onSocketMessage(function (res) {
74
- if (typeof res.data === 'string') {
75
- const buffer = Buffer.from(res.data, 'base64')
76
- proxy.push(buffer)
77
- } else {
78
- const reader = new FileReader()
79
- reader.addEventListener('load', function () {
80
- let data = reader.result
81
-
82
- if (data instanceof ArrayBuffer) data = Buffer.from(data)
83
- else data = Buffer.from(data, 'utf8')
84
- proxy.push(data)
85
- })
86
- reader.readAsArrayBuffer(res.data)
87
- }
88
- })
89
-
90
- my.onSocketClose(function () {
91
- stream.end()
92
- stream.destroy()
93
- })
94
-
95
- my.onSocketError(function (res) {
96
- stream.destroy(res)
97
- })
59
+ function bindEventHandler() {
60
+ if (isInitialized) return
61
+
62
+ isInitialized = true
63
+
64
+ my.onSocketOpen(() => {
65
+ stream.setReadable(proxy)
66
+ stream.setWritable(proxy)
67
+ stream.emit('connect')
68
+ })
69
+
70
+ my.onSocketMessage((res) => {
71
+ if (typeof res.data === 'string') {
72
+ const buffer = Buffer.from(res.data, 'base64')
73
+ proxy.push(buffer)
74
+ } else {
75
+ const reader = new FileReader()
76
+ reader.addEventListener('load', () => {
77
+ let data = reader.result
78
+
79
+ if (data instanceof ArrayBuffer) data = Buffer.from(data)
80
+ else data = Buffer.from(data, 'utf8')
81
+ proxy.push(data)
82
+ })
83
+ reader.readAsArrayBuffer(res.data)
84
+ }
85
+ })
86
+
87
+ my.onSocketClose(() => {
88
+ stream.end()
89
+ stream.destroy()
90
+ })
91
+
92
+ my.onSocketError((res) => {
93
+ stream.destroy(res)
94
+ })
98
95
  }
99
96
 
100
- function buildStream (client, opts) {
101
- opts.hostname = opts.hostname || opts.host
97
+ function buildStream(client, opts) {
98
+ opts.hostname = opts.hostname || opts.host
102
99
 
103
- if (!opts.hostname) {
104
- throw new Error('Could not determine host. Specify host manually.')
105
- }
100
+ if (!opts.hostname) {
101
+ throw new Error('Could not determine host. Specify host manually.')
102
+ }
106
103
 
107
- const websocketSubProtocol =
108
- (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
109
- ? 'mqttv3.1'
110
- : 'mqtt'
104
+ const websocketSubProtocol =
105
+ opts.protocolId === 'MQIsdp' && opts.protocolVersion === 3
106
+ ? 'mqttv3.1'
107
+ : 'mqtt'
111
108
 
112
- setDefaultOpts(opts)
109
+ setDefaultOpts(opts)
113
110
 
114
- const url = buildUrl(opts, client)
115
- my = opts.my
116
- my.connectSocket({
117
- url: url,
118
- protocols: websocketSubProtocol
119
- })
111
+ const url = buildUrl(opts, client)
112
+ my = opts.my
113
+ my.connectSocket({
114
+ url,
115
+ protocols: websocketSubProtocol,
116
+ })
120
117
 
121
- proxy = buildProxy()
122
- stream = duplexify.obj()
118
+ proxy = buildProxy()
119
+ stream = duplexify.obj()
123
120
 
124
- bindEventHandler()
121
+ bindEventHandler()
125
122
 
126
- return stream
123
+ return stream
127
124
  }
128
125
 
129
126
  module.exports = buildStream
@@ -1,28 +1,25 @@
1
- 'use strict'
2
-
1
+ const url = require('url')
3
2
  const MqttClient = require('../client')
4
3
  const Store = require('../store')
5
4
  const DefaultMessageIdProvider = require('../default-message-id-provider')
6
5
  const UniqueMessageIdProvider = require('../unique-message-id-provider')
7
- const IS_BROWSER = require('../is-browser').IS_BROWSER
8
- const url = require('url')
9
- const xtend = require('xtend')
6
+ const { IS_BROWSER } = require('../is-browser')
10
7
  const debug = require('debug')('mqttjs')
11
8
 
12
9
  const protocols = {}
13
10
 
14
11
  if (!IS_BROWSER) {
15
- protocols.mqtt = require('./tcp')
16
- protocols.tcp = require('./tcp')
17
- protocols.ssl = require('./tls')
18
- protocols.tls = require('./tls')
19
- protocols.mqtts = require('./tls')
12
+ protocols.mqtt = require('./tcp')
13
+ protocols.tcp = require('./tcp')
14
+ protocols.ssl = require('./tls')
15
+ protocols.tls = require('./tls')
16
+ protocols.mqtts = require('./tls')
20
17
  } else {
21
- protocols.wx = require('./wx')
22
- protocols.wxs = require('./wx')
18
+ protocols.wx = require('./wx')
19
+ protocols.wxs = require('./wx')
23
20
 
24
- protocols.ali = require('./ali')
25
- protocols.alis = require('./ali')
21
+ protocols.ali = require('./ali')
22
+ protocols.alis = require('./ali')
26
23
  }
27
24
 
28
25
  protocols.ws = require('./ws')
@@ -33,17 +30,17 @@ protocols.wss = require('./ws')
33
30
  *
34
31
  * @param {Object} [opts] option object
35
32
  */
36
- function parseAuthOptions (opts) {
37
- let matches
38
- if (opts.auth) {
39
- matches = opts.auth.match(/^(.+):(.+)$/)
40
- if (matches) {
41
- opts.username = matches[1]
42
- opts.password = matches[2]
43
- } else {
44
- opts.username = opts.auth
45
- }
46
- }
33
+ function parseAuthOptions(opts) {
34
+ let matches
35
+ if (opts.auth) {
36
+ matches = opts.auth.match(/^(.+):(.+)$/)
37
+ if (matches) {
38
+ opts.username = matches[1]
39
+ opts.password = matches[2]
40
+ } else {
41
+ opts.username = opts.auth
42
+ }
43
+ }
47
44
  }
48
45
 
49
46
  /**
@@ -52,113 +49,122 @@ function parseAuthOptions (opts) {
52
49
  * @param {String} [brokerUrl] - url of the broker, optional
53
50
  * @param {Object} opts - see MqttClient#constructor
54
51
  */
55
- function connect (brokerUrl, opts) {
56
- debug('connecting to an MQTT broker...')
57
- if ((typeof brokerUrl === 'object') && !opts) {
58
- opts = brokerUrl
59
- brokerUrl = null
60
- }
52
+ function connect(brokerUrl, opts) {
53
+ debug('connecting to an MQTT broker...')
54
+ if (typeof brokerUrl === 'object' && !opts) {
55
+ opts = brokerUrl
56
+ brokerUrl = null
57
+ }
61
58
 
62
- opts = opts || {}
59
+ opts = opts || {}
63
60
 
64
- if (brokerUrl) {
65
- // eslint-disable-next-line
61
+ if (brokerUrl) {
62
+ // eslint-disable-next-line
66
63
  const parsed = url.parse(brokerUrl, true)
67
- if (parsed.port != null) {
68
- parsed.port = Number(parsed.port)
69
- }
70
-
71
- opts = xtend(parsed, opts)
72
-
73
- if (opts.protocol === null) {
74
- throw new Error('Missing protocol')
75
- }
76
-
77
- opts.protocol = opts.protocol.replace(/:$/, '')
78
- }
79
-
80
- // merge in the auth options if supplied
81
- parseAuthOptions(opts)
82
-
83
- // support clientId passed in the query string of the url
84
- if (opts.query && typeof opts.query.clientId === 'string') {
85
- opts.clientId = opts.query.clientId
86
- }
87
-
88
- if (opts.cert && opts.key) {
89
- if (opts.protocol) {
90
- if (['mqtts', 'wss', 'wxs', 'alis'].indexOf(opts.protocol) === -1) {
91
- switch (opts.protocol) {
92
- case 'mqtt':
93
- opts.protocol = 'mqtts'
94
- break
95
- case 'ws':
96
- opts.protocol = 'wss'
97
- break
98
- case 'wx':
99
- opts.protocol = 'wxs'
100
- break
101
- case 'ali':
102
- opts.protocol = 'alis'
103
- break
104
- default:
105
- throw new Error('Unknown protocol for secure connection: "' + opts.protocol + '"!')
106
- }
107
- }
108
- } else {
109
- // A cert and key was provided, however no protocol was specified, so we will throw an error.
110
- throw new Error('Missing secure protocol key')
111
- }
112
- }
113
-
114
- if (!protocols[opts.protocol]) {
115
- const isSecure = ['mqtts', 'wss'].indexOf(opts.protocol) !== -1
116
- opts.protocol = [
117
- 'mqtt',
118
- 'mqtts',
119
- 'ws',
120
- 'wss',
121
- 'wx',
122
- 'wxs',
123
- 'ali',
124
- 'alis'
125
- ].filter(function (key, index) {
126
- if (isSecure && index % 2 === 0) {
127
- // Skip insecure protocols when requesting a secure one.
128
- return false
129
- }
130
- return (typeof protocols[key] === 'function')
131
- })[0]
132
- }
133
-
134
- if (opts.clean === false && !opts.clientId) {
135
- throw new Error('Missing clientId for unclean clients')
136
- }
137
-
138
- if (opts.protocol) {
139
- opts.defaultProtocol = opts.protocol
140
- }
141
-
142
- function wrapper (client) {
143
- if (opts.servers) {
144
- if (!client._reconnectCount || client._reconnectCount === opts.servers.length) {
145
- client._reconnectCount = 0
146
- }
147
-
148
- opts.host = opts.servers[client._reconnectCount].host
149
- opts.port = opts.servers[client._reconnectCount].port
150
- opts.protocol = (!opts.servers[client._reconnectCount].protocol ? opts.defaultProtocol : opts.servers[client._reconnectCount].protocol)
151
- opts.hostname = opts.host
152
-
153
- client._reconnectCount++
154
- }
155
-
156
- debug('calling streambuilder for', opts.protocol)
157
- return protocols[opts.protocol](client, opts)
158
- }
159
- const client = new MqttClient(wrapper, opts)
160
- client.on('error', function () { /* Automatically set up client error handling */ })
161
- return client
64
+ if (parsed.port != null) {
65
+ parsed.port = Number(parsed.port)
66
+ }
67
+
68
+ opts = { ...parsed, ...opts }
69
+
70
+ if (opts.protocol === null) {
71
+ throw new Error('Missing protocol')
72
+ }
73
+
74
+ opts.protocol = opts.protocol.replace(/:$/, '')
75
+ }
76
+
77
+ // merge in the auth options if supplied
78
+ parseAuthOptions(opts)
79
+
80
+ // support clientId passed in the query string of the url
81
+ if (opts.query && typeof opts.query.clientId === 'string') {
82
+ opts.clientId = opts.query.clientId
83
+ }
84
+
85
+ if (opts.cert && opts.key) {
86
+ if (opts.protocol) {
87
+ if (['mqtts', 'wss', 'wxs', 'alis'].indexOf(opts.protocol) === -1) {
88
+ switch (opts.protocol) {
89
+ case 'mqtt':
90
+ opts.protocol = 'mqtts'
91
+ break
92
+ case 'ws':
93
+ opts.protocol = 'wss'
94
+ break
95
+ case 'wx':
96
+ opts.protocol = 'wxs'
97
+ break
98
+ case 'ali':
99
+ opts.protocol = 'alis'
100
+ break
101
+ default:
102
+ throw new Error(
103
+ `Unknown protocol for secure connection: "${opts.protocol}"!`,
104
+ )
105
+ }
106
+ }
107
+ } else {
108
+ // A cert and key was provided, however no protocol was specified, so we will throw an error.
109
+ throw new Error('Missing secure protocol key')
110
+ }
111
+ }
112
+
113
+ if (!protocols[opts.protocol]) {
114
+ const isSecure = ['mqtts', 'wss'].indexOf(opts.protocol) !== -1
115
+ opts.protocol = [
116
+ 'mqtt',
117
+ 'mqtts',
118
+ 'ws',
119
+ 'wss',
120
+ 'wx',
121
+ 'wxs',
122
+ 'ali',
123
+ 'alis',
124
+ ].filter((key, index) => {
125
+ if (isSecure && index % 2 === 0) {
126
+ // Skip insecure protocols when requesting a secure one.
127
+ return false
128
+ }
129
+ return typeof protocols[key] === 'function'
130
+ })[0]
131
+ }
132
+
133
+ if (opts.clean === false && !opts.clientId) {
134
+ throw new Error('Missing clientId for unclean clients')
135
+ }
136
+
137
+ if (opts.protocol) {
138
+ opts.defaultProtocol = opts.protocol
139
+ }
140
+
141
+ function wrapper(client) {
142
+ if (opts.servers) {
143
+ if (
144
+ !client._reconnectCount ||
145
+ client._reconnectCount === opts.servers.length
146
+ ) {
147
+ client._reconnectCount = 0
148
+ }
149
+
150
+ opts.host = opts.servers[client._reconnectCount].host
151
+ opts.port = opts.servers[client._reconnectCount].port
152
+ opts.protocol = !opts.servers[client._reconnectCount].protocol
153
+ ? opts.defaultProtocol
154
+ : opts.servers[client._reconnectCount].protocol
155
+ opts.hostname = opts.host
156
+
157
+ client._reconnectCount++
158
+ }
159
+
160
+ debug('calling streambuilder for', opts.protocol)
161
+ return protocols[opts.protocol](client, opts)
162
+ }
163
+ const client = new MqttClient(wrapper, opts)
164
+ client.on('error', () => {
165
+ /* Automatically set up client error handling */
166
+ })
167
+ return client
162
168
  }
163
169
 
164
170
  module.exports = connect
@@ -1,4 +1,3 @@
1
- 'use strict'
2
1
  const net = require('net')
3
2
  const debug = require('debug')('mqttjs:tcp')
4
3
 
@@ -6,15 +5,15 @@ const debug = require('debug')('mqttjs:tcp')
6
5
  variables port and host can be removed since
7
6
  you have all required information in opts object
8
7
  */
9
- function streamBuilder (client, opts) {
10
- opts.port = opts.port || 1883
11
- opts.hostname = opts.hostname || opts.host || 'localhost'
8
+ function streamBuilder(client, opts) {
9
+ opts.port = opts.port || 1883
10
+ opts.hostname = opts.hostname || opts.host || 'localhost'
12
11
 
13
- const port = opts.port
14
- const host = opts.hostname
12
+ const { port } = opts
13
+ const host = opts.hostname
15
14
 
16
- debug('port %d and host %s', port, host)
17
- return net.createConnection(port, host)
15
+ debug('port %d and host %s', port, host)
16
+ return net.createConnection(port, host)
18
17
  }
19
18
 
20
19
  module.exports = streamBuilder
@@ -1,48 +1,52 @@
1
- 'use strict'
2
1
  const tls = require('tls')
3
2
  const net = require('net')
4
3
  const debug = require('debug')('mqttjs:tls')
5
4
 
6
- function buildBuilder (mqttClient, opts) {
7
- opts.port = opts.port || 8883
8
- opts.host = opts.hostname || opts.host || 'localhost'
9
-
10
- if (net.isIP(opts.host) === 0) {
11
- opts.servername = opts.host
12
- }
13
-
14
- opts.rejectUnauthorized = opts.rejectUnauthorized !== false
15
-
16
- delete opts.path
17
-
18
- debug('port %d host %s rejectUnauthorized %b', opts.port, opts.host, opts.rejectUnauthorized)
19
-
20
- const connection = tls.connect(opts)
21
- /* eslint no-use-before-define: [2, "nofunc"] */
22
- connection.on('secureConnect', function () {
23
- if (opts.rejectUnauthorized && !connection.authorized) {
24
- connection.emit('error', new Error('TLS not authorized'))
25
- } else {
26
- connection.removeListener('error', handleTLSerrors)
27
- }
28
- })
29
-
30
- function handleTLSerrors (err) {
31
- // How can I get verify this error is a tls error?
32
- if (opts.rejectUnauthorized) {
33
- mqttClient.emit('error', err)
34
- }
35
-
36
- // close this connection to match the behaviour of net
37
- // otherwise all we get is an error from the connection
38
- // and close event doesn't fire. This is a work around
39
- // to enable the reconnect code to work the same as with
40
- // net.createConnection
41
- connection.end()
42
- }
43
-
44
- connection.on('error', handleTLSerrors)
45
- return connection
5
+ function buildBuilder(mqttClient, opts) {
6
+ opts.port = opts.port || 8883
7
+ opts.host = opts.hostname || opts.host || 'localhost'
8
+
9
+ if (net.isIP(opts.host) === 0) {
10
+ opts.servername = opts.host
11
+ }
12
+
13
+ opts.rejectUnauthorized = opts.rejectUnauthorized !== false
14
+
15
+ delete opts.path
16
+
17
+ debug(
18
+ 'port %d host %s rejectUnauthorized %b',
19
+ opts.port,
20
+ opts.host,
21
+ opts.rejectUnauthorized,
22
+ )
23
+
24
+ const connection = tls.connect(opts)
25
+ /* eslint no-use-before-define: [2, "nofunc"] */
26
+ connection.on('secureConnect', () => {
27
+ if (opts.rejectUnauthorized && !connection.authorized) {
28
+ connection.emit('error', new Error('TLS not authorized'))
29
+ } else {
30
+ connection.removeListener('error', handleTLSerrors)
31
+ }
32
+ })
33
+
34
+ function handleTLSerrors(err) {
35
+ // How can I get verify this error is a tls error?
36
+ if (opts.rejectUnauthorized) {
37
+ mqttClient.emit('error', err)
38
+ }
39
+
40
+ // close this connection to match the behaviour of net
41
+ // otherwise all we get is an error from the connection
42
+ // and close event doesn't fire. This is a work around
43
+ // to enable the reconnect code to work the same as with
44
+ // net.createConnection
45
+ connection.end()
46
+ }
47
+
48
+ connection.on('error', handleTLSerrors)
49
+ return connection
46
50
  }
47
51
 
48
52
  module.exports = buildBuilder