mqtt 5.0.0-beta.2 → 5.0.0-beta.4

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 (137) hide show
  1. package/README.md +48 -28
  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 +266 -0
  16. package/build/src/lib/client.js +1147 -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 +5 -0
  22. package/build/src/lib/connect/index.js +134 -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 +17 -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 +10 -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 +8 -0
  79. package/build/src/mqtt.js +33 -0
  80. package/build/src/mqtt.js.map +1 -0
  81. package/build/tsconfig.build.tsbuildinfo +1 -0
  82. package/dist/mqtt.js +4987 -5249
  83. package/dist/mqtt.min.js +4 -4
  84. package/package.json +84 -66
  85. package/src/bin/mqtt.ts +32 -0
  86. package/src/bin/pub.ts +171 -0
  87. package/src/bin/sub.ts +146 -0
  88. package/src/lib/TypedEmitter.ts +45 -0
  89. package/src/lib/client.ts +2279 -0
  90. package/src/lib/connect/ali.ts +128 -0
  91. package/src/lib/connect/index.ts +180 -0
  92. package/src/lib/connect/tcp.ts +23 -0
  93. package/src/lib/connect/tls.ts +56 -0
  94. package/src/lib/connect/ws.ts +282 -0
  95. package/src/lib/connect/wx.ts +141 -0
  96. package/src/lib/default-message-id-provider.ts +99 -0
  97. package/src/lib/handlers/ack.ts +151 -0
  98. package/src/lib/handlers/auth.ts +44 -0
  99. package/src/lib/handlers/connack.ts +55 -0
  100. package/src/lib/handlers/index.ts +67 -0
  101. package/src/lib/handlers/publish.ts +183 -0
  102. package/src/lib/handlers/pubrel.ts +27 -0
  103. package/src/lib/is-browser.ts +12 -0
  104. package/src/lib/shared.ts +73 -0
  105. package/src/lib/store.ts +166 -0
  106. package/src/lib/topic-alias-recv.ts +48 -0
  107. package/src/lib/topic-alias-send.ts +96 -0
  108. package/src/lib/unique-message-id-provider.ts +63 -0
  109. package/src/lib/validations.ts +46 -0
  110. package/src/mqtt.ts +23 -0
  111. package/bin/mqtt.js +0 -27
  112. package/bin/pub.js +0 -146
  113. package/bin/sub.js +0 -123
  114. package/lib/client.js +0 -1918
  115. package/lib/connect/ali.js +0 -129
  116. package/lib/connect/index.js +0 -169
  117. package/lib/connect/tcp.js +0 -20
  118. package/lib/connect/tls.js +0 -48
  119. package/lib/connect/ws.js +0 -257
  120. package/lib/connect/wx.js +0 -133
  121. package/lib/default-message-id-provider.js +0 -69
  122. package/lib/is-browser.js +0 -11
  123. package/lib/store.js +0 -128
  124. package/lib/topic-alias-recv.js +0 -47
  125. package/lib/topic-alias-send.js +0 -91
  126. package/lib/unique-message-id-provider.js +0 -65
  127. package/lib/validations.js +0 -52
  128. package/mqtt.js +0 -21
  129. package/types/index.d.ts +0 -30
  130. package/types/lib/client-options.d.ts +0 -208
  131. package/types/lib/client.d.ts +0 -261
  132. package/types/lib/connect/index.d.ts +0 -19
  133. package/types/lib/default-message-id-provider.d.ts +0 -49
  134. package/types/lib/message-id-provider.d.ts +0 -40
  135. package/types/lib/store-options.d.ts +0 -6
  136. package/types/lib/store.d.ts +0 -46
  137. package/types/lib/unique-message-id-provider.d.ts +0 -48
@@ -0,0 +1,183 @@
1
+ import { IPublishPacket } from 'mqtt-packet'
2
+ import { PacketHandler } from '../shared'
3
+
4
+ const validReasonCodes = [0, 16, 128, 131, 135, 144, 145, 151, 153]
5
+
6
+ /*
7
+ those late 2 case should be rewrite to comply with coding style:
8
+
9
+ case 1:
10
+ case 0:
11
+ // do not wait sending a puback
12
+ // no callback passed
13
+ if (1 === qos) {
14
+ this._sendPacket({
15
+ cmd: 'puback',
16
+ messageId: messageId
17
+ });
18
+ }
19
+ // emit the message event for both qos 1 and 0
20
+ this.emit('message', topic, message, packet);
21
+ this.handleMessage(packet, done);
22
+ break;
23
+ default:
24
+ // do nothing but every switch mus have a default
25
+ // log or throw an error about unknown qos
26
+ break;
27
+
28
+ for now i just suppressed the warnings
29
+ */
30
+ const handlePublish: PacketHandler = (client, packet: IPublishPacket, done) => {
31
+ client.log('handlePublish: packet %o', packet)
32
+ done = typeof done !== 'undefined' ? done : client.noop
33
+ let topic = packet.topic.toString()
34
+ const message = packet.payload
35
+ const { qos } = packet
36
+ const { messageId } = packet
37
+ const { options } = client
38
+ if (client.options.protocolVersion === 5) {
39
+ let alias: number
40
+ if (packet.properties) {
41
+ alias = packet.properties.topicAlias
42
+ }
43
+ if (typeof alias !== 'undefined') {
44
+ if (topic.length === 0) {
45
+ if (alias > 0 && alias <= 0xffff) {
46
+ const gotTopic =
47
+ client['topicAliasRecv'].getTopicByAlias(alias)
48
+ if (gotTopic) {
49
+ topic = gotTopic
50
+ client.log(
51
+ 'handlePublish :: topic complemented by alias. topic: %s - alias: %d',
52
+ topic,
53
+ alias,
54
+ )
55
+ } else {
56
+ client.log(
57
+ 'handlePublish :: unregistered topic alias. alias: %d',
58
+ alias,
59
+ )
60
+ client.emit(
61
+ 'error',
62
+ new Error('Received unregistered Topic Alias'),
63
+ )
64
+ return
65
+ }
66
+ } else {
67
+ client.log(
68
+ 'handlePublish :: topic alias out of range. alias: %d',
69
+ alias,
70
+ )
71
+ client.emit(
72
+ 'error',
73
+ new Error('Received Topic Alias is out of range'),
74
+ )
75
+ return
76
+ }
77
+ } else if (client['topicAliasRecv'].put(topic, alias)) {
78
+ client.log(
79
+ 'handlePublish :: registered topic: %s - alias: %d',
80
+ topic,
81
+ alias,
82
+ )
83
+ } else {
84
+ client.log(
85
+ 'handlePublish :: topic alias out of range. alias: %d',
86
+ alias,
87
+ )
88
+ client.emit(
89
+ 'error',
90
+ new Error('Received Topic Alias is out of range'),
91
+ )
92
+ return
93
+ }
94
+ }
95
+ }
96
+ client.log('handlePublish: qos %d', qos)
97
+ switch (qos) {
98
+ case 2: {
99
+ options.customHandleAcks(
100
+ topic,
101
+ message as Buffer,
102
+ packet,
103
+ (error, code) => {
104
+ if (typeof error === 'number') {
105
+ code = error
106
+ error = null
107
+ }
108
+ if (error) {
109
+ return client.emit('error', error)
110
+ }
111
+ if (validReasonCodes.indexOf(code) === -1) {
112
+ return client.emit(
113
+ 'error',
114
+ new Error('Wrong reason code for pubrec'),
115
+ )
116
+ }
117
+ if (code) {
118
+ client['_sendPacket'](
119
+ { cmd: 'pubrec', messageId, reasonCode: code },
120
+ done,
121
+ )
122
+ } else {
123
+ client.incomingStore.put(packet, () => {
124
+ client['_sendPacket'](
125
+ { cmd: 'pubrec', messageId },
126
+ done,
127
+ )
128
+ })
129
+ }
130
+ },
131
+ )
132
+ break
133
+ }
134
+ case 1: {
135
+ // emit the message event
136
+ options.customHandleAcks(
137
+ topic,
138
+ message as Buffer,
139
+ packet,
140
+ (error, code) => {
141
+ if (typeof error === 'number') {
142
+ code = error
143
+ error = null
144
+ }
145
+ if (error) {
146
+ return client.emit('error', error)
147
+ }
148
+ if (validReasonCodes.indexOf(code) === -1) {
149
+ return client.emit(
150
+ 'error',
151
+ new Error('Wrong reason code for puback'),
152
+ )
153
+ }
154
+ if (!code) {
155
+ client.emit('message', topic, message as Buffer, packet)
156
+ }
157
+ client.handleMessage(packet, (err) => {
158
+ if (err) {
159
+ return done && done(err)
160
+ }
161
+ client['_sendPacket'](
162
+ { cmd: 'puback', messageId, reasonCode: code },
163
+ done,
164
+ )
165
+ })
166
+ },
167
+ )
168
+ break
169
+ }
170
+ case 0:
171
+ // emit the message event
172
+ client.emit('message', topic, message as Buffer, packet)
173
+ client.handleMessage(packet, done)
174
+ break
175
+ default:
176
+ // do nothing
177
+ client.log('handlePublish: unknown QoS. Doing nothing.')
178
+ // log or throw an error about unknown qos
179
+ break
180
+ }
181
+ }
182
+
183
+ export default handlePublish
@@ -0,0 +1,27 @@
1
+ import { IPubcompPacket, IPublishPacket, IPubrelPacket } from 'mqtt-packet'
2
+ import { PacketHandler } from '../shared'
3
+
4
+ const handlePubrel: PacketHandler = (client, packet: IPubrelPacket, done) => {
5
+ client.log('handling pubrel packet')
6
+ const callback = typeof done !== 'undefined' ? done : client.noop
7
+ const { messageId } = packet
8
+
9
+ const comp: IPubcompPacket = { cmd: 'pubcomp', messageId }
10
+
11
+ client.incomingStore.get(packet, (err, pub: IPublishPacket) => {
12
+ if (!err) {
13
+ client.emit('message', pub.topic, pub.payload as Buffer, pub)
14
+ client.handleMessage(pub, (err2) => {
15
+ if (err2) {
16
+ return callback(err2)
17
+ }
18
+ client.incomingStore.del(pub, client.noop)
19
+ client['_sendPacket'](comp, callback)
20
+ })
21
+ } else {
22
+ client['_sendPacket'](comp, callback)
23
+ }
24
+ })
25
+ }
26
+
27
+ export default handlePubrel
@@ -0,0 +1,12 @@
1
+ const legacyIsBrowser =
2
+ (typeof process !== 'undefined' && process.title === 'browser') ||
3
+ // eslint-disable-next-line camelcase, @typescript-eslint/ban-ts-comment
4
+ // @ts-ignore
5
+ typeof __webpack_require__ === 'function'
6
+
7
+ const isBrowser =
8
+ typeof window !== 'undefined' && typeof document !== 'undefined'
9
+
10
+ const IS_BROWSER = isBrowser || legacyIsBrowser
11
+
12
+ export default IS_BROWSER
@@ -0,0 +1,73 @@
1
+ import type { IClientOptions } from './client'
2
+ import type MqttClient from './client'
3
+ import { Packet } from 'mqtt-packet'
4
+ import { Duplex, Writable } from 'readable-stream'
5
+
6
+ export type DoneCallback = (error?: Error) => void
7
+
8
+ export type GenericCallback<T> = (error?: Error, result?: T) => void
9
+
10
+ export type VoidCallback = () => void
11
+
12
+ export type IStream = Duplex | Writable
13
+
14
+ export type StreamBuilder = (
15
+ client: MqttClient,
16
+ opts?: IClientOptions,
17
+ ) => IStream
18
+
19
+ export type Callback = () => void
20
+
21
+ export type PacketHandler = (
22
+ client: MqttClient,
23
+ packet: Packet,
24
+ done?: DoneCallback,
25
+ ) => void
26
+
27
+ export class ErrorWithReasonCode extends Error {
28
+ public code: number
29
+
30
+ public constructor(message: string, code: number) {
31
+ super(message)
32
+ this.code = code
33
+
34
+ // We need to set the prototype explicitly
35
+ Object.setPrototypeOf(this, ErrorWithReasonCode.prototype)
36
+ Object.getPrototypeOf(this).name = 'ErrorWithReasonCode'
37
+ }
38
+ }
39
+
40
+ // eslint-disable-next-line @typescript-eslint/ban-types
41
+ export type Constructor<T = {}> = new (...args: any[]) => T
42
+
43
+ export function applyMixin(
44
+ target: Constructor,
45
+ mixin: Constructor,
46
+ includeConstructor = false,
47
+ ): void {
48
+ // Figure out the inheritance chain of the mixin
49
+ const inheritanceChain: Constructor[] = [mixin]
50
+ // eslint-disable-next-line no-constant-condition
51
+ while (true) {
52
+ const current = inheritanceChain[0]
53
+ const base = Object.getPrototypeOf(current)
54
+ if (base?.prototype) {
55
+ inheritanceChain.unshift(base)
56
+ } else {
57
+ break
58
+ }
59
+ }
60
+ for (const ctor of inheritanceChain) {
61
+ for (const prop of Object.getOwnPropertyNames(ctor.prototype)) {
62
+ // Do not override the constructor
63
+ if (includeConstructor || prop !== 'constructor') {
64
+ Object.defineProperty(
65
+ target.prototype,
66
+ prop,
67
+ Object.getOwnPropertyDescriptor(ctor.prototype, prop) ??
68
+ Object.create(null),
69
+ )
70
+ }
71
+ }
72
+ }
73
+ }
@@ -0,0 +1,166 @@
1
+ /**
2
+ * Module dependencies
3
+ */
4
+ import { Readable } from 'readable-stream'
5
+ import { Packet } from 'mqtt-packet'
6
+ import { DoneCallback } from './shared'
7
+
8
+ const streamsOpts = { objectMode: true }
9
+ const defaultStoreOptions = {
10
+ clean: true,
11
+ }
12
+
13
+ export interface IStoreOptions {
14
+ /**
15
+ * true, clear _inflights at close
16
+ */
17
+ clean?: boolean
18
+ }
19
+
20
+ export type PacketCallback = (error?: Error, packet?: Packet) => void
21
+
22
+ export interface IStore {
23
+ /**
24
+ * Adds a packet to the store, a packet is
25
+ * anything that has a messageId property.
26
+ *
27
+ */
28
+ put(packet: Packet, cb: DoneCallback): IStore
29
+
30
+ /**
31
+ * Creates a stream with all the packets in the store
32
+ *
33
+ */
34
+ createStream(): Readable
35
+
36
+ /**
37
+ * deletes a packet from the store.
38
+ */
39
+ del(packet: Pick<Packet, 'messageId'>, cb: PacketCallback): IStore
40
+
41
+ /**
42
+ * get a packet from the store.
43
+ */
44
+ get(packet: Pick<Packet, 'messageId'>, cb: PacketCallback): IStore
45
+
46
+ /**
47
+ * Close the store
48
+ */
49
+ close(cb: DoneCallback): void
50
+ }
51
+
52
+ /**
53
+ * In-memory implementation of the message store
54
+ * This can actually be saved into files.
55
+ *
56
+ * @param {Object} [options] - store options
57
+ */
58
+ export default class Store implements IStore {
59
+ private options: IStoreOptions
60
+
61
+ private _inflights: Map<number, Packet>
62
+
63
+ constructor(options?: IStoreOptions) {
64
+ this.options = options || {}
65
+
66
+ // Defaults
67
+ this.options = { ...defaultStoreOptions, ...options }
68
+
69
+ this._inflights = new Map()
70
+ }
71
+
72
+ /**
73
+ * Adds a packet to the store, a packet is
74
+ * anything that has a messageId property.
75
+ *
76
+ */
77
+ put(packet: Packet, cb: DoneCallback) {
78
+ this._inflights.set(packet.messageId, packet)
79
+
80
+ if (cb) {
81
+ cb()
82
+ }
83
+
84
+ return this
85
+ }
86
+
87
+ /**
88
+ * Creates a stream with all the packets in the store
89
+ *
90
+ */
91
+ createStream() {
92
+ const stream = new Readable(streamsOpts)
93
+ const values = []
94
+ let destroyed = false
95
+ let i = 0
96
+
97
+ this._inflights.forEach((value, key) => {
98
+ values.push(value)
99
+ })
100
+
101
+ stream._read = () => {
102
+ if (!destroyed && i < values.length) {
103
+ stream.push(values[i++])
104
+ } else {
105
+ stream.push(null)
106
+ }
107
+ }
108
+
109
+ stream.destroy = (err) => {
110
+ if (destroyed) {
111
+ return
112
+ }
113
+
114
+ destroyed = true
115
+
116
+ setTimeout(() => {
117
+ stream.emit('close')
118
+ }, 0)
119
+
120
+ return stream
121
+ }
122
+
123
+ return stream
124
+ }
125
+
126
+ /**
127
+ * deletes a packet from the store.
128
+ */
129
+ del(packet: Pick<Packet, 'messageId'>, cb: PacketCallback) {
130
+ const toDelete = this._inflights.get(packet.messageId)
131
+ if (toDelete) {
132
+ this._inflights.delete(packet.messageId)
133
+ cb(null, toDelete)
134
+ } else if (cb) {
135
+ cb(new Error('missing packet'))
136
+ }
137
+
138
+ return this
139
+ }
140
+
141
+ /**
142
+ * get a packet from the store.
143
+ */
144
+ get(packet: Pick<Packet, 'messageId'>, cb: PacketCallback) {
145
+ const storedPacket = this._inflights.get(packet.messageId)
146
+ if (storedPacket) {
147
+ cb(null, storedPacket)
148
+ } else if (cb) {
149
+ cb(new Error('missing packet'))
150
+ }
151
+
152
+ return this
153
+ }
154
+
155
+ /**
156
+ * Close the store
157
+ */
158
+ close(cb: DoneCallback) {
159
+ if (this.options.clean) {
160
+ this._inflights = null
161
+ }
162
+ if (cb) {
163
+ cb()
164
+ }
165
+ }
166
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Topic Alias receiving manager
3
+ * This holds alias to topic map
4
+ * @param {Number} [max] - topic alias maximum entries
5
+ */
6
+ export default class TopicAliasRecv {
7
+ private aliasToTopic: Record<number, string>
8
+
9
+ public max: number
10
+
11
+ public length: number
12
+
13
+ constructor(max: number) {
14
+ this.aliasToTopic = {}
15
+ this.max = max
16
+ }
17
+
18
+ /**
19
+ * Insert or update topic - alias entry.
20
+ * @param {String} [topic] - topic
21
+ * @param {Number} [alias] - topic alias
22
+ * @returns {Boolean} - if success return true otherwise false
23
+ */
24
+ put(topic: string, alias: number): boolean {
25
+ if (alias === 0 || alias > this.max) {
26
+ return false
27
+ }
28
+ this.aliasToTopic[alias] = topic
29
+ this.length = Object.keys(this.aliasToTopic).length
30
+ return true
31
+ }
32
+
33
+ /**
34
+ * Get topic by alias
35
+ * @param {String} [topic] - topic
36
+ * @returns {Number} - if mapped topic exists return topic alias, otherwise return undefined
37
+ */
38
+ getTopicByAlias(alias: number): string {
39
+ return this.aliasToTopic[alias]
40
+ }
41
+
42
+ /**
43
+ * Clear all entries
44
+ */
45
+ clear() {
46
+ this.aliasToTopic = {}
47
+ }
48
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Module dependencies
3
+ */
4
+ import LRUCache from 'lru-cache'
5
+ import { NumberAllocator } from 'number-allocator'
6
+
7
+ /**
8
+ * Topic Alias sending manager
9
+ * This holds both topic to alias and alias to topic map
10
+ * @param {Number} [max] - topic alias maximum entries
11
+ */
12
+ export default class TopicAliasSend {
13
+ private aliasToTopic: LRUCache<number, string>
14
+
15
+ private topicToAlias: Record<string, number>
16
+
17
+ private max: number
18
+
19
+ private numberAllocator: NumberAllocator
20
+
21
+ public length: number
22
+
23
+ constructor(max: number) {
24
+ if (max > 0) {
25
+ this.aliasToTopic = new LRUCache<number, string>({ max })
26
+ this.topicToAlias = {}
27
+ this.numberAllocator = new NumberAllocator(1, max)
28
+ this.max = max
29
+ this.length = 0
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Insert or update topic - alias entry.
35
+ * @param {String} [topic] - topic
36
+ * @param {Number} [alias] - topic alias
37
+ * @returns {Boolean} - if success return true otherwise false
38
+ */
39
+ put(topic: string, alias: number): boolean {
40
+ if (alias === 0 || alias > this.max) {
41
+ return false
42
+ }
43
+ const entry = this.aliasToTopic.get(alias)
44
+ if (entry) {
45
+ delete this.topicToAlias[entry]
46
+ }
47
+ this.aliasToTopic.set(alias, topic)
48
+ this.topicToAlias[topic] = alias
49
+ this.numberAllocator.use(alias)
50
+ this.length = this.aliasToTopic.size
51
+ return true
52
+ }
53
+
54
+ /**
55
+ * Get topic by alias
56
+ * @param {Number} [alias] - topic alias
57
+ * @returns {String} - if mapped topic exists return topic, otherwise return undefined
58
+ */
59
+ getTopicByAlias(alias: number): string {
60
+ return this.aliasToTopic.get(alias)
61
+ }
62
+
63
+ /**
64
+ * Get topic by alias
65
+ * @param {String} [topic] - topic
66
+ * @returns {Number} - if mapped topic exists return topic alias, otherwise return undefined
67
+ */
68
+ getAliasByTopic(topic: string): number | undefined {
69
+ const alias = this.topicToAlias[topic]
70
+ if (typeof alias !== 'undefined') {
71
+ this.aliasToTopic.get(alias) // LRU update
72
+ }
73
+ return alias
74
+ }
75
+
76
+ /**
77
+ * Clear all entries
78
+ */
79
+ clear() {
80
+ this.aliasToTopic.clear()
81
+ this.topicToAlias = {}
82
+ this.numberAllocator.clear()
83
+ this.length = 0
84
+ }
85
+
86
+ /**
87
+ * Get Least Recently Used (LRU) topic alias
88
+ * @returns {Number} - if vacant alias exists then return it, otherwise then return LRU alias
89
+ */
90
+ getLruAlias(): number {
91
+ const alias = this.numberAllocator.firstVacant()
92
+ if (alias) return alias
93
+ // get last alias (key) from LRU cache
94
+ return [...this.aliasToTopic.keys()][this.aliasToTopic.size - 1]
95
+ }
96
+ }
@@ -0,0 +1,63 @@
1
+ import { NumberAllocator } from 'number-allocator'
2
+
3
+ /**
4
+ * UniqueMessageAllocator constructor
5
+ * @constructor
6
+ */
7
+ export default class UniqueMessageIdProvider {
8
+ private numberAllocator: NumberAllocator
9
+
10
+ private lastId: number
11
+
12
+ constructor() {
13
+ this.numberAllocator = new NumberAllocator(1, 65535)
14
+ }
15
+
16
+ /**
17
+ * allocate
18
+ *
19
+ * Get the next messageId.
20
+ * @return if messageId is fully allocated then return null,
21
+ * otherwise return the smallest usable unsigned int messageId.
22
+ */
23
+ allocate() {
24
+ this.lastId = this.numberAllocator.alloc()
25
+ return this.lastId
26
+ }
27
+
28
+ /**
29
+ * getLastAllocated
30
+ * Get the last allocated messageId.
31
+ * @return unsigned int
32
+ */
33
+ getLastAllocated() {
34
+ return this.lastId
35
+ }
36
+
37
+ /**
38
+ * register
39
+ * Register messageId. If success return true, otherwise return false.
40
+ * @param { unsigned int } - messageId to register,
41
+ * @return boolean
42
+ */
43
+ register(messageId: number) {
44
+ return this.numberAllocator.use(messageId)
45
+ }
46
+
47
+ /**
48
+ * deallocate
49
+ * Deallocate messageId.
50
+ * @param { unsigned int } - messageId to deallocate,
51
+ */
52
+ deallocate(messageId: number) {
53
+ this.numberAllocator.free(messageId)
54
+ }
55
+
56
+ /**
57
+ * clear
58
+ * Deallocate all messageIds.
59
+ */
60
+ clear() {
61
+ this.numberAllocator.clear()
62
+ }
63
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Validate a topic to see if it's valid or not.
3
+ * A topic is valid if it follow below rules:
4
+ * - Rule #1: If any part of the topic is not `+` or `#`, then it must not contain `+` and '#'
5
+ * - Rule #2: Part `#` must be located at the end of the mailbox
6
+ *
7
+ * @param {String} topic - A topic
8
+ * @returns {Boolean} If the topic is valid, returns true. Otherwise, returns false.
9
+ */
10
+ export function validateTopic(topic: string): boolean {
11
+ const parts = topic.split('/')
12
+
13
+ for (let i = 0; i < parts.length; i++) {
14
+ if (parts[i] === '+') {
15
+ continue
16
+ }
17
+
18
+ if (parts[i] === '#') {
19
+ // for Rule #2
20
+ return i === parts.length - 1
21
+ }
22
+
23
+ if (parts[i].indexOf('+') !== -1 || parts[i].indexOf('#') !== -1) {
24
+ return false
25
+ }
26
+ }
27
+
28
+ return true
29
+ }
30
+
31
+ /**
32
+ * Validate an array of topics to see if any of them is valid or not
33
+ * @param {Array} topics - Array of topics
34
+ * @returns {String} If the topics is valid, returns null. Otherwise, returns the invalid one
35
+ */
36
+ export function validateTopics(topics: string[]): string {
37
+ if (topics.length === 0) {
38
+ return 'empty_topic_list'
39
+ }
40
+ for (let i = 0; i < topics.length; i++) {
41
+ if (!validateTopic(topics[i])) {
42
+ return topics[i]
43
+ }
44
+ }
45
+ return null
46
+ }