mqtt 5.0.0-beta.3 → 5.0.0

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.
Files changed (127) hide show
  1. package/README.md +43 -4
  2. package/build/package.json +162 -0
  3. package/build/src/bin/mqtt.d.ts +2 -0
  4. package/build/src/bin/mqtt.js +27 -0
  5. package/build/src/bin/mqtt.js.map +1 -0
  6. package/build/src/bin/pub.d.ts +2 -0
  7. package/build/src/bin/pub.js +146 -0
  8. package/build/src/bin/pub.js.map +1 -0
  9. package/build/src/bin/sub.d.ts +2 -0
  10. package/build/src/bin/sub.js +121 -0
  11. package/build/src/bin/sub.js.map +1 -0
  12. package/build/src/lib/TypedEmitter.d.ts +11 -0
  13. package/build/src/lib/TypedEmitter.js +13 -0
  14. package/build/src/lib/TypedEmitter.js.map +1 -0
  15. package/build/src/lib/client.d.ts +220 -0
  16. package/build/src/lib/client.js +1204 -0
  17. package/build/src/lib/client.js.map +1 -0
  18. package/build/src/lib/connect/ali.d.ts +3 -0
  19. package/build/src/lib/connect/ali.js +113 -0
  20. package/build/src/lib/connect/ali.js.map +1 -0
  21. package/build/src/lib/connect/index.d.ts +9 -0
  22. package/build/src/lib/connect/index.js +169 -0
  23. package/build/src/lib/connect/index.js.map +1 -0
  24. package/build/src/lib/connect/tcp.d.ts +3 -0
  25. package/build/src/lib/connect/tcp.js +18 -0
  26. package/build/src/lib/connect/tcp.js.map +1 -0
  27. package/build/src/lib/connect/tls.d.ts +3 -0
  28. package/build/src/lib/connect/tls.js +38 -0
  29. package/build/src/lib/connect/tls.js.map +1 -0
  30. package/build/src/lib/connect/ws.d.ts +3 -0
  31. package/build/src/lib/connect/ws.js +212 -0
  32. package/build/src/lib/connect/ws.js.map +1 -0
  33. package/build/src/lib/connect/wx.d.ts +3 -0
  34. package/build/src/lib/connect/wx.js +117 -0
  35. package/build/src/lib/connect/wx.js.map +1 -0
  36. package/build/src/lib/default-message-id-provider.d.ts +16 -0
  37. package/build/src/lib/default-message-id-provider.js +24 -0
  38. package/build/src/lib/default-message-id-provider.js.map +1 -0
  39. package/build/src/lib/handlers/ack.d.ts +48 -0
  40. package/build/src/lib/handlers/ack.js +129 -0
  41. package/build/src/lib/handlers/ack.js.map +1 -0
  42. package/build/src/lib/handlers/auth.d.ts +3 -0
  43. package/build/src/lib/handlers/auth.js +30 -0
  44. package/build/src/lib/handlers/auth.js.map +1 -0
  45. package/build/src/lib/handlers/connack.d.ts +3 -0
  46. package/build/src/lib/handlers/connack.js +48 -0
  47. package/build/src/lib/handlers/connack.js.map +1 -0
  48. package/build/src/lib/handlers/index.d.ts +3 -0
  49. package/build/src/lib/handlers/index.js +64 -0
  50. package/build/src/lib/handlers/index.js.map +1 -0
  51. package/build/src/lib/handlers/publish.d.ts +3 -0
  52. package/build/src/lib/handlers/publish.js +106 -0
  53. package/build/src/lib/handlers/publish.js.map +1 -0
  54. package/build/src/lib/handlers/pubrel.d.ts +3 -0
  55. package/build/src/lib/handlers/pubrel.js +25 -0
  56. package/build/src/lib/handlers/pubrel.js.map +1 -0
  57. package/build/src/lib/is-browser.d.ts +2 -0
  58. package/build/src/lib/is-browser.js +8 -0
  59. package/build/src/lib/is-browser.js.map +1 -0
  60. package/build/src/lib/shared.d.ts +18 -0
  61. package/build/src/lib/shared.js +35 -0
  62. package/build/src/lib/shared.js.map +1 -0
  63. package/build/src/lib/store.d.ts +24 -0
  64. package/build/src/lib/store.js +80 -0
  65. package/build/src/lib/store.js.map +1 -0
  66. package/build/src/lib/topic-alias-recv.d.ts +9 -0
  67. package/build/src/lib/topic-alias-recv.js +24 -0
  68. package/build/src/lib/topic-alias-recv.js.map +1 -0
  69. package/build/src/lib/topic-alias-send.d.ts +13 -0
  70. package/build/src/lib/topic-alias-send.js +56 -0
  71. package/build/src/lib/topic-alias-send.js.map +1 -0
  72. package/build/src/lib/unique-message-id-provider.d.ts +11 -0
  73. package/build/src/lib/unique-message-id-provider.js +26 -0
  74. package/build/src/lib/unique-message-id-provider.js.map +1 -0
  75. package/build/src/lib/validations.d.ts +2 -0
  76. package/build/src/lib/validations.js +32 -0
  77. package/build/src/lib/validations.js.map +1 -0
  78. package/build/src/mqtt.d.ts +10 -0
  79. package/build/src/mqtt.js +49 -0
  80. package/build/src/mqtt.js.map +1 -0
  81. package/build/tsconfig.build.tsbuildinfo +1 -0
  82. package/dist/mqtt.js +2726 -3493
  83. package/dist/mqtt.min.js +4 -4
  84. package/doc/subscribe.txt +1 -1
  85. package/package.json +49 -29
  86. package/{bin/mqtt.js → src/bin/mqtt.ts} +11 -6
  87. package/src/bin/pub.ts +171 -0
  88. package/src/bin/sub.ts +146 -0
  89. package/src/lib/TypedEmitter.ts +45 -0
  90. package/{lib/client.js → src/lib/client.ts} +895 -252
  91. package/{lib/connect/ali.js → src/lib/connect/ali.ts} +13 -11
  92. package/src/lib/connect/index.ts +241 -0
  93. package/{lib/connect/tcp.js → src/lib/connect/tcp.ts} +8 -4
  94. package/{lib/connect/tls.js → src/lib/connect/tls.ts} +10 -8
  95. package/{lib/connect/ws.js → src/lib/connect/ws.ts} +52 -36
  96. package/{lib/connect/wx.js → src/lib/connect/wx.ts} +18 -9
  97. package/src/lib/default-message-id-provider.ts +99 -0
  98. package/{lib/handlers/ack.js → src/lib/handlers/ack.ts} +17 -19
  99. package/src/lib/handlers/auth.ts +44 -0
  100. package/{lib/handlers/connack.js → src/lib/handlers/connack.ts} +15 -11
  101. package/{lib/handlers/index.js → src/lib/handlers/index.ts} +8 -7
  102. package/{lib/handlers/publish.js → src/lib/handlers/publish.ts} +73 -57
  103. package/src/lib/handlers/pubrel.ts +27 -0
  104. package/{lib/is-browser.js → src/lib/is-browser.ts} +5 -4
  105. package/src/lib/shared.ts +73 -0
  106. package/{lib/store.js → src/lib/store.ts} +61 -16
  107. package/{lib/topic-alias-recv.js → src/lib/topic-alias-recv.ts} +10 -6
  108. package/{lib/topic-alias-send.js → src/lib/topic-alias-send.ts} +19 -11
  109. package/{lib/unique-message-id-provider.js → src/lib/unique-message-id-provider.ts} +10 -7
  110. package/{lib/validations.js → src/lib/validations.ts} +2 -6
  111. package/src/mqtt.ts +26 -0
  112. package/bin/pub.js +0 -159
  113. package/bin/sub.js +0 -141
  114. package/lib/connect/index.js +0 -175
  115. package/lib/default-message-id-provider.js +0 -63
  116. package/lib/handlers/auth.js +0 -34
  117. package/lib/handlers/pubrel.js +0 -24
  118. package/mqtt.js +0 -21
  119. package/types/index.d.ts +0 -30
  120. package/types/lib/client-options.d.ts +0 -224
  121. package/types/lib/client.d.ts +0 -273
  122. package/types/lib/connect/index.d.ts +0 -19
  123. package/types/lib/default-message-id-provider.d.ts +0 -49
  124. package/types/lib/message-id-provider.d.ts +0 -40
  125. package/types/lib/store-options.d.ts +0 -6
  126. package/types/lib/store.d.ts +0 -46
  127. package/types/lib/unique-message-id-provider.d.ts +0 -48
@@ -1,10 +1,12 @@
1
- const { Buffer } = require('buffer')
2
- const { Transform } = require('readable-stream')
3
- const duplexify = require('duplexify')
4
-
5
- let my
6
- let proxy
7
- let stream
1
+ import { Buffer } from 'buffer'
2
+ import { Transform } from 'readable-stream'
3
+ import duplexify, { Duplexify } from 'duplexify'
4
+ import { StreamBuilder } from '../shared'
5
+ import MqttClient, { IClientOptions } from '../client'
6
+
7
+ let my: any
8
+ let proxy: Transform
9
+ let stream: Duplexify
8
10
  let isInitialized = false
9
11
 
10
12
  function buildProxy() {
@@ -31,7 +33,7 @@ function buildProxy() {
31
33
  return _proxy
32
34
  }
33
35
 
34
- function setDefaultOpts(opts) {
36
+ function setDefaultOpts(opts: IClientOptions) {
35
37
  if (!opts.hostname) {
36
38
  opts.hostname = 'localhost'
37
39
  }
@@ -44,7 +46,7 @@ function setDefaultOpts(opts) {
44
46
  }
45
47
  }
46
48
 
47
- function buildUrl(opts, client) {
49
+ function buildUrl(opts: IClientOptions, client: MqttClient) {
48
50
  const protocol = opts.protocol === 'alis' ? 'wss' : 'ws'
49
51
  let url = `${protocol}://${opts.hostname}${opts.path}`
50
52
  if (opts.port && opts.port !== 80 && opts.port !== 443) {
@@ -94,7 +96,7 @@ function bindEventHandler() {
94
96
  })
95
97
  }
96
98
 
97
- function buildStream(client, opts) {
99
+ const buildStream: StreamBuilder = (client, opts) => {
98
100
  opts.hostname = opts.hostname || opts.host
99
101
 
100
102
  if (!opts.hostname) {
@@ -123,4 +125,4 @@ function buildStream(client, opts) {
123
125
  return stream
124
126
  }
125
127
 
126
- module.exports = buildStream
128
+ export default buildStream
@@ -0,0 +1,241 @@
1
+ /* eslint-disable @typescript-eslint/no-var-requires */
2
+ import _debug from 'debug'
3
+ import url from 'url'
4
+ import MqttClient, {
5
+ IClientOptions,
6
+ MqttClientEventCallbacks,
7
+ MqttProtocol,
8
+ } from '../client'
9
+ import IS_BROWSER from '../is-browser'
10
+ import { StreamBuilder } from '../shared'
11
+
12
+ const debug = _debug('mqttjs')
13
+
14
+ const protocols: Record<string, StreamBuilder> = {}
15
+
16
+ if (!IS_BROWSER) {
17
+ protocols.mqtt = require('./tcp').default
18
+ protocols.tcp = require('./tcp').default
19
+ protocols.ssl = require('./tls').default
20
+ protocols.tls = protocols.ssl
21
+ protocols.mqtts = require('./tls').default
22
+ } else {
23
+ protocols.wx = require('./wx').default
24
+ protocols.wxs = require('./wx').default
25
+
26
+ protocols.ali = require('./ali').default
27
+ protocols.alis = require('./ali').default
28
+ }
29
+
30
+ protocols.ws = require('./ws').default
31
+ protocols.wss = require('./ws').default
32
+
33
+ /**
34
+ * Parse the auth attribute and merge username and password in the options object.
35
+ *
36
+ * @param {Object} [opts] option object
37
+ */
38
+ function parseAuthOptions(opts: IClientOptions) {
39
+ let matches: RegExpMatchArray | null
40
+ if (opts.auth) {
41
+ matches = opts.auth.match(/^(.+):(.+)$/)
42
+ if (matches) {
43
+ opts.username = matches[1]
44
+ opts.password = matches[2]
45
+ } else {
46
+ opts.username = opts.auth
47
+ }
48
+ }
49
+ }
50
+
51
+ /**
52
+ * connect - connect to an MQTT broker.
53
+ */
54
+ function connect(brokerUrl: string): MqttClient
55
+ function connect(opts: IClientOptions): MqttClient
56
+ function connect(brokerUrl: string, opts?: IClientOptions): MqttClient
57
+ function connect(
58
+ brokerUrl: string | IClientOptions,
59
+ opts?: IClientOptions,
60
+ ): MqttClient {
61
+ debug('connecting to an MQTT broker...')
62
+ if (typeof brokerUrl === 'object' && !opts) {
63
+ opts = brokerUrl
64
+ brokerUrl = ''
65
+ }
66
+
67
+ opts = opts || {}
68
+
69
+ if (brokerUrl && typeof brokerUrl === 'string') {
70
+ // eslint-disable-next-line
71
+ const parsed = url.parse(brokerUrl, true)
72
+ if (parsed.port != null) {
73
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
74
+ // @ts-ignore
75
+ parsed.port = Number(parsed.port)
76
+ }
77
+
78
+ opts = { ...parsed, ...opts } as IClientOptions
79
+
80
+ if (opts.protocol === null) {
81
+ throw new Error('Missing protocol')
82
+ }
83
+
84
+ opts.protocol = opts.protocol.replace(/:$/, '') as MqttProtocol
85
+ }
86
+
87
+ // merge in the auth options if supplied
88
+ parseAuthOptions(opts)
89
+
90
+ // support clientId passed in the query string of the url
91
+ if (opts.query && typeof opts.query.clientId === 'string') {
92
+ opts.clientId = opts.query.clientId
93
+ }
94
+
95
+ if (opts.cert && opts.key) {
96
+ if (opts.protocol) {
97
+ if (['mqtts', 'wss', 'wxs', 'alis'].indexOf(opts.protocol) === -1) {
98
+ switch (opts.protocol) {
99
+ case 'mqtt':
100
+ opts.protocol = 'mqtts'
101
+ break
102
+ case 'ws':
103
+ opts.protocol = 'wss'
104
+ break
105
+ case 'wx':
106
+ opts.protocol = 'wxs'
107
+ break
108
+ case 'ali':
109
+ opts.protocol = 'alis'
110
+ break
111
+ default:
112
+ throw new Error(
113
+ `Unknown protocol for secure connection: "${opts.protocol}"!`,
114
+ )
115
+ }
116
+ }
117
+ } else {
118
+ // A cert and key was provided, however no protocol was specified, so we will throw an error.
119
+ throw new Error('Missing secure protocol key')
120
+ }
121
+ }
122
+
123
+ if (!protocols[opts.protocol]) {
124
+ const isSecure = ['mqtts', 'wss'].indexOf(opts.protocol) !== -1
125
+ opts.protocol = [
126
+ 'mqtt',
127
+ 'mqtts',
128
+ 'ws',
129
+ 'wss',
130
+ 'wx',
131
+ 'wxs',
132
+ 'ali',
133
+ 'alis',
134
+ ].filter((key, index) => {
135
+ if (isSecure && index % 2 === 0) {
136
+ // Skip insecure protocols when requesting a secure one.
137
+ return false
138
+ }
139
+ return typeof protocols[key] === 'function'
140
+ })[0] as MqttProtocol
141
+ }
142
+
143
+ if (opts.clean === false && !opts.clientId) {
144
+ throw new Error('Missing clientId for unclean clients')
145
+ }
146
+
147
+ if (opts.protocol) {
148
+ opts.defaultProtocol = opts.protocol
149
+ }
150
+
151
+ function wrapper(client: MqttClient) {
152
+ if (opts.servers) {
153
+ if (
154
+ !client._reconnectCount ||
155
+ client._reconnectCount === opts.servers.length
156
+ ) {
157
+ client._reconnectCount = 0
158
+ }
159
+
160
+ opts.host = opts.servers[client._reconnectCount].host
161
+ opts.port = opts.servers[client._reconnectCount].port
162
+ opts.protocol = !opts.servers[client._reconnectCount].protocol
163
+ ? opts.defaultProtocol
164
+ : opts.servers[client._reconnectCount].protocol
165
+ opts.hostname = opts.host
166
+
167
+ client._reconnectCount++
168
+ }
169
+
170
+ debug('calling streambuilder for', opts.protocol)
171
+ return protocols[opts.protocol](client, opts)
172
+ }
173
+ const client = new MqttClient(wrapper, opts)
174
+ client.on('error', () => {
175
+ /* Automatically set up client error handling */
176
+ })
177
+
178
+ return client
179
+ }
180
+
181
+ function connectAsync(brokerUrl: string): Promise<MqttClient>
182
+ function connectAsync(opts: IClientOptions): Promise<MqttClient>
183
+ function connectAsync(
184
+ brokerUrl: string,
185
+ opts?: IClientOptions,
186
+ ): Promise<MqttClient>
187
+ function connectAsync(
188
+ brokerUrl: string | IClientOptions,
189
+ opts?: IClientOptions,
190
+ allowRetries = true,
191
+ ): Promise<MqttClient> {
192
+ return new Promise((resolve, reject) => {
193
+ const client = connect(brokerUrl as string, opts)
194
+
195
+ const promiseResolutionListeners: Partial<MqttClientEventCallbacks> = {
196
+ connect: (connack) => {
197
+ removePromiseResolutionListeners()
198
+ resolve(client) // Resolve on connect
199
+ },
200
+ end: () => {
201
+ removePromiseResolutionListeners()
202
+ resolve(client) // Resolve on end
203
+ },
204
+ error: (err) => {
205
+ removePromiseResolutionListeners()
206
+ client.end()
207
+ reject(err) // Reject on error
208
+ },
209
+ }
210
+
211
+ // If retries are not allowed, reject on close
212
+ if (allowRetries === false) {
213
+ promiseResolutionListeners.close = () => {
214
+ promiseResolutionListeners.error(
215
+ new Error("Couldn't connect to server"),
216
+ )
217
+ }
218
+ }
219
+
220
+ // Remove listeners added to client by this promise
221
+ function removePromiseResolutionListeners() {
222
+ Object.keys(promiseResolutionListeners).forEach((eventName) => {
223
+ client.off(
224
+ eventName as keyof MqttClientEventCallbacks,
225
+ promiseResolutionListeners[eventName],
226
+ )
227
+ })
228
+ }
229
+
230
+ // Add listeners to client
231
+ Object.keys(promiseResolutionListeners).forEach((eventName) => {
232
+ client.on(
233
+ eventName as keyof MqttClientEventCallbacks,
234
+ promiseResolutionListeners[eventName],
235
+ )
236
+ })
237
+ })
238
+ }
239
+
240
+ export default connect
241
+ export { connectAsync }
@@ -1,11 +1,15 @@
1
- const net = require('net')
2
- const debug = require('debug')('mqttjs:tcp')
1
+ import { StreamBuilder } from '../shared'
3
2
 
3
+ import net from 'net'
4
+ import _debug from 'debug'
5
+ import { Duplex } from 'readable-stream'
6
+
7
+ const debug = _debug('mqttjs:tcp')
4
8
  /*
5
9
  variables port and host can be removed since
6
10
  you have all required information in opts object
7
11
  */
8
- function streamBuilder(client, opts) {
12
+ const buildStream: StreamBuilder = (client, opts) => {
9
13
  opts.port = opts.port || 1883
10
14
  opts.hostname = opts.hostname || opts.host || 'localhost'
11
15
 
@@ -16,4 +20,4 @@ function streamBuilder(client, opts) {
16
20
  return net.createConnection(port, host)
17
21
  }
18
22
 
19
- module.exports = streamBuilder
23
+ export default buildStream
@@ -1,8 +1,11 @@
1
- const tls = require('tls')
2
- const net = require('net')
3
- const debug = require('debug')('mqttjs:tls')
1
+ import tls from 'tls'
2
+ import net from 'net'
3
+ import _debug from 'debug'
4
+ import { StreamBuilder } from '../shared'
4
5
 
5
- function buildBuilder(mqttClient, opts) {
6
+ const debug = _debug('mqttjs:tls')
7
+
8
+ const buildStream: StreamBuilder = (client, opts) => {
6
9
  opts.port = opts.port || 8883
7
10
  opts.host = opts.hostname || opts.host || 'localhost'
8
11
 
@@ -22,7 +25,6 @@ function buildBuilder(mqttClient, opts) {
22
25
  )
23
26
 
24
27
  const connection = tls.connect(opts)
25
- /* eslint no-use-before-define: [2, "nofunc"] */
26
28
  connection.on('secureConnect', () => {
27
29
  if (opts.rejectUnauthorized && !connection.authorized) {
28
30
  connection.emit('error', new Error('TLS not authorized'))
@@ -31,10 +33,10 @@ function buildBuilder(mqttClient, opts) {
31
33
  }
32
34
  })
33
35
 
34
- function handleTLSerrors(err) {
36
+ function handleTLSerrors(err: Error) {
35
37
  // How can I get verify this error is a tls error?
36
38
  if (opts.rejectUnauthorized) {
37
- mqttClient.emit('error', err)
39
+ client.emit('error', err)
38
40
  }
39
41
 
40
42
  // close this connection to match the behaviour of net
@@ -49,4 +51,4 @@ function buildBuilder(mqttClient, opts) {
49
51
  return connection
50
52
  }
51
53
 
52
- module.exports = buildBuilder
54
+ export default buildStream
@@ -1,9 +1,14 @@
1
- const { Buffer } = require('buffer')
2
- const WS = require('ws')
3
- const debug = require('debug')('mqttjs:ws')
4
- const duplexify = require('duplexify')
5
- const { Transform } = require('readable-stream')
6
- const { IS_BROWSER } = require('../is-browser')
1
+ import { StreamBuilder } from '../shared'
2
+
3
+ import { Buffer } from 'buffer'
4
+ import WS, { ClientOptions } from 'ws'
5
+ import _debug from 'debug'
6
+ import duplexify from 'duplexify'
7
+ import { DuplexOptions, Transform } from 'readable-stream'
8
+ import IS_BROWSER from '../is-browser'
9
+ import MqttClient, { IClientOptions } from '../client'
10
+
11
+ const debug = _debug('mqttjs:ws')
7
12
 
8
13
  const WSS_OPTIONS = [
9
14
  'rejectUnauthorized',
@@ -14,7 +19,7 @@ const WSS_OPTIONS = [
14
19
  'passphrase',
15
20
  ]
16
21
 
17
- function buildUrl(opts, client) {
22
+ function buildUrl(opts: IClientOptions, client: MqttClient) {
18
23
  let url = `${opts.protocol}://${opts.hostname}:${opts.port}${opts.path}`
19
24
  if (typeof opts.transformWsUrl === 'function') {
20
25
  url = opts.transformWsUrl(url, opts, client)
@@ -22,7 +27,7 @@ function buildUrl(opts, client) {
22
27
  return url
23
28
  }
24
29
 
25
- function setDefaultOpts(opts) {
30
+ function setDefaultOpts(opts: IClientOptions) {
26
31
  const options = opts
27
32
  if (!opts.hostname) {
28
33
  options.hostname = 'localhost'
@@ -56,7 +61,7 @@ function setDefaultOpts(opts) {
56
61
  return options
57
62
  }
58
63
 
59
- function setDefaultBrowserOpts(opts) {
64
+ function setDefaultBrowserOpts(opts: IClientOptions) {
60
65
  const options = setDefaultOpts(opts)
61
66
 
62
67
  if (!options.hostname) {
@@ -74,7 +79,7 @@ function setDefaultBrowserOpts(opts) {
74
79
  options.hostname = parsed.hostname
75
80
 
76
81
  if (!options.port) {
77
- options.port = parsed.port
82
+ options.port = Number(parsed.port)
78
83
  }
79
84
  }
80
85
 
@@ -88,7 +93,11 @@ function setDefaultBrowserOpts(opts) {
88
93
  return options
89
94
  }
90
95
 
91
- function createWebSocket(client, url, opts) {
96
+ function createWebSocket(
97
+ client: MqttClient,
98
+ url: string,
99
+ opts: IClientOptions,
100
+ ) {
92
101
  debug('createWebSocket')
93
102
  debug(`protocol: ${opts.protocolId} ${opts.protocolVersion}`)
94
103
  const websocketSubProtocol =
@@ -99,11 +108,15 @@ function createWebSocket(client, url, opts) {
99
108
  debug(
100
109
  `creating new Websocket for url: ${url} and protocol: ${websocketSubProtocol}`,
101
110
  )
102
- const socket = new WS(url, [websocketSubProtocol], opts.wsOptions)
111
+ const socket = new WS(
112
+ url,
113
+ [websocketSubProtocol],
114
+ opts.wsOptions as ClientOptions,
115
+ )
103
116
  return socket
104
117
  }
105
118
 
106
- function createBrowserWebSocket(client, opts) {
119
+ function createBrowserWebSocket(client: MqttClient, opts: IClientOptions) {
107
120
  const websocketSubProtocol =
108
121
  opts.protocolId === 'MQIsdp' && opts.protocolVersion === 3
109
122
  ? 'mqttv3.1'
@@ -115,20 +128,24 @@ function createBrowserWebSocket(client, opts) {
115
128
  return socket
116
129
  }
117
130
 
118
- function streamBuilder(client, opts) {
131
+ const streamBuilder: StreamBuilder = (client, opts) => {
119
132
  debug('streamBuilder')
120
133
  const options = setDefaultOpts(opts)
121
134
  const url = buildUrl(options, client)
122
135
  const socket = createWebSocket(client, url, options)
123
- const webSocketStream = WS.createWebSocketStream(socket, options.wsOptions)
124
- webSocketStream.url = url
136
+ const webSocketStream = WS.createWebSocketStream(
137
+ socket,
138
+ options.wsOptions as DuplexOptions,
139
+ )
140
+
141
+ webSocketStream['url'] = url
125
142
  socket.on('close', () => {
126
143
  webSocketStream.destroy()
127
144
  })
128
145
  return webSocketStream
129
146
  }
130
147
 
131
- function browserStreamBuilder(client, opts) {
148
+ const browserStreamBuilder: StreamBuilder = (client, opts) => {
132
149
  debug('browserStreamBuilder')
133
150
  let stream
134
151
  const options = setDefaultBrowserOpts(opts)
@@ -140,7 +157,6 @@ function browserStreamBuilder(client, opts) {
140
157
  const coerceToBuffer = !opts.objectMode
141
158
 
142
159
  const socket = createBrowserWebSocket(client, opts)
143
-
144
160
  const proxy = buildProxy(opts, socketWriteBrowser, socketEndBrowser)
145
161
 
146
162
  if (!opts.objectMode) {
@@ -171,20 +187,20 @@ function browserStreamBuilder(client, opts) {
171
187
  stream.socket = socket
172
188
 
173
189
  if (eventListenerSupport) {
174
- socket.addEventListener('close', onclose)
175
- socket.addEventListener('error', onerror)
176
- socket.addEventListener('message', onmessage)
190
+ socket.addEventListener('close', onClose)
191
+ socket.addEventListener('error', onError)
192
+ socket.addEventListener('message', onMessage)
177
193
  } else {
178
- socket.onclose = onclose
179
- socket.onerror = onerror
180
- socket.onmessage = onmessage
194
+ socket.onclose = onClose
195
+ socket.onerror = onError
196
+ socket.onmessage = onMessage
181
197
  }
182
198
 
183
199
  // methods for browserStreamBuilder
184
200
 
185
- function buildProxy(pOptions, socketWrite, socketEnd) {
201
+ function buildProxy(pOptions: IClientOptions, socketWrite, socketEnd) {
186
202
  const _proxy = new Transform({
187
- objectModeMode: pOptions.objectMode,
203
+ objectMode: pOptions.objectMode,
188
204
  })
189
205
 
190
206
  _proxy._write = socketWrite
@@ -199,16 +215,16 @@ function browserStreamBuilder(client, opts) {
199
215
  stream.emit('connect')
200
216
  }
201
217
 
202
- function onclose() {
218
+ function onClose() {
203
219
  stream.end()
204
220
  stream.destroy()
205
221
  }
206
222
 
207
- function onerror(err) {
223
+ function onError(err: Event) {
208
224
  stream.destroy(err)
209
225
  }
210
226
 
211
- function onmessage(event) {
227
+ function onMessage(event: MessageEvent) {
212
228
  let { data } = event
213
229
  if (data instanceof ArrayBuffer) data = Buffer.from(data)
214
230
  else data = Buffer.from(data, 'utf8')
@@ -216,7 +232,7 @@ function browserStreamBuilder(client, opts) {
216
232
  }
217
233
 
218
234
  // this is to be enabled only if objectMode is false
219
- function writev(chunks, cb) {
235
+ function writev(chunks: any, cb: (err?: Error) => void) {
220
236
  const buffers = new Array(chunks.length)
221
237
  for (let i = 0; i < chunks.length; i++) {
222
238
  if (typeof chunks[i].chunk === 'string') {
@@ -229,7 +245,11 @@ function browserStreamBuilder(client, opts) {
229
245
  this._write(Buffer.concat(buffers), 'binary', cb)
230
246
  }
231
247
 
232
- function socketWriteBrowser(chunk, enc, next) {
248
+ function socketWriteBrowser(
249
+ chunk: any,
250
+ enc: string,
251
+ next: (err?: Error) => void,
252
+ ) {
233
253
  if (socket.bufferedAmount > bufferSize) {
234
254
  // throttle data until buffered amount is reduced.
235
255
  setTimeout(socketWriteBrowser, bufferTimeout, chunk, enc, next)
@@ -258,8 +278,4 @@ function browserStreamBuilder(client, opts) {
258
278
  return stream
259
279
  }
260
280
 
261
- if (IS_BROWSER) {
262
- module.exports = browserStreamBuilder
263
- } else {
264
- module.exports = streamBuilder
265
- }
281
+ export default IS_BROWSER ? browserStreamBuilder : streamBuilder
@@ -1,11 +1,14 @@
1
- const { Buffer } = require('buffer')
2
- const { Transform } = require('readable-stream')
3
- const duplexify = require('duplexify')
1
+ import { StreamBuilder } from '../shared'
2
+
3
+ import { Buffer } from 'buffer'
4
+ import { Transform } from 'readable-stream'
5
+ import duplexify, { Duplexify } from 'duplexify'
6
+ import MqttClient, { IClientOptions } from '../client'
4
7
 
5
8
  /* global wx */
6
- let socketTask
7
- let proxy
8
- let stream
9
+ let socketTask: any
10
+ let proxy: Transform
11
+ let stream: Duplexify
9
12
 
10
13
  function buildProxy() {
11
14
  const _proxy = new Transform()
@@ -44,7 +47,7 @@ function setDefaultOpts(opts) {
44
47
  }
45
48
  }
46
49
 
47
- function buildUrl(opts, client) {
50
+ function buildUrl(opts: IClientOptions, client: MqttClient) {
48
51
  const protocol = opts.protocol === 'wxs' ? 'wss' : 'ws'
49
52
  let url = `${protocol}://${opts.hostname}${opts.path}`
50
53
  if (opts.port && opts.port !== 80 && opts.port !== 443) {
@@ -81,7 +84,7 @@ function bindEventHandler() {
81
84
  })
82
85
  }
83
86
 
84
- function buildStream(client, opts) {
87
+ const buildStream: StreamBuilder = (client, opts) => {
85
88
  opts.hostname = opts.hostname || opts.host
86
89
 
87
90
  if (!opts.hostname) {
@@ -96,6 +99,8 @@ function buildStream(client, opts) {
96
99
  setDefaultOpts(opts)
97
100
 
98
101
  const url = buildUrl(opts, client)
102
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
103
+ // @ts-ignore
99
104
  socketTask = wx.connectSocket({
100
105
  url,
101
106
  protocols: [websocketSubProtocol],
@@ -112,12 +117,16 @@ function buildStream(client, opts) {
112
117
  }
113
118
 
114
119
  const destroyRef = stream.destroy
120
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
121
+ // @ts-ignore
115
122
  stream.destroy = () => {
116
123
  stream.destroy = destroyRef
117
124
 
118
125
  setTimeout(() => {
119
126
  socketTask.close({
120
127
  fail() {
128
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
129
+ // @ts-ignore
121
130
  stream._destroy(new Error())
122
131
  },
123
132
  })
@@ -129,4 +138,4 @@ function buildStream(client, opts) {
129
138
  return stream
130
139
  }
131
140
 
132
- module.exports = buildStream
141
+ export default buildStream