@itznomo/baileys 0.0.0-stage → 0.0.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.
Files changed (124) hide show
  1. package/BUTTONS.md +153 -0
  2. package/Example/call-bot.mjs +38 -0
  3. package/Example/example.mjs +36 -0
  4. package/Example/full-bot-commands.mjs +319 -0
  5. package/Example/full-bot.mjs +77 -0
  6. package/LICENSE +21 -0
  7. package/README.md +543 -2
  8. package/WAProto/@dnuzi +1 -0
  9. package/WAProto/index.d.ts +15932 -0
  10. package/WAProto/index.js +113300 -0
  11. package/assets/banner.svg +17 -0
  12. package/assets/devider.svg +1 -0
  13. package/assets/features.svg +21 -0
  14. package/docs/CALLS.md +106 -0
  15. package/docs/FEATURES.md +1152 -0
  16. package/engine-requirements.js +19 -0
  17. package/index.d.ts +815 -0
  18. package/package.json +51 -4
  19. package/src/binary/wa-binary-constants.js +1300 -0
  20. package/src/binary/wa-binary.js +627 -0
  21. package/src/constants.js +147 -0
  22. package/src/defaults.js +106 -0
  23. package/src/foundation/ai-rich.js +654 -0
  24. package/src/foundation/audio-duration.js +470 -0
  25. package/src/foundation/audio-samples.js +250 -0
  26. package/src/foundation/boom.js +39 -0
  27. package/src/foundation/builders.js +851 -0
  28. package/src/foundation/cache.js +134 -0
  29. package/src/foundation/concurrency.js +69 -0
  30. package/src/foundation/curve25519.js +189 -0
  31. package/src/foundation/image-thumb.js +65 -0
  32. package/src/foundation/link-preview.js +278 -0
  33. package/src/foundation/logger.js +78 -0
  34. package/src/foundation/long.js +130 -0
  35. package/src/foundation/performance.js +385 -0
  36. package/src/foundation/protobuf-minimal.js +587 -0
  37. package/src/foundation/qrcode-terminal.js +273 -0
  38. package/src/foundation/sql-database.js +716 -0
  39. package/src/foundation/wa-crypto.js +47 -0
  40. package/src/foundation/zip.js +108 -0
  41. package/src/index.js +67 -0
  42. package/src/signal/libsignal.js +996 -0
  43. package/src/signal/signal-group.js +455 -0
  44. package/src/signal/signal-repository.js +635 -0
  45. package/src/socket/business-communities.js +811 -0
  46. package/src/socket/chats.js +702 -0
  47. package/src/socket/groups-newsletter.js +524 -0
  48. package/src/socket/messages-recv.js +1815 -0
  49. package/src/socket/messages-send.js +1526 -0
  50. package/src/socket/socket-builder.js +131 -0
  51. package/src/socket/socket-core.js +913 -0
  52. package/src/socket/usync.js +287 -0
  53. package/src/socket-client/native-websocket.js +344 -0
  54. package/src/socket-client/websocket-client.js +170 -0
  55. package/src/utils/auth-state-core.js +731 -0
  56. package/src/utils/auth-state-storage.js +594 -0
  57. package/src/utils/chat-sync.js +1046 -0
  58. package/src/utils/check-status.js +159 -0
  59. package/src/utils/cstoken.js +17 -0
  60. package/src/utils/media.js +807 -0
  61. package/src/utils/message-compose.js +1747 -0
  62. package/src/utils/message-processing.js +912 -0
  63. package/src/utils/modern-messages.js +435 -0
  64. package/src/utils/nomo-buttons.js +138 -0
  65. package/src/utils/nomo-commands.js +168 -0
  66. package/src/utils/spam-report-utils.js +136 -0
  67. package/src/utils/use-keyv-auth-state.js +307 -0
  68. package/src/utils/username.js +19 -0
  69. package/src/utils/wa-protocol-core.js +1227 -0
  70. package/src/voip/WaVoipCoordinator.js +158 -0
  71. package/src/voip/app-data/WaAppDataStream.js +193 -0
  72. package/src/voip/app-data/protocol.js +172 -0
  73. package/src/voip/auto.js +139 -0
  74. package/src/voip/bytes.js +63 -0
  75. package/src/voip/call/WaCallManager.js +442 -0
  76. package/src/voip/call/WaCallMediaSession.js +1727 -0
  77. package/src/voip/call/call-state.js +203 -0
  78. package/src/voip/crypto/encryption.js +13 -0
  79. package/src/voip/crypto/primitives.js +21 -0
  80. package/src/voip/crypto/rtcp.js +66 -0
  81. package/src/voip/crypto/srtp.js +180 -0
  82. package/src/voip/crypto/ssrc.js +15 -0
  83. package/src/voip/index.js +730 -0
  84. package/src/voip/media/WaAudioEngine.js +486 -0
  85. package/src/voip/media/WaVideoEngine.js +275 -0
  86. package/src/voip/media/audio-codec.js +0 -0
  87. package/src/voip/media/audio-reorder.js +107 -0
  88. package/src/voip/media/h264.js +246 -0
  89. package/src/voip/media/mlow-codec.js +465 -0
  90. package/src/voip/media/rtcp.js +68 -0
  91. package/src/voip/media/rtp.js +242 -0
  92. package/src/voip/protobuf.js +30 -0
  93. package/src/voip/relay/WaManualRelay.js +609 -0
  94. package/src/voip/relay/datachannel/pre-negotiated.js +25 -0
  95. package/src/voip/relay/dtls/aead.js +46 -0
  96. package/src/voip/relay/dtls/cert-builder.js +102 -0
  97. package/src/voip/relay/dtls/der.js +98 -0
  98. package/src/voip/relay/dtls/ecdhe.js +37 -0
  99. package/src/voip/relay/dtls/handshake-framing.js +100 -0
  100. package/src/voip/relay/dtls/handshake-messages.js +158 -0
  101. package/src/voip/relay/dtls/handshake.js +582 -0
  102. package/src/voip/relay/dtls/prf.js +39 -0
  103. package/src/voip/relay/dtls/record.js +56 -0
  104. package/src/voip/relay/relay-ack.js +141 -0
  105. package/src/voip/relay/sctp/association.js +434 -0
  106. package/src/voip/relay/sctp/crc32c.js +21 -0
  107. package/src/voip/relay/sctp/wire.js +226 -0
  108. package/src/voip/relay/stun.js +463 -0
  109. package/src/voip/shim/baileys-resolve.js +7 -0
  110. package/src/voip/shim/core.js +66 -0
  111. package/src/voip/shim/crypto.js +6 -0
  112. package/src/voip/shim/proto.js +10 -0
  113. package/src/voip/shim/protocol.js +130 -0
  114. package/src/voip/shim/transport.js +82 -0
  115. package/src/voip/shim/util.js +207 -0
  116. package/src/voip/signaling/bridge.js +102 -0
  117. package/src/voip/signaling/screen-share.js +60 -0
  118. package/src/voip/signaling/signaling.js +491 -0
  119. package/src/voip/types.js +69 -0
  120. package/src/voip/voip-deps.js +243 -0
  121. package/src/voip/voipClient.js +314 -0
  122. package/src/wam/wam-constants.js +22852 -0
  123. package/src/wam/wam.js +146 -0
  124. package/voip.d.ts +144 -0
@@ -0,0 +1,627 @@
1
+ import { promisify } from 'node:util'
2
+ import { inflate } from 'node:zlib'
3
+ import { randomBytes } from 'node:crypto'
4
+ import { Boom } from '../foundation/boom.js'
5
+ import * as constants from './wa-binary-constants.js'
6
+
7
+ export const S_WHATSAPP_NET = '@s.whatsapp.net'
8
+ export const OFFICIAL_BIZ_JID = '16505361212@c.us'
9
+ export const SERVER_JID = 'server@c.us'
10
+ export const PSA_WID = '0@c.us'
11
+ export const STORIES_JID = 'status@broadcast'
12
+ export const META_AI_JID = '13135550002@c.us'
13
+
14
+ export const WAJIDDomains = {
15
+ WHATSAPP: 0,
16
+ LID: 1,
17
+ HOSTED: 128,
18
+ HOSTED_LID: 129
19
+ }
20
+
21
+ export const getServerFromDomainType = (initialServer, domainType) => {
22
+ switch (domainType) {
23
+ case WAJIDDomains.LID:
24
+ return 'lid'
25
+ case WAJIDDomains.HOSTED:
26
+ return 'hosted'
27
+ case WAJIDDomains.HOSTED_LID:
28
+ return 'hosted.lid'
29
+ case WAJIDDomains.WHATSAPP:
30
+ default:
31
+ return initialServer
32
+ }
33
+ }
34
+
35
+ export const jidEncode = (user, server, device, agent) =>
36
+ `${user || ''}${agent ? `_${agent}` : ''}${device ? `:${device}` : ''}@${server || 'lid'}`
37
+
38
+ export const jidDecode = jid => {
39
+ const sepIdx = typeof jid === 'string' ? jid.indexOf('@') : -1
40
+ if (sepIdx < 0) return undefined
41
+
42
+ const server = jid.slice(sepIdx + 1)
43
+ const userCombined = jid.slice(0, sepIdx)
44
+ const [userAgent, device] = userCombined.split(':')
45
+ const [user, agent] = userAgent.split('_')
46
+
47
+ let domainType = WAJIDDomains.WHATSAPP
48
+ if (server === 'lid') domainType = WAJIDDomains.LID
49
+ else if (server === 'hosted') domainType = WAJIDDomains.HOSTED
50
+ else if (server === 'hosted.lid') domainType = WAJIDDomains.HOSTED_LID
51
+ else if (agent) domainType = parseInt(agent)
52
+
53
+ return { server, user, domainType, device: device ? +device : undefined }
54
+ }
55
+
56
+ export const areJidsSameUser = (jid1, jid2) => jidDecode(jid1)?.user === jidDecode(jid2)?.user
57
+ export const isJidMetaAI = jid => jid?.endsWith('@bot')
58
+ export const isPnUser = jid => jid?.endsWith('@s.whatsapp.net')
59
+ export const isLidUser = jid => jid?.endsWith('@lid')
60
+ export const isJidBroadcast = jid => jid?.endsWith('@broadcast')
61
+ export const isJidGroup = jid => jid?.endsWith('@g.us')
62
+ export const isJidStatusBroadcast = jid => jid === 'status@broadcast'
63
+ export const isJidNewsletter = jid => jid?.endsWith('@newsletter')
64
+ export const isHostedPnUser = jid => jid?.endsWith('@hosted')
65
+ export const isHostedLidUser = jid => jid?.endsWith('@hosted.lid')
66
+
67
+ const BOT_JID_RE = /^1313555\d{4}$|^131655500\d{2}$/
68
+ export const isJidBot = jid => jid && BOT_JID_RE.test(jid.split('@')[0]) && jid.endsWith('@c.us')
69
+
70
+ export const jidNormalizedUser = jid => {
71
+ const result = jidDecode(jid)
72
+ if (!result) return ''
73
+ const { user, server } = result
74
+ return jidEncode(user, server === 'c.us' ? 's.whatsapp.net' : server)
75
+ }
76
+
77
+ export const transferDevice = (fromJid, toJid) => {
78
+ const fromDecoded = jidDecode(fromJid)
79
+ const deviceId = fromDecoded?.device || 0
80
+ const { server, user } = jidDecode(toJid)
81
+ return jidEncode(user, server, deviceId)
82
+ }
83
+
84
+ export const encodeBinaryNode = (node, opts = constants, buffer = [0]) => {
85
+ const encoded = encodeBinaryNodeInner(node, opts, buffer)
86
+ return Buffer.from(encoded)
87
+ }
88
+
89
+ const encodeBinaryNodeInner = ({ tag, attrs, content }, opts, buffer) => {
90
+ const { TAGS, TOKEN_MAP } = opts
91
+
92
+ const pushByte = value => buffer.push(value & 0xff)
93
+ const pushInt = (value, n, littleEndian = false) => {
94
+ for (let i = 0; i < n; i++) {
95
+ const curShift = littleEndian ? i : n - 1 - i
96
+ buffer.push((value >> (curShift * 8)) & 0xff)
97
+ }
98
+ }
99
+ const pushBytes = bytes => {
100
+ for (const b of bytes) buffer.push(b)
101
+ }
102
+ const pushInt16 = value => pushBytes([(value >> 8) & 0xff, value & 0xff])
103
+ const pushInt20 = value => pushBytes([(value >> 16) & 0x0f, (value >> 8) & 0xff, value & 0xff])
104
+
105
+ const writeByteLength = length => {
106
+ if (length >= 4294967296) throw new Error('string too large to encode: ' + length)
107
+ if (length >= 1 << 20) {
108
+ pushByte(TAGS.BINARY_32)
109
+ pushInt(length, 4)
110
+ } else if (length >= 256) {
111
+ pushByte(TAGS.BINARY_20)
112
+ pushInt20(length)
113
+ } else {
114
+ pushByte(TAGS.BINARY_8)
115
+ pushByte(length)
116
+ }
117
+ }
118
+
119
+ const writeStringRaw = str => {
120
+ const bytes = Buffer.from(str, 'utf-8')
121
+ writeByteLength(bytes.length)
122
+ pushBytes(bytes)
123
+ }
124
+
125
+ const writeJid = ({ domainType, device, user, server }) => {
126
+ if (typeof device !== 'undefined') {
127
+ pushByte(TAGS.AD_JID)
128
+ pushByte(domainType || 0)
129
+ pushByte(device || 0)
130
+ writeString(user)
131
+ } else {
132
+ pushByte(TAGS.JID_PAIR)
133
+ if (user.length) writeString(user)
134
+ else pushByte(TAGS.LIST_EMPTY)
135
+ writeString(server)
136
+ }
137
+ }
138
+
139
+ const packNibble = char => {
140
+ switch (char) {
141
+ case '-':
142
+ return 10
143
+ case '.':
144
+ return 11
145
+ case '\0':
146
+ return 15
147
+ default:
148
+ if (char >= '0' && char <= '9') return char.charCodeAt(0) - '0'.charCodeAt(0)
149
+ throw new Error(`invalid byte for nibble "${char}"`)
150
+ }
151
+ }
152
+
153
+ const packHex = char => {
154
+ if (char >= '0' && char <= '9') return char.charCodeAt(0) - '0'.charCodeAt(0)
155
+ if (char >= 'A' && char <= 'F') return 10 + char.charCodeAt(0) - 'A'.charCodeAt(0)
156
+ if (char >= 'a' && char <= 'f') return 10 + char.charCodeAt(0) - 'a'.charCodeAt(0)
157
+ if (char === '\0') return 15
158
+ throw new Error(`Invalid hex char "${char}"`)
159
+ }
160
+
161
+ const writePackedBytes = (str, type) => {
162
+ if (str.length > TAGS.PACKED_MAX) throw new Error('Too many bytes to pack')
163
+ pushByte(type === 'nibble' ? TAGS.NIBBLE_8 : TAGS.HEX_8)
164
+ let roundedLength = Math.ceil(str.length / 2.0)
165
+ if (str.length % 2 !== 0) roundedLength |= 128
166
+ pushByte(roundedLength)
167
+ const packFunction = type === 'nibble' ? packNibble : packHex
168
+ const packBytePair = (v1, v2) => (packFunction(v1) << 4) | packFunction(v2)
169
+ const strLengthHalf = Math.floor(str.length / 2)
170
+ for (let i = 0; i < strLengthHalf; i++) pushByte(packBytePair(str[2 * i], str[2 * i + 1]))
171
+ if (str.length % 2 !== 0) pushByte(packBytePair(str[str.length - 1], '\x00'))
172
+ }
173
+
174
+ const isNibble = str => {
175
+ if (!str || str.length > TAGS.PACKED_MAX) return false
176
+ for (const char of str) {
177
+ const isInNibbleRange = char >= '0' && char <= '9'
178
+ if (!isInNibbleRange && char !== '-' && char !== '.') return false
179
+ }
180
+ return true
181
+ }
182
+
183
+ const isHex = str => {
184
+ if (!str || str.length > TAGS.PACKED_MAX) return false
185
+ for (const char of str) {
186
+ const isInNibbleRange = char >= '0' && char <= '9'
187
+ if (!isInNibbleRange && !(char >= 'A' && char <= 'F')) return false
188
+ }
189
+ return true
190
+ }
191
+
192
+ const writeString = str => {
193
+ if (str === undefined || str === null) {
194
+ pushByte(TAGS.LIST_EMPTY)
195
+ return
196
+ }
197
+ if (str === '') {
198
+ writeStringRaw(str)
199
+ return
200
+ }
201
+ const tokenIndex = TOKEN_MAP[str]
202
+ if (tokenIndex) {
203
+ if (typeof tokenIndex.dict === 'number') pushByte(TAGS.DICTIONARY_0 + tokenIndex.dict)
204
+ pushByte(tokenIndex.index)
205
+ } else if (isNibble(str)) {
206
+ writePackedBytes(str, 'nibble')
207
+ } else if (isHex(str)) {
208
+ writePackedBytes(str, 'hex')
209
+ } else {
210
+ const decodedJid = jidDecode(str)
211
+ if (decodedJid) writeJid(decodedJid)
212
+ else writeStringRaw(str)
213
+ }
214
+ }
215
+
216
+ const writeListStart = listSize => {
217
+ if (listSize === 0) pushByte(TAGS.LIST_EMPTY)
218
+ else if (listSize < 256) pushBytes([TAGS.LIST_8, listSize])
219
+ else {
220
+ pushByte(TAGS.LIST_16)
221
+ pushInt16(listSize)
222
+ }
223
+ }
224
+
225
+ if (!tag) throw new Error('Invalid node: tag cannot be undefined')
226
+
227
+ const validAttributes = Object.keys(attrs || {}).filter(k => typeof attrs[k] !== 'undefined' && attrs[k] !== null)
228
+ writeListStart(2 * validAttributes.length + 1 + (typeof content !== 'undefined' ? 1 : 0))
229
+ writeString(tag)
230
+ for (const key of validAttributes) {
231
+ if (typeof attrs[key] === 'string') {
232
+ writeString(key)
233
+ writeString(attrs[key])
234
+ }
235
+ }
236
+
237
+ if (typeof content === 'string') {
238
+ writeString(content)
239
+ } else if (Buffer.isBuffer(content) || content instanceof Uint8Array) {
240
+ writeByteLength(content.length)
241
+ pushBytes(content)
242
+ } else if (Array.isArray(content)) {
243
+ const validContent = content.filter(
244
+ item => item && (item.tag || Buffer.isBuffer(item) || item instanceof Uint8Array || typeof item === 'string')
245
+ )
246
+ writeListStart(validContent.length)
247
+ for (const item of validContent) encodeBinaryNodeInner(item, opts, buffer)
248
+ } else if (typeof content === 'undefined') {
249
+
250
+ } else {
251
+ throw new Error(`invalid children for header "${tag}": ${content} (${typeof content})`)
252
+ }
253
+
254
+ return buffer
255
+ }
256
+
257
+ const inflatePromise = promisify(inflate)
258
+
259
+ export const decompressingIfRequired = async buffer => {
260
+ if (2 & buffer.readUInt8()) {
261
+ buffer = await inflatePromise(buffer.slice(1))
262
+ } else {
263
+ buffer = buffer.slice(1)
264
+ }
265
+ return buffer
266
+ }
267
+
268
+ export const decodeDecompressedBinaryNode = (buffer, opts, indexRef = { index: 0 }) => {
269
+ const { DOUBLE_BYTE_TOKENS, SINGLE_BYTE_TOKENS, TAGS } = opts
270
+
271
+ const checkEOS = length => {
272
+ if (indexRef.index + length > buffer.length) throw new Error('end of stream')
273
+ }
274
+ const next = () => {
275
+ const value = buffer[indexRef.index]
276
+ indexRef.index += 1
277
+ return value
278
+ }
279
+ const readByte = () => {
280
+ checkEOS(1)
281
+ return next()
282
+ }
283
+ const readBytes = n => {
284
+ checkEOS(n)
285
+ const value = buffer.slice(indexRef.index, indexRef.index + n)
286
+ indexRef.index += n
287
+ return value
288
+ }
289
+ const readStringFromChars = length => readBytes(length).toString('utf-8')
290
+ const readInt = (n, littleEndian = false) => {
291
+ checkEOS(n)
292
+ let val = 0
293
+ for (let i = 0; i < n; i++) {
294
+ const shift = littleEndian ? i : n - 1 - i
295
+ val |= next() << (shift * 8)
296
+ }
297
+ return val
298
+ }
299
+ const readInt20 = () => {
300
+ checkEOS(3)
301
+ return ((next() & 15) << 16) + (next() << 8) + next()
302
+ }
303
+
304
+ const unpackHex = value => {
305
+ if (value >= 0 && value < 16) return value < 10 ? '0'.charCodeAt(0) + value : 'A'.charCodeAt(0) + value - 10
306
+ throw new Error('invalid hex: ' + value)
307
+ }
308
+ const unpackNibble = value => {
309
+ if (value >= 0 && value <= 9) return '0'.charCodeAt(0) + value
310
+ switch (value) {
311
+ case 10:
312
+ return '-'.charCodeAt(0)
313
+ case 11:
314
+ return '.'.charCodeAt(0)
315
+ case 15:
316
+ return '\0'.charCodeAt(0)
317
+ default:
318
+ throw new Error('invalid nibble: ' + value)
319
+ }
320
+ }
321
+ const unpackByte = (tag, value) => {
322
+ if (tag === TAGS.NIBBLE_8) return unpackNibble(value)
323
+ if (tag === TAGS.HEX_8) return unpackHex(value)
324
+ throw new Error('unknown tag: ' + tag)
325
+ }
326
+ const readPacked8 = tag => {
327
+ const startByte = readByte()
328
+ let value = ''
329
+ for (let i = 0; i < (startByte & 127); i++) {
330
+ const curByte = readByte()
331
+ value += String.fromCharCode(unpackByte(tag, (curByte & 0xf0) >> 4))
332
+ value += String.fromCharCode(unpackByte(tag, curByte & 0x0f))
333
+ }
334
+ if (startByte >> 7 !== 0) value = value.slice(0, -1)
335
+ return value
336
+ }
337
+
338
+ const isListTag = tag => tag === TAGS.LIST_EMPTY || tag === TAGS.LIST_8 || tag === TAGS.LIST_16
339
+ const readListSize = tag => {
340
+ switch (tag) {
341
+ case TAGS.LIST_EMPTY:
342
+ return 0
343
+ case TAGS.LIST_8:
344
+ return readByte()
345
+ case TAGS.LIST_16:
346
+ return readInt(2)
347
+ default:
348
+ throw new Error('invalid tag for list size: ' + tag)
349
+ }
350
+ }
351
+
352
+ const readJidPair = () => {
353
+ const i = readString(readByte())
354
+ const j = readString(readByte())
355
+ if (j) return (i || '') + '@' + j
356
+ throw new Error('invalid jid pair: ' + i + ', ' + j)
357
+ }
358
+ const readAdJid = () => {
359
+ const domainType = Number(readByte())
360
+ const device = readByte()
361
+ const user = readString(readByte())
362
+ let server = 's.whatsapp.net'
363
+ if (domainType === WAJIDDomains.LID) server = 'lid'
364
+ else if (domainType === WAJIDDomains.HOSTED) server = 'hosted'
365
+ else if (domainType === WAJIDDomains.HOSTED_LID) server = 'hosted.lid'
366
+ return jidEncode(user, server, device)
367
+ }
368
+ const readFbJid = () => {
369
+ const user = readString(readByte())
370
+ const device = readInt(2)
371
+ const server = readString(readByte())
372
+ return `${user}:${device}@${server}`
373
+ }
374
+ const readInteropJid = () => {
375
+ const user = readString(readByte())
376
+ const device = readInt(2)
377
+ const integrator = readInt(2)
378
+ let server = 'interop'
379
+ const beforeServer = indexRef.index
380
+ try {
381
+ server = readString(readByte())
382
+ } catch {
383
+ indexRef.index = beforeServer
384
+ }
385
+ return `${integrator}-${user}:${device}@${server}`
386
+ }
387
+
388
+ const readString = tag => {
389
+ if (tag >= 1 && tag < SINGLE_BYTE_TOKENS.length) return SINGLE_BYTE_TOKENS[tag] || ''
390
+ switch (tag) {
391
+ case TAGS.DICTIONARY_0:
392
+ case TAGS.DICTIONARY_1:
393
+ case TAGS.DICTIONARY_2:
394
+ case TAGS.DICTIONARY_3:
395
+ return getTokenDouble(tag - TAGS.DICTIONARY_0, readByte())
396
+ case TAGS.LIST_EMPTY:
397
+ return ''
398
+ case TAGS.BINARY_8:
399
+ return readStringFromChars(readByte())
400
+ case TAGS.BINARY_20:
401
+ return readStringFromChars(readInt20())
402
+ case TAGS.BINARY_32:
403
+ return readStringFromChars(readInt(4))
404
+ case TAGS.JID_PAIR:
405
+ return readJidPair()
406
+ case TAGS.FB_JID:
407
+ return readFbJid()
408
+ case TAGS.INTEROP_JID:
409
+ return readInteropJid()
410
+ case TAGS.AD_JID:
411
+ return readAdJid()
412
+ case TAGS.HEX_8:
413
+ case TAGS.NIBBLE_8:
414
+ return readPacked8(tag)
415
+ default:
416
+ throw new Error('invalid string with tag: ' + tag)
417
+ }
418
+ }
419
+
420
+ const readList = tag => {
421
+ const items = []
422
+ const size = readListSize(tag)
423
+ for (let i = 0; i < size; i++) items.push(decodeDecompressedBinaryNode(buffer, opts, indexRef))
424
+ return items
425
+ }
426
+
427
+ const getTokenDouble = (index1, index2) => {
428
+ const dict = DOUBLE_BYTE_TOKENS[index1]
429
+ if (!dict) throw new Error(`Invalid double token dict (${index1})`)
430
+ const value = dict[index2]
431
+ if (typeof value === 'undefined') throw new Error(`Invalid double token (${index2})`)
432
+ return value
433
+ }
434
+
435
+ const listSize = readListSize(readByte())
436
+ const header = readString(readByte())
437
+ if (!listSize || !header.length) throw new Error('invalid node')
438
+
439
+ const attrs = {}
440
+ let data
441
+
442
+ const attributesLength = (listSize - 1) >> 1
443
+ for (let i = 0; i < attributesLength; i++) {
444
+ const key = readString(readByte())
445
+ const value = readString(readByte())
446
+ attrs[key] = value
447
+ }
448
+
449
+ if (listSize % 2 === 0) {
450
+ const tag = readByte()
451
+ if (isListTag(tag)) {
452
+ data = readList(tag)
453
+ } else {
454
+ switch (tag) {
455
+ case TAGS.BINARY_8:
456
+ data = readBytes(readByte())
457
+ break
458
+ case TAGS.BINARY_20:
459
+ data = readBytes(readInt20())
460
+ break
461
+ case TAGS.BINARY_32:
462
+ data = readBytes(readInt(4))
463
+ break
464
+ default:
465
+ data = readString(tag)
466
+ break
467
+ }
468
+ }
469
+ }
470
+
471
+ return { tag: header, attrs, content: data }
472
+ }
473
+
474
+ export const decodeBinaryNode = async buff => {
475
+ const decompBuff = await decompressingIfRequired(buff)
476
+ return decodeDecompressedBinaryNode(decompBuff, constants)
477
+ }
478
+
479
+ const indexCache = new WeakMap()
480
+
481
+ export const getBinaryNodeChildren = (node, childTag) => {
482
+ if (!node || !Array.isArray(node.content)) return []
483
+ let index = indexCache.get(node)
484
+ if (!index) {
485
+ index = new Map()
486
+ for (const child of node.content) {
487
+ let arr = index.get(child.tag)
488
+ if (!arr) index.set(child.tag, (arr = []))
489
+ arr.push(child)
490
+ }
491
+ indexCache.set(node, index)
492
+ }
493
+ return index.get(childTag) || []
494
+ }
495
+
496
+ export const getBinaryNodeChild = (node, childTag) => getBinaryNodeChildren(node, childTag)[0]
497
+
498
+ export const getAllBinaryNodeChildren = ({ content }) => (Array.isArray(content) ? content : [])
499
+
500
+ export const getBinaryNodeChildBuffer = (node, childTag) => {
501
+ const child = getBinaryNodeChild(node, childTag)?.content
502
+ if (Buffer.isBuffer(child) || child instanceof Uint8Array) return child
503
+ }
504
+
505
+ export const getBinaryNodeChildString = (node, childTag) => {
506
+ const child = getBinaryNodeChild(node, childTag)?.content
507
+ if (Buffer.isBuffer(child) || child instanceof Uint8Array) return Buffer.from(child).toString('utf-8')
508
+ if (typeof child === 'string') return child
509
+ }
510
+
511
+ const bufferToUInt = (e, t) => {
512
+ let a = 0
513
+ for (let i = 0; i < t; i++) a = 256 * a + e[i]
514
+ return a
515
+ }
516
+
517
+ export const getBinaryNodeChildUInt = (node, childTag, length) => {
518
+ const buff = getBinaryNodeChildBuffer(node, childTag)
519
+ if (buff) return bufferToUInt(buff, length)
520
+ }
521
+
522
+ export const assertNodeErrorFree = node => {
523
+ const errNode = getBinaryNodeChild(node, 'error')
524
+ if (errNode) throw new Boom(errNode.attrs.text || 'Unknown error', { data: +errNode.attrs.code })
525
+ }
526
+
527
+ export const reduceBinaryNodeToDictionary = (node, tag) => {
528
+ const nodes = getBinaryNodeChildren(node, tag)
529
+ return nodes.reduce((dict, { attrs }) => {
530
+ if (typeof attrs.name === 'string') dict[attrs.name] = attrs.value || attrs.config_value
531
+ else dict[attrs.config_code] = attrs.value || attrs.config_value
532
+ return dict
533
+ }, {})
534
+ }
535
+
536
+ export const getBinaryNodeMessages = ({ content }, proto) => {
537
+ const msgs = []
538
+ if (Array.isArray(content)) {
539
+ for (const item of content) {
540
+ if (item.tag === 'message') msgs.push(proto.WebMessageInfo.decode(item.content).toJSON())
541
+ }
542
+ }
543
+ return msgs
544
+ }
545
+
546
+ const tabs = n => '\t'.repeat(n)
547
+ export function binaryNodeToString(node, i = 0) {
548
+ if (!node) return node
549
+ if (typeof node === 'string') return tabs(i) + node
550
+ if (node instanceof Uint8Array) return tabs(i) + Buffer.from(node).toString('hex')
551
+ if (Array.isArray(node)) return node.map(x => tabs(i + 1) + binaryNodeToString(x, i + 1)).join('\n')
552
+
553
+ const children = binaryNodeToString(node.content, i + 1)
554
+ const tag = `<${node.tag} ${Object.entries(node.attrs || {})
555
+ .filter(([, v]) => v !== undefined)
556
+ .map(([k, v]) => `${k}='${v}'`)
557
+ .join(' ')}`
558
+ const content = children ? `>\n${children}\n${tabs(i)}</${node.tag}>` : '/>'
559
+ return tag + content
560
+ }
561
+
562
+ const FLOWS_MAP = {
563
+ mpm: true,
564
+ cta_catalog: true,
565
+ send_location: true,
566
+ call_permission_request: true,
567
+ wa_payment_transaction_details: true,
568
+ automated_greeting_message_view_catalog: true
569
+ }
570
+ const DECISION_SOURCE_CONTENT = [{ tag: 'decision_source', attrs: { value: 'df' } }]
571
+ const LIST_TYPE_CONTENT = { tag: 'list', attrs: { v: '2', type: 'product_list' } }
572
+ const NATIVE_FLOW_ATTRIBUTE = { type: 'native_flow', v: '1' }
573
+ const MIXED_NATIVE_FLOW = {
574
+ tag: 'interactive',
575
+ attrs: NATIVE_FLOW_ATTRIBUTE,
576
+ content: [{ tag: 'native_flow', attrs: { v: '9', name: 'mixed' } }]
577
+ }
578
+
579
+ export const getBizBinaryNode = message => {
580
+ const flowMsg = message.interactiveMessage?.nativeFlowMessage
581
+ const firstButtonName = flowMsg?.buttons?.[0]?.name
582
+ const qualityContent = {
583
+ tag: 'quality_control',
584
+ attrs: {
585
+ decision_id: randomBytes(20).toString('hex'),
586
+ source_type: 'third_party'
587
+ },
588
+ content: DECISION_SOURCE_CONTENT
589
+ }
590
+ const bizAttributes = {
591
+ actual_actors: '2',
592
+ host_storage: '2',
593
+ privacy_mode_ts: `${(Date.now() / 1_000) | 0}`
594
+ }
595
+
596
+ if (firstButtonName === 'review_and_pay' || firstButtonName === 'payment_info') {
597
+ bizAttributes.native_flow_name = firstButtonName === 'review_and_pay' ? 'order_details' : firstButtonName
598
+ return { tag: 'biz', attrs: bizAttributes, content: [qualityContent] }
599
+ }
600
+
601
+ if (firstButtonName && FLOWS_MAP[firstButtonName]) {
602
+ return {
603
+ tag: 'biz',
604
+ attrs: bizAttributes,
605
+ content: [
606
+ {
607
+ tag: 'interactive',
608
+ attrs: NATIVE_FLOW_ATTRIBUTE,
609
+ content: [{ tag: 'native_flow', attrs: { v: '2', name: firstButtonName } }]
610
+ },
611
+ qualityContent
612
+ ]
613
+ }
614
+ }
615
+
616
+ if (flowMsg || message.interactiveMessage?.carouselMessage || message.buttonsMessage || message.templateMessage) {
617
+ return { tag: 'biz', attrs: bizAttributes, content: [MIXED_NATIVE_FLOW, qualityContent] }
618
+ }
619
+
620
+ if (message.listMessage) {
621
+ return { tag: 'biz', attrs: bizAttributes, content: [LIST_TYPE_CONTENT, qualityContent] }
622
+ }
623
+
624
+ return { tag: 'biz', attrs: bizAttributes, content: [qualityContent] }
625
+ }
626
+
627
+ export { constants as WA_BINARY_CONSTANTS }