@hiroosy/baileys-lite 0.0.1

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 (63) hide show
  1. package/README.md +25 -0
  2. package/WAProto/index.d.ts +15932 -0
  3. package/WAProto/index.js +115856 -0
  4. package/engine-requirements.js +11 -0
  5. package/package.json +27 -0
  6. package/src/binary/wa-binary-constants.js +1300 -0
  7. package/src/binary/wa-binary.js +649 -0
  8. package/src/constants.js +143 -0
  9. package/src/defaults.js +102 -0
  10. package/src/foundation/audio-duration.js +530 -0
  11. package/src/foundation/audio-samples.js +268 -0
  12. package/src/foundation/boom.js +46 -0
  13. package/src/foundation/cache.js +142 -0
  14. package/src/foundation/concurrency.js +87 -0
  15. package/src/foundation/curve25519.js +221 -0
  16. package/src/foundation/link-preview.js +320 -0
  17. package/src/foundation/logger.js +69 -0
  18. package/src/foundation/long.js +140 -0
  19. package/src/foundation/protobuf-minimal.js +619 -0
  20. package/src/foundation/wa-crypto.js +76 -0
  21. package/src/foundation/zip.js +124 -0
  22. package/src/index.js +48 -0
  23. package/src/signal/libsignal.js +1051 -0
  24. package/src/signal/signal-group.js +487 -0
  25. package/src/signal/signal-repository.js +646 -0
  26. package/src/socket/business-communities.js +830 -0
  27. package/src/socket/chats.js +674 -0
  28. package/src/socket/groups-newsletter.js +342 -0
  29. package/src/socket/messages-recv.js +1835 -0
  30. package/src/socket/messages-send.js +1202 -0
  31. package/src/socket/socket-core.js +833 -0
  32. package/src/socket/usync.js +291 -0
  33. package/src/socket-client/websocket-client.js +124 -0
  34. package/src/utils/auth-state-core.js +764 -0
  35. package/src/utils/auth-state-storage.js +316 -0
  36. package/src/utils/chat-sync.js +1045 -0
  37. package/src/utils/media.js +841 -0
  38. package/src/utils/message-compose.js +1609 -0
  39. package/src/utils/message-processing.js +958 -0
  40. package/src/utils/wa-protocol-core.js +1283 -0
  41. package/src/vendor/jpeg-js/LICENSE +25 -0
  42. package/src/vendor/jpeg-js/decoder.js +1152 -0
  43. package/src/vendor/jpeg-js/encoder.js +824 -0
  44. package/src/vendor/pngjs/LICENSE +20 -0
  45. package/src/vendor/pngjs/bitmapper.js +273 -0
  46. package/src/vendor/pngjs/bitpacker.js +167 -0
  47. package/src/vendor/pngjs/constants.js +38 -0
  48. package/src/vendor/pngjs/crc.js +47 -0
  49. package/src/vendor/pngjs/filter-pack.js +179 -0
  50. package/src/vendor/pngjs/filter-parse-sync.js +27 -0
  51. package/src/vendor/pngjs/filter-parse.js +185 -0
  52. package/src/vendor/pngjs/format-normaliser.js +101 -0
  53. package/src/vendor/pngjs/interlace.js +101 -0
  54. package/src/vendor/pngjs/packer-sync.js +65 -0
  55. package/src/vendor/pngjs/packer.js +138 -0
  56. package/src/vendor/pngjs/paeth-predictor.js +22 -0
  57. package/src/vendor/pngjs/parser-sync.js +121 -0
  58. package/src/vendor/pngjs/parser.js +299 -0
  59. package/src/vendor/pngjs/png-sync.js +19 -0
  60. package/src/vendor/pngjs/sync-inflate.js +174 -0
  61. package/src/vendor/pngjs/sync-reader.js +54 -0
  62. package/src/wam/wam-constants.js +22853 -0
  63. package/src/wam/wam.js +151 -0
@@ -0,0 +1,268 @@
1
+ /**
2
+ * Native PCM decoders for waveform generation (replaces `audio-decode` for the formats that can be decoded exactly
3
+ * without a codec library): WAV (PCM 8/16/24/32-bit, IEEE float 32/64, WAVE_FORMAT_EXTENSIBLE) and FLAC.
4
+ *
5
+ * `decodeChannel0(buffer)` returns the FIRST channel as a Float32Array in [-1, 1], or `undefined` when the container
6
+ * is not one of the above (Ogg Opus/Vorbis, MP3, AAC, ... need a real codec: see getAudioWaveform's ffmpeg fallback).
7
+ * Values are exactly sample / 2^(bits-1), i.e. what a bit-exact decoder produces.
8
+ */
9
+
10
+ /* ------------------------------ WAV ------------------------------ */
11
+
12
+ function decodeWav(buf) {
13
+ if (buf.toString('latin1', 0, 4) !== 'RIFF' || buf.toString('latin1', 8, 12) !== 'WAVE') return undefined
14
+ let pos = 12
15
+ let fmt
16
+ while (pos + 8 <= buf.length) {
17
+ const id = buf.toString('latin1', pos, pos + 4)
18
+ const size = buf.readUInt32LE(pos + 4)
19
+ const body = pos + 8
20
+ if (id === 'fmt ') {
21
+ let tag = buf.readUInt16LE(body)
22
+ const bits = buf.readUInt16LE(body + 14)
23
+ if (tag === 0xfffe && size >= 26) tag = buf.readUInt16LE(body + 24) // extensible: real format = first 2 bytes of SubFormat
24
+ fmt = { tag, channels: buf.readUInt16LE(body + 2), blockAlign: buf.readUInt16LE(body + 12), bits }
25
+ } else if (id === 'data') {
26
+ if (!fmt || !fmt.channels || !fmt.blockAlign) return undefined
27
+ const end = Math.min(buf.length, size === 0xffffffff ? buf.length : body + size)
28
+ const frames = Math.floor((end - body) / fmt.blockAlign)
29
+ const bytes = fmt.bits >> 3
30
+ const out = new Float32Array(frames)
31
+ for (let i = 0; i < frames; i++) {
32
+ const o = body + i * fmt.blockAlign // channel 0 is the first sample of each frame
33
+ let v
34
+ if (fmt.tag === 1) {
35
+ if (fmt.bits === 8) v = (buf[o] - 128) / 128
36
+ else if (fmt.bits === 16) v = buf.readInt16LE(o) / 32768
37
+ else if (fmt.bits === 24) v = buf.readIntLE(o, 3) / 8388608
38
+ else if (fmt.bits === 32) v = buf.readInt32LE(o) / 2147483648
39
+ else return undefined
40
+ } else if (fmt.tag === 3) {
41
+ if (bytes === 4) v = buf.readFloatLE(o)
42
+ else if (bytes === 8) v = buf.readDoubleLE(o)
43
+ else return undefined
44
+ } else return undefined // ADPCM, A-law, mu-law, MP3-in-WAV, ...
45
+ out[i] = v
46
+ }
47
+ return out
48
+ }
49
+ pos = body + size + (size & 1)
50
+ }
51
+ return undefined
52
+ }
53
+
54
+ /* ------------------------------ FLAC ------------------------------ */
55
+
56
+ class Bits {
57
+ constructor(buf, pos) {
58
+ this.buf = buf
59
+ this.pos = pos * 8 // bit position
60
+ }
61
+ get bytePos() {
62
+ return this.pos >> 3
63
+ }
64
+ read(n) {
65
+ // up to 32 bits, unsigned
66
+ let v = 0
67
+ while (n > 0) {
68
+ const byte = this.buf[this.pos >> 3]
69
+ if (byte === undefined) throw new Error('FLAC: unexpected end of data')
70
+ const avail = 8 - (this.pos & 7)
71
+ const take = Math.min(avail, n)
72
+ v = v * (1 << take) + ((byte >> (avail - take)) & ((1 << take) - 1))
73
+ this.pos += take
74
+ n -= take
75
+ }
76
+ return v
77
+ }
78
+ readSigned(n) {
79
+ const v = this.read(n)
80
+ return v >= 2 ** (n - 1) ? v - 2 ** n : v
81
+ }
82
+ unary() {
83
+ let n = 0
84
+ while (this.read(1) === 0) n++
85
+ return n
86
+ }
87
+ align() {
88
+ this.pos = (this.pos + 7) & ~7
89
+ }
90
+ }
91
+
92
+ const FIXED = [[], [1], [2, -1], [3, -3, 1], [4, -6, 4, -1]]
93
+ const BLOCK_SIZES = { 1: 192, 2: 576, 3: 1152, 4: 2304, 5: 4608, 8: 256, 9: 512, 10: 1024, 11: 2048, 12: 4096, 13: 8192, 14: 16384, 15: 32768 }
94
+ const SAMPLE_BITS = { 1: 8, 2: 12, 4: 16, 5: 20, 6: 24, 7: 32 }
95
+
96
+ function readResidual(br, out, offset, blockSize, order) {
97
+ const method = br.read(2)
98
+ if (method > 1) throw new Error('FLAC: bad residual coding method')
99
+ const paramBits = method === 0 ? 4 : 5
100
+ const escape = method === 0 ? 15 : 31
101
+ const partOrder = br.read(4)
102
+ const parts = 1 << partOrder
103
+ let n = offset + order
104
+ for (let p = 0; p < parts; p++) {
105
+ const count = (blockSize >> partOrder) - (p === 0 ? order : 0)
106
+ const param = br.read(paramBits)
107
+ if (param === escape) {
108
+ const bits = br.read(5)
109
+ for (let i = 0; i < count; i++) out[n++] = bits ? br.readSigned(bits) : 0
110
+ } else {
111
+ for (let i = 0; i < count; i++) {
112
+ const q = br.unary()
113
+ const r = param ? br.read(param) : 0
114
+ const u = q * 2 ** param + r
115
+ out[n++] = u % 2 === 0 ? u / 2 : -(u + 1) / 2 // zig-zag
116
+ }
117
+ }
118
+ }
119
+ }
120
+
121
+ function readSubframe(br, blockSize, bps) {
122
+ br.read(1) // padding
123
+ const type = br.read(6)
124
+ let wasted = 0
125
+ if (br.read(1)) wasted = br.unary() + 1
126
+ const bits = bps - wasted
127
+ const s = new Float64Array(blockSize)
128
+ if (type === 0) {
129
+ const v = br.readSigned(bits)
130
+ s.fill(v)
131
+ } else if (type === 1) {
132
+ for (let i = 0; i < blockSize; i++) s[i] = br.readSigned(bits)
133
+ } else if (type >= 8 && type <= 12) {
134
+ const order = type - 8
135
+ for (let i = 0; i < order; i++) s[i] = br.readSigned(bits)
136
+ readResidual(br, s, 0, blockSize, order)
137
+ const c = FIXED[order]
138
+ for (let i = order; i < blockSize; i++) {
139
+ let pred = 0
140
+ for (let j = 0; j < order; j++) pred += c[j] * s[i - 1 - j]
141
+ s[i] += pred
142
+ }
143
+ } else if (type >= 32) {
144
+ const order = type - 31
145
+ for (let i = 0; i < order; i++) s[i] = br.readSigned(bits)
146
+ const precision = br.read(4) + 1
147
+ if (precision === 16) throw new Error('FLAC: invalid LPC precision')
148
+ const shift = br.readSigned(5)
149
+ const coefs = []
150
+ for (let i = 0; i < order; i++) coefs.push(br.readSigned(precision))
151
+ readResidual(br, s, 0, blockSize, order)
152
+ const div = 2 ** shift
153
+ for (let i = order; i < blockSize; i++) {
154
+ let sum = 0
155
+ for (let j = 0; j < order; j++) sum += coefs[j] * s[i - 1 - j]
156
+ s[i] += shift >= 0 ? Math.floor(sum / div) : sum * 2 ** -shift // arithmetic right shift == floor division
157
+ }
158
+ } else throw new Error('FLAC: reserved subframe type')
159
+ if (wasted) for (let i = 0; i < blockSize; i++) s[i] *= 2 ** wasted
160
+ return s
161
+ }
162
+
163
+ function decodeFlac(buf) {
164
+ if (buf.toString('latin1', 0, 4) !== 'fLaC') return undefined
165
+ let pos = 4
166
+ let streamBps = 0
167
+ let total = 0
168
+ while (pos + 4 <= buf.length) {
169
+ const h = buf[pos]
170
+ const len = (buf[pos + 1] << 16) | (buf[pos + 2] << 8) | buf[pos + 3]
171
+ if ((h & 0x7f) === 0 && len === 34) {
172
+ streamBps = ((buf[pos + 4 + 12] & 1) << 4) + (buf[pos + 4 + 13] >> 4) + 1
173
+ total = (buf[pos + 4 + 13] & 15) * 2 ** 32 + buf.readUInt32BE(pos + 4 + 14)
174
+ }
175
+ pos += 4 + len
176
+ if (h & 0x80) break
177
+ }
178
+ if (!streamBps) return undefined
179
+ const chunks = []
180
+ let count = 0
181
+ const br = new Bits(buf, pos)
182
+ while (br.bytePos + 6 < buf.length) {
183
+ const sync = br.read(14)
184
+ if (sync !== 0x3ffe) break // trailing garbage / end
185
+ br.read(2) // reserved + blocking strategy
186
+ const bsCode = br.read(4)
187
+ const srCode = br.read(4)
188
+ const chAssign = br.read(4)
189
+ const sizeCode = br.read(3)
190
+ br.read(1)
191
+ // coded frame/sample number: UTF-8 style, 1..7 bytes
192
+ const first = br.read(8)
193
+ let extra = first < 0x80 ? 0 : first < 0xe0 ? 1 : first < 0xf0 ? 2 : first < 0xf8 ? 3 : first < 0xfc ? 4 : first < 0xfe ? 5 : 6
194
+ while (extra-- > 0) br.read(8)
195
+ let blockSize = BLOCK_SIZES[bsCode]
196
+ if (bsCode === 6) blockSize = br.read(8) + 1
197
+ else if (bsCode === 7) blockSize = br.read(16) + 1
198
+ if (!blockSize) throw new Error('FLAC: bad block size')
199
+ if (srCode === 12) br.read(8)
200
+ else if (srCode === 13 || srCode === 14) br.read(16)
201
+ br.read(8) // header CRC-8
202
+ const bps = sizeCode === 0 ? streamBps : SAMPLE_BITS[sizeCode]
203
+ if (!bps) throw new Error('FLAC: reserved sample size')
204
+ const nch = chAssign < 8 ? chAssign + 1 : 2
205
+ const chans = []
206
+ for (let c = 0; c < nch; c++) {
207
+ // the side channel carries one extra bit
208
+ const extraBit = (chAssign === 8 && c === 1) || (chAssign === 9 && c === 0) || (chAssign === 10 && c === 1) ? 1 : 0
209
+ chans.push(readSubframe(br, blockSize, bps + extraBit))
210
+ }
211
+ br.align()
212
+ br.read(16) // frame CRC-16
213
+ // channel 0 after undoing inter-channel decorrelation
214
+ let ch0 = chans[0]
215
+ if (chAssign === 8) ch0 = chans[0] // left/side: channel 0 is left already
216
+ else if (chAssign === 9) {
217
+ ch0 = new Float64Array(blockSize) // side/right: left = side + right
218
+ for (let i = 0; i < blockSize; i++) ch0[i] = chans[0][i] + chans[1][i]
219
+ } else if (chAssign === 10) {
220
+ ch0 = new Float64Array(blockSize) // mid/side: left = (mid*2 + (side&1) + side) / 2
221
+ for (let i = 0; i < blockSize; i++) {
222
+ const side = chans[1][i]
223
+ const mid = chans[0][i] * 2 + (((side % 2) + 2) % 2)
224
+ ch0[i] = (mid + side) / 2 // exact: mid and side always have the same parity
225
+ }
226
+ }
227
+ const scale = 2 ** (bps - 1)
228
+ const f = new Float32Array(blockSize)
229
+ for (let i = 0; i < blockSize; i++) f[i] = ch0[i] / scale
230
+ chunks.push(f)
231
+ count += blockSize
232
+ }
233
+ const out = new Float32Array(count)
234
+ let o = 0
235
+ for (const c of chunks) {
236
+ out.set(c, o)
237
+ o += c.length
238
+ }
239
+ return total && count > total ? out.subarray(0, total) : out
240
+ }
241
+
242
+ /** @returns {Float32Array|undefined} first channel, or undefined if the container is not WAV/FLAC */
243
+ export function decodeChannel0(buffer) {
244
+ if (!Buffer.isBuffer(buffer)) buffer = Buffer.from(buffer)
245
+ if (buffer.length < 12) return undefined
246
+ try {
247
+ return decodeWav(buffer) ?? decodeFlac(buffer)
248
+ } catch {
249
+ return undefined
250
+ }
251
+ }
252
+
253
+ /**
254
+ * The 64-value voice-note waveform (0..100) — same algorithm as upstream's getAudioWaveform:
255
+ * 64 equal blocks, mean absolute amplitude per block, scaled so the loudest block is 100.
256
+ */
257
+ export function waveformFromSamples(rawData, samples = 64) {
258
+ const blockSize = Math.floor(rawData.length / samples)
259
+ const filtered = []
260
+ for (let i = 0; i < samples; i++) {
261
+ const blockStart = blockSize * i
262
+ let sum = 0
263
+ for (let j = 0; j < blockSize; j++) sum += Math.abs(rawData[blockStart + j])
264
+ filtered.push(sum / blockSize)
265
+ }
266
+ const multiplier = Math.pow(Math.max(...filtered), -1)
267
+ return new Uint8Array(filtered.map(n => n * multiplier).map(n => Math.floor(100 * n)))
268
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Minimal replacement for `@hapi/boom`.
3
+ * Baileys only ever does: `new Boom(message, { statusCode, data })`,
4
+ * `err instanceof Boom`, and reads `err.output.statusCode` / `err.data` / `err.isBoom`.
5
+ * That's the entire surface reproduced here.
6
+ */
7
+
8
+ const STATUS_TEXT = {
9
+ 400: 'Bad Request',
10
+ 401: 'Unauthorized',
11
+ 403: 'Forbidden',
12
+ 404: 'Not Found',
13
+ 408: 'Request Time-out',
14
+ 409: 'Conflict',
15
+ 411: 'Length Required',
16
+ 428: 'Precondition Required',
17
+ 440: 'Login Timeout',
18
+ 500: 'Internal Server Error',
19
+ 501: 'Not Implemented',
20
+ 503: 'Service Unavailable',
21
+ 515: 'Stream Error Code'
22
+ }
23
+
24
+ export class Boom extends Error {
25
+ constructor(message, options = {}) {
26
+ super(message || STATUS_TEXT[options.statusCode || 500] || 'Internal Server Error')
27
+ this.name = 'Boom'
28
+ Error.captureStackTrace?.(this, Boom)
29
+
30
+ const statusCode = options.statusCode || 500
31
+ this.isBoom = true
32
+ this.isServer = statusCode >= 500
33
+ this.data = options.data ?? null
34
+ this.output = {
35
+ statusCode,
36
+ payload: {
37
+ statusCode,
38
+ error: STATUS_TEXT[statusCode] || 'Error',
39
+ message: this.message
40
+ },
41
+ headers: {}
42
+ }
43
+ }
44
+ }
45
+
46
+ export const isBoom = err => err instanceof Error && !!err.isBoom
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Replaces `lru-cache` and `@cacheable/node-cache`.
3
+ *
4
+ * Covers exactly the surface Baileys uses against both libraries:
5
+ * get(key), set(key, value), has(key), delete(key), clear()/flushAll()
6
+ * with:
7
+ * - ttl (ms): entries expire after this long
8
+ * - max: hard cap on entry count (oldest inserted/refreshed evicted first)
9
+ * - updateAgeOnGet: a `get()` refreshes the entry's TTL clock (both libs support this)
10
+ * - dispose(value, key): called when an entry is evicted, whether by TTL or by `max`
11
+ *
12
+ * Built on a plain Map (insertion order == recency order once we re-insert on
13
+ * touch), with a lazy sweep instead of a per-entry timer so a cache with many
14
+ * short-lived entries doesn't spin up thousands of timers.
15
+ */
16
+
17
+ export class Cache {
18
+ constructor(options = {}) {
19
+ this.ttl = options.ttl ?? (options.stdTTL ? options.stdTTL * 1000 : 0) // stdTTL is node-cache's seconds-based option
20
+ this.max = options.max || Infinity
21
+ this.updateAgeOnGet = !!options.updateAgeOnGet
22
+ this.dispose = options.dispose || (() => {})
23
+ this._store = new Map() // key -> { value, expiresAt }
24
+
25
+ if (this.ttl > 0) {
26
+ this._sweeper = setInterval(() => this._sweep(), Math.min(this.ttl, 60_000))
27
+ this._sweeper.unref?.()
28
+ }
29
+ }
30
+
31
+ _isExpired(entry) {
32
+ return this.ttl > 0 && entry.expiresAt !== 0 && entry.expiresAt <= Date.now()
33
+ }
34
+
35
+ _sweep() {
36
+ const now = Date.now()
37
+ for (const [key, entry] of this._store) {
38
+ if (entry.expiresAt !== 0 && entry.expiresAt <= now) {
39
+ this._store.delete(key)
40
+ this.dispose(entry.value, key)
41
+ }
42
+ }
43
+ }
44
+
45
+ get(key) {
46
+ const entry = this._store.get(key)
47
+ if (!entry) return undefined
48
+ if (this._isExpired(entry)) {
49
+ this._store.delete(key)
50
+ this.dispose(entry.value, key)
51
+ return undefined
52
+ }
53
+ if (this.updateAgeOnGet && this.ttl > 0) {
54
+ entry.expiresAt = Date.now() + this.ttl
55
+ // re-insert to move to the back (most-recently-used) for `max` eviction order
56
+ this._store.delete(key)
57
+ this._store.set(key, entry)
58
+ }
59
+ return entry.value
60
+ }
61
+
62
+ set(key, value) {
63
+ if (this._store.has(key)) this._store.delete(key) // re-insert to refresh recency order
64
+ this._store.set(key, {
65
+ value,
66
+ expiresAt: this.ttl > 0 ? Date.now() + this.ttl : 0
67
+ })
68
+ while (this._store.size > this.max) {
69
+ const oldestKey = this._store.keys().next().value
70
+ const oldest = this._store.get(oldestKey)
71
+ this._store.delete(oldestKey)
72
+ this.dispose(oldest.value, oldestKey)
73
+ }
74
+ return true
75
+ }
76
+
77
+ has(key) {
78
+ const entry = this._store.get(key)
79
+ if (!entry) return false
80
+ if (this._isExpired(entry)) {
81
+ this._store.delete(key)
82
+ this.dispose(entry.value, key)
83
+ return false
84
+ }
85
+ return true
86
+ }
87
+
88
+ delete(key) {
89
+ const entry = this._store.get(key)
90
+ if (!entry) return false
91
+ this._store.delete(key)
92
+ this.dispose(entry.value, key)
93
+ return true
94
+ }
95
+
96
+ clear() {
97
+ for (const [key, entry] of this._store) this.dispose(entry.value, key)
98
+ this._store.clear()
99
+ }
100
+
101
+ // node-cache alias
102
+ flushAll() {
103
+ this.clear()
104
+ }
105
+
106
+ // node-cache alias: `del(key)` (Baileys calls this, e.g. msgRetryCache.del / placeholderResendCache.del)
107
+ del(key) {
108
+ return this.delete(key)
109
+ }
110
+
111
+ /** node-cache's close(): stop the background sweeper so the process can exit cleanly. */
112
+ close() {
113
+ if (this._sweeper) {
114
+ clearInterval(this._sweeper)
115
+ this._sweeper = undefined
116
+ }
117
+ }
118
+
119
+ /** node-cache's mget: returns { [key]: value } for keys that were found (and not expired). */
120
+ mget(keys) {
121
+ const result = {}
122
+ for (const key of keys) {
123
+ const value = this.get(key)
124
+ if (value !== undefined) result[key] = value
125
+ }
126
+ return result
127
+ }
128
+
129
+ /** node-cache's mset: data is an array of { key, value, ttl? } (ttl currently ignored — per-entry TTL override not needed by Baileys' usage). */
130
+ mset(data) {
131
+ for (const item of data) this.set(item.key, item.value)
132
+ return true
133
+ }
134
+
135
+ get size() {
136
+ return this._store.size
137
+ }
138
+ }
139
+
140
+ /** Factory mirroring `new LRUCache(opts)` / `new NodeCache(opts)` call sites. */
141
+ export const LRUCache = Cache
142
+ export const NodeCache = Cache
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Replaces `async-mutex` and `p-queue`.
3
+ *
4
+ * Every usage of both libraries in Baileys is a plain serial (concurrency = 1)
5
+ * task queue: run async tasks one at a time, in submission order, each waiting
6
+ * for the previous to settle. That's implementable with a single chained
7
+ * promise and no external dependency.
8
+ */
9
+
10
+ /** A single serial execution lane. */
11
+ class SerialQueue {
12
+ constructor() {
13
+ this._tail = Promise.resolve()
14
+ }
15
+
16
+ /** Run `task` once all previously-queued tasks have settled. Returns task's result/throw. */
17
+ run(task) {
18
+ const result = this._tail.then(() => task())
19
+ // swallow so a rejected task doesn't break the chain for the next task
20
+ this._tail = result.then(
21
+ () => undefined,
22
+ () => undefined
23
+ )
24
+ return result
25
+ }
26
+ }
27
+
28
+ /** Replacement for async-mutex's `Mutex`: mutex().runExclusive(fn) -> mutex(fn). */
29
+ export const makeMutex = () => {
30
+ const queue = new SerialQueue()
31
+ return {
32
+ mutex(task) {
33
+ return queue.run(task)
34
+ }
35
+ }
36
+ }
37
+
38
+ /** Replacement for a Map<key, Mutex>: one independent serial lane per key, garbage collected when idle. */
39
+ export const makeKeyedMutex = () => {
40
+ const lanes = new Map()
41
+ return {
42
+ async mutex(key, task) {
43
+ let entry = lanes.get(key)
44
+ if (!entry) {
45
+ entry = { queue: new SerialQueue(), refCount: 0 }
46
+ lanes.set(key, entry)
47
+ }
48
+ entry.refCount++
49
+ try {
50
+ return await entry.queue.run(task)
51
+ } finally {
52
+ entry.refCount--
53
+ if (entry.refCount === 0 && lanes.get(key) === entry) {
54
+ lanes.delete(key)
55
+ }
56
+ }
57
+ }
58
+ }
59
+ }
60
+
61
+ /**
62
+ * Replacement for `new PQueue({ concurrency: 1 })`.
63
+ * Only the `.add(fn)` API is used anywhere in Baileys, so that's all this covers.
64
+ */
65
+ export const makeSerialTaskQueue = () => {
66
+ const queue = new SerialQueue()
67
+ return {
68
+ add(task) {
69
+ return queue.run(task)
70
+ }
71
+ }
72
+ }
73
+
74
+ /** Map<key, serial task queue>, created lazily — used by PreKeyManager / auth key queues. */
75
+ export const makeKeyedSerialTaskQueues = () => {
76
+ const queues = new Map()
77
+ return {
78
+ get(key) {
79
+ let q = queues.get(key)
80
+ if (!q) {
81
+ q = makeSerialTaskQueue()
82
+ queues.set(key, q)
83
+ }
84
+ return q
85
+ }
86
+ }
87
+ }