@yannajah/baileys 0.0.0-stage → 1.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 (145) hide show
  1. package/LICENSE +23 -0
  2. package/LICENSE.jexkcode +21 -0
  3. package/README.md +41 -2
  4. package/THIRD_PARTY_NOTICES.md +15 -0
  5. package/WAProto/index.d.ts +16922 -0
  6. package/WAProto/index.js +122451 -0
  7. package/engine-requirements.js +10 -0
  8. package/lib/Defaults/baileys-version.json +3 -0
  9. package/lib/Defaults/index.js +156 -0
  10. package/lib/Defaults/phonenumber-mcc.json +223 -0
  11. package/lib/Signal/Group/ciphertext-message.js +15 -0
  12. package/lib/Signal/Group/group-session-builder.js +64 -0
  13. package/lib/Signal/Group/group_cipher.js +96 -0
  14. package/lib/Signal/Group/index.js +57 -0
  15. package/lib/Signal/Group/keyhelper.js +55 -0
  16. package/lib/Signal/Group/queue-job.js +57 -0
  17. package/lib/Signal/Group/sender-chain-key.js +34 -0
  18. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  19. package/lib/Signal/Group/sender-key-message.js +69 -0
  20. package/lib/Signal/Group/sender-key-name.js +51 -0
  21. package/lib/Signal/Group/sender-key-record.js +53 -0
  22. package/lib/Signal/Group/sender-key-state.js +99 -0
  23. package/lib/Signal/Group/sender-message-key.js +29 -0
  24. package/lib/Signal/libsignal.js +174 -0
  25. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  26. package/lib/Socket/Client/index.js +19 -0
  27. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  28. package/lib/Socket/Client/web-socket-client.js +87 -0
  29. package/lib/Socket/business.js +260 -0
  30. package/lib/Socket/chats.js +1002 -0
  31. package/lib/Socket/clutch-handler.d.ts +27 -0
  32. package/lib/Socket/clutch-handler.js +880 -0
  33. package/lib/Socket/groups.js +317 -0
  34. package/lib/Socket/index.js +97 -0
  35. package/lib/Socket/messages-recv.js +1154 -0
  36. package/lib/Socket/messages-send.js +946 -0
  37. package/lib/Socket/newsletter.js +411 -0
  38. package/lib/Socket/registration.js +166 -0
  39. package/lib/Socket/socket.js +688 -0
  40. package/lib/Socket/usync.js +70 -0
  41. package/lib/Store/index.js +10 -0
  42. package/lib/Store/make-cache-manager-store.js +83 -0
  43. package/lib/Store/make-in-memory-store.js +457 -0
  44. package/lib/Store/make-ordered-dictionary.js +81 -0
  45. package/lib/Store/object-repository.js +27 -0
  46. package/lib/Types/Auth.js +2 -0
  47. package/lib/Types/Call.js +2 -0
  48. package/lib/Types/Chat.js +4 -0
  49. package/lib/Types/Contact.js +2 -0
  50. package/lib/Types/Events.js +2 -0
  51. package/lib/Types/GroupMetadata.js +2 -0
  52. package/lib/Types/Label.js +27 -0
  53. package/lib/Types/LabelAssociation.js +9 -0
  54. package/lib/Types/Message.js +10 -0
  55. package/lib/Types/Mex.d.ts +2 -0
  56. package/lib/Types/Mex.js +98 -0
  57. package/lib/Types/Newsletter.js +41 -0
  58. package/lib/Types/Product.js +2 -0
  59. package/lib/Types/Signal.js +2 -0
  60. package/lib/Types/Socket.js +2 -0
  61. package/lib/Types/State.js +2 -0
  62. package/lib/Types/USync.js +2 -0
  63. package/lib/Types/index.js +43 -0
  64. package/lib/Utils/MessageBuilder.d.ts +215 -0
  65. package/lib/Utils/MessageBuilder.js +4001 -0
  66. package/lib/Utils/a2ui.d.ts +202 -0
  67. package/lib/Utils/a2ui.js +770 -0
  68. package/lib/Utils/auth-utils.js +206 -0
  69. package/lib/Utils/baileys-event-stream.js +63 -0
  70. package/lib/Utils/bot-signature.d.ts +22 -0
  71. package/lib/Utils/bot-signature.js +125 -0
  72. package/lib/Utils/business.js +234 -0
  73. package/lib/Utils/channel-manager.d.ts +39 -0
  74. package/lib/Utils/channel-manager.js +312 -0
  75. package/lib/Utils/chat-utils.js +729 -0
  76. package/lib/Utils/crypto.js +151 -0
  77. package/lib/Utils/decode-wa-message.js +198 -0
  78. package/lib/Utils/event-buffer.js +514 -0
  79. package/lib/Utils/extras.d.ts +449 -0
  80. package/lib/Utils/extras.js +1377 -0
  81. package/lib/Utils/generics.js +574 -0
  82. package/lib/Utils/history.js +96 -0
  83. package/lib/Utils/html-app.d.ts +39 -0
  84. package/lib/Utils/html-app.js +307 -0
  85. package/lib/Utils/index.d.ts +23 -0
  86. package/lib/Utils/index.js +51 -0
  87. package/lib/Utils/link-preview.js +93 -0
  88. package/lib/Utils/logger.js +7 -0
  89. package/lib/Utils/lt-hash.js +51 -0
  90. package/lib/Utils/make-mutex.js +43 -0
  91. package/lib/Utils/message-retry-manager.d.ts +42 -0
  92. package/lib/Utils/message-retry-manager.js +309 -0
  93. package/lib/Utils/messages-media.js +861 -0
  94. package/lib/Utils/messages.js +1085 -0
  95. package/lib/Utils/metaai.d.ts +438 -0
  96. package/lib/Utils/metaai.js +911 -0
  97. package/lib/Utils/mini-app.d.ts +93 -0
  98. package/lib/Utils/mini-app.js +453 -0
  99. package/lib/Utils/modern-messages.d.ts +150 -0
  100. package/lib/Utils/modern-messages.js +498 -0
  101. package/lib/Utils/native-flow.d.ts +14 -0
  102. package/lib/Utils/native-flow.js +122 -0
  103. package/lib/Utils/newsletter-status.d.ts +163 -0
  104. package/lib/Utils/newsletter-status.js +695 -0
  105. package/lib/Utils/noise-handler.js +155 -0
  106. package/lib/Utils/payment-messages.d.ts +59 -0
  107. package/lib/Utils/payment-messages.js +164 -0
  108. package/lib/Utils/process-message.js +334 -0
  109. package/lib/Utils/reporting-utils.d.ts +12 -0
  110. package/lib/Utils/reporting-utils.js +271 -0
  111. package/lib/Utils/scheduled-message.d.ts +82 -0
  112. package/lib/Utils/scheduled-message.js +126 -0
  113. package/lib/Utils/signal.js +153 -0
  114. package/lib/Utils/spr.d.ts +26 -0
  115. package/lib/Utils/spr.js +525 -0
  116. package/lib/Utils/status-stickers.d.ts +78 -0
  117. package/lib/Utils/status-stickers.js +275 -0
  118. package/lib/Utils/telegram-adapter.d.ts +28 -0
  119. package/lib/Utils/telegram-adapter.js +285 -0
  120. package/lib/Utils/use-multi-file-auth-state.js +153 -0
  121. package/lib/Utils/validate-connection.js +235 -0
  122. package/lib/WABinary/constants.js +40 -0
  123. package/lib/WABinary/decode.js +252 -0
  124. package/lib/WABinary/encode.js +265 -0
  125. package/lib/WABinary/generic-utils.js +178 -0
  126. package/lib/WABinary/index.js +21 -0
  127. package/lib/WABinary/jid-utils.js +81 -0
  128. package/lib/WABinary/types.js +2 -0
  129. package/lib/WAM/BinaryInfo.js +13 -0
  130. package/lib/WAM/constants.js +15350 -0
  131. package/lib/WAM/encode.js +155 -0
  132. package/lib/WAM/index.js +19 -0
  133. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  134. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  135. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  136. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  137. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  138. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  139. package/lib/WAUSync/Protocols/index.js +20 -0
  140. package/lib/WAUSync/USyncQuery.js +89 -0
  141. package/lib/WAUSync/USyncUser.js +26 -0
  142. package/lib/WAUSync/index.js +19 -0
  143. package/lib/index.d.ts +20 -0
  144. package/lib/index.js +99 -0
  145. package/package.json +110 -4
@@ -0,0 +1,695 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const { proto } = require("../../WAProto");
4
+ const { encodeNewsletterMessage, generateMessageIDV2 } = require("./generics");
5
+ const { generateWAMessage, normalizeMessageContent } = require("./messages");
6
+ const { prepareModernMessageContent } = require("./modern-messages");
7
+ const { WAMessageStatus } = require("../Types/Message");
8
+ const { getBinaryNodeChild, getBinaryNodeChildren, S_WHATSAPP_NET } = require("../WABinary");
9
+ const { isJidNewsLetter } = require("../WABinary/jid-utils");
10
+ const isJidNewsletter = isJidNewsLetter;
11
+
12
+ const NEWSLETTER_STATUS_MEDIA_TYPES = new Set(['audio', 'gif', 'image', 'video'])
13
+ const NEWSLETTER_STATUS_WEB_MEDIA_TYPES = new Set(['image', 'video'])
14
+ const NEWSLETTER_STATUS_INTERACTIONS = new Set(['question', 'question_response', 'question_reshare'])
15
+ const NEWSLETTER_STATUS_CONTENT_TYPES = new Set(['text', 'media', 'reaction'])
16
+ const NEWSLETTER_STATUS_CALLBACK_EVENTS = ['CB:ack', 'CB:status', 'CB:iq', 'CB:notification', 'CB:message']
17
+ const NEWSLETTER_STATUS_EDIT_REACTION_REVOKE = '7'
18
+ const NEWSLETTER_STATUS_EDIT_ADMIN_REVOKE = '8'
19
+ const NEWSLETTER_STATUS_ACK_CLASS = 'status'
20
+ const NEWSLETTER_STATUS_ACK_TIMEOUT_MS = 20000
21
+ const NEWSLETTER_STATUS_SERVER_ID_TIMEOUT_MS = 8000
22
+
23
+ const getNewsletterStatusMediaType = exports.getNewsletterStatusMediaType = message => {
24
+ const content = normalizeMessageContent(message)
25
+ if (content?.imageMessage) return 'image'
26
+ if (content?.videoMessage) return content.videoMessage.gifPlayback ? 'gif' : 'video'
27
+ if (content?.audioMessage) return 'audio'
28
+ return undefined
29
+ }
30
+
31
+ const assertNewsletterJid = jid => {
32
+ if (!isJidNewsletter(jid)) throw new TypeError('Newsletter status target must be a @newsletter JID')
33
+ }
34
+
35
+ const assertInteraction = interactionType => {
36
+ if (interactionType !== undefined && !NEWSLETTER_STATUS_INTERACTIONS.has(interactionType)) {
37
+ throw new TypeError(`Unsupported newsletter status interaction: ${interactionType}`)
38
+ }
39
+ }
40
+
41
+ const assertMediaType = mediaType => {
42
+ if (mediaType !== undefined && !NEWSLETTER_STATUS_MEDIA_TYPES.has(mediaType)) {
43
+ throw new TypeError(`Unsupported newsletter status media type: ${mediaType}`)
44
+ }
45
+ }
46
+
47
+ const isPresent = value => value !== undefined && value !== null && value !== ''
48
+
49
+ const NEWSLETTER_SERVER_ID_MIN = exports.NEWSLETTER_SERVER_ID_MIN = 99
50
+ const NEWSLETTER_SERVER_ID_MAX = exports.NEWSLETTER_SERVER_ID_MAX = 2147476647
51
+
52
+ const toNewsletterServerId = exports.toNewsletterServerId = (value, label) => {
53
+ const parsed = typeof value === 'number' ? value : Number(String(value).trim())
54
+ if (!Number.isInteger(parsed) || parsed < NEWSLETTER_SERVER_ID_MIN || parsed > NEWSLETTER_SERVER_ID_MAX) {
55
+ throw new TypeError(`${JSON.stringify(value)} is not a newsletter server id${label ? ` for ${label}` : ''}; the server accepts ${NEWSLETTER_SERVER_ID_MIN}..${NEWSLETTER_SERVER_ID_MAX}, and you get one from newsletterFetchMessages or a sent status`)
56
+ }
57
+ return String(parsed)
58
+ }
59
+
60
+ const toServerId = (value, label) => toNewsletterServerId(value, label)
61
+
62
+ const buildMetaNode = ({ interactionType, parentServerId, responseServerId, aiContent }) => {
63
+ assertInteraction(interactionType)
64
+
65
+ const attrs = {}
66
+ if (interactionType) {
67
+ attrs.interaction_type = interactionType
68
+ if (interactionType === 'question_reshare') {
69
+ if (!isPresent(parentServerId)) throw new TypeError('question_reshare requires parentServerId')
70
+ if (!isPresent(responseServerId)) throw new TypeError('question_reshare requires responseServerId')
71
+ attrs.parent_server_id = toServerId(parentServerId, 'parentServerId')
72
+ attrs.response_server_id = String(responseServerId)
73
+ }
74
+ else if (interactionType === 'question_response' && isPresent(responseServerId)) {
75
+ attrs.response_server_id = String(responseServerId)
76
+ }
77
+ }
78
+
79
+ if (!interactionType && !aiContent) return undefined
80
+
81
+ return {
82
+ tag: 'meta',
83
+ attrs,
84
+ content: aiContent ? [{ tag: 'ai_content', attrs: {}, content: undefined }] : undefined
85
+ }
86
+ }
87
+
88
+ const withNewsletterStatusAttribution = exports.withNewsletterStatusAttribution = content => ({
89
+ ...content,
90
+ contextInfo: {
91
+ statusAttributions: [{ type: proto.StatusAttribution.Type.NEWSLETTER_STATUS }],
92
+ featureEligibilities: { canBeReshared: true },
93
+ ...(content?.contextInfo || {})
94
+ }
95
+ })
96
+
97
+ const snapshotCallbackNode = (event, node) => ({
98
+ event,
99
+ tag: node?.tag,
100
+ attrs: node?.attrs || {},
101
+ children: Array.isArray(node?.content)
102
+ ? node.content.map(child => ({ tag: child?.tag, attrs: child?.attrs || {} }))
103
+ : []
104
+ })
105
+
106
+ const collectStatusCallbacks = sock => {
107
+ const frames = []
108
+ const listeners = []
109
+ if (!sock?.ws?.on) {
110
+ return { frames, stop: () => {} }
111
+ }
112
+
113
+ for (const event of NEWSLETTER_STATUS_CALLBACK_EVENTS) {
114
+ const listener = node => {
115
+ if (frames.length >= 40) return
116
+ frames.push(snapshotCallbackNode(event, node))
117
+ }
118
+ sock.ws.on(event, listener)
119
+ listeners.push([event, listener])
120
+ }
121
+
122
+ return {
123
+ frames,
124
+ stop: () => {
125
+ for (const [event, listener] of listeners) {
126
+ sock.ws?.off?.(event, listener)
127
+ }
128
+ }
129
+ }
130
+ }
131
+
132
+ const readIntAttr = (attrs, key) => {
133
+ if (!isPresent(attrs?.[key])) return undefined
134
+ const parsed = Number.parseInt(String(attrs[key]), 10)
135
+ return Number.isFinite(parsed) ? parsed : undefined
136
+ }
137
+
138
+ const parseNewsletterStatusAck = exports.parseNewsletterStatusAck = (node, { jid, messageId } = {}) => {
139
+ if (!node || typeof node !== 'object') throw new TypeError('Newsletter status ack node is required')
140
+ if (node.tag !== 'ack') {
141
+ const error = new Error(`Newsletter status expected <ack>, got <${node.tag}>`)
142
+ error.data = node
143
+ throw error
144
+ }
145
+
146
+ const attrs = node.attrs || {}
147
+ if (attrs.class !== undefined && attrs.class !== NEWSLETTER_STATUS_ACK_CLASS) {
148
+ const error = new Error(`Newsletter status ack has class "${attrs.class}", expected "${NEWSLETTER_STATUS_ACK_CLASS}"`)
149
+ error.data = node
150
+ throw error
151
+ }
152
+ if (isPresent(messageId) && isPresent(attrs.id) && attrs.id !== messageId) {
153
+ const error = new Error(`Newsletter status ack id mismatch: ${attrs.id} != ${messageId}`)
154
+ error.data = node
155
+ throw error
156
+ }
157
+ if (isPresent(jid) && isPresent(attrs.from) && attrs.from !== jid) {
158
+ const error = new Error(`Newsletter status ack from mismatch: ${attrs.from} != ${jid}`)
159
+ error.data = node
160
+ throw error
161
+ }
162
+
163
+ return {
164
+ class: attrs.class,
165
+ from: attrs.from,
166
+ id: attrs.id,
167
+ t: readIntAttr(attrs, 't'),
168
+ serverId: readIntAttr(attrs, 'server_id'),
169
+ edit: attrs.edit,
170
+ error: isPresent(attrs.error) ? String(attrs.error) : undefined,
171
+ applicationError: readIntAttr(attrs, 'application_error'),
172
+ backoff: readIntAttr(attrs, 'backoff'),
173
+ node
174
+ }
175
+ }
176
+
177
+ /**
178
+ * The ack carries from, class, id and t, and nothing else. The server id lands
179
+ * separately, in the <status> stanza the server sends back to the publisher --
180
+ * WASmaxInStatusDeliverFromNewsletterMixin reads from, server_id, t and
181
+ * is_sender off exactly that tag. Reacting to or revoking your own status needs
182
+ * that id, so wait a moment for the echo rather than returning undefined.
183
+ */
184
+ const waitForNewsletterStatusServerId = exports.waitForNewsletterStatusServerId = (sock, { jid, messageId, timeoutMs = 8000 }) => {
185
+ let settle
186
+ const promise = new Promise(resolve => {
187
+ let done = false
188
+ const finish = value => {
189
+ if (done) return
190
+ done = true
191
+ clearTimeout(timer)
192
+ sock.ws.off('CB:status', onStatus)
193
+ resolve(value)
194
+ }
195
+ const onStatus = node => {
196
+ if (node?.tag !== 'status') return
197
+ const attrs = node.attrs || {}
198
+ if (isPresent(jid) && isPresent(attrs.from) && attrs.from !== jid) return
199
+ if (isPresent(messageId) && isPresent(attrs.id) && attrs.id !== messageId) return
200
+ const serverId = readIntAttr(attrs, 'server_id')
201
+ if (serverId !== undefined) finish({ serverId, node })
202
+ }
203
+ const timer = setTimeout(() => finish(undefined), timeoutMs)
204
+ sock.ws.on('CB:status', onStatus)
205
+ settle = finish
206
+ })
207
+ promise.cancel = () => settle(undefined)
208
+ return promise
209
+ }
210
+
211
+ const assertStatusServerResponse = (response, { jid, messageId, callbacks = [] }) => {
212
+ if (!response) {
213
+ const suffix = callbacks.length
214
+ ? `; callbacks=${JSON.stringify(callbacks)}`
215
+ : '; no ack/status/iq/notification/message callback observed'
216
+ const error = new Error(`Newsletter status server ACK timed out for ${messageId}${suffix}`)
217
+ error.data = { messageId, callbacks }
218
+ throw error
219
+ }
220
+
221
+ const ack = parseNewsletterStatusAck(response, { jid, messageId })
222
+ if (ack.error) {
223
+ const details = [
224
+ ack.applicationError !== undefined ? `application_error=${ack.applicationError}` : undefined,
225
+ ack.backoff !== undefined ? `backoff=${ack.backoff}` : undefined
226
+ ].filter(Boolean).join(', ')
227
+ const hint = ack.error === '403' || ack.error === '401' || ack.error === 'not-authorized' || ack.error === 'forbidden'
228
+ ? '; the channel may be missing the CHANNEL_STATUS_PRODUCER capability, check newsletterCanPostStatus(jid)'
229
+ : ''
230
+ const error = new Error(`Newsletter status rejected by server (${ack.error})${details ? `: ${details}` : ''}${hint}`)
231
+ error.data = ack
232
+ throw error
233
+ }
234
+
235
+ return ack
236
+ }
237
+
238
+ const buildNewsletterAdminProfileStatusMessage = exports.buildNewsletterAdminProfileStatusMessage = message => {
239
+ if (!message || typeof message !== 'object') throw new TypeError('Newsletter status message is required')
240
+ return proto.Message.create({
241
+ newsletterAdminProfileStatusMessage: proto.Message.FutureProofMessage.create({
242
+ message
243
+ })
244
+ })
245
+ }
246
+
247
+ const resolveStatusPayload = ({ message, payload }) => {
248
+ if (payload !== undefined) {
249
+ if (!(payload instanceof Uint8Array)) throw new TypeError('Newsletter status payload must be a Uint8Array')
250
+ return payload
251
+ }
252
+ if (!message || typeof message !== 'object') throw new TypeError('Newsletter status message is required')
253
+ return encodeNewsletterMessage(message)
254
+ }
255
+
256
+ const buildNewsletterStatusNode = exports.buildNewsletterStatusNode = ({
257
+ jid,
258
+ message,
259
+ payload,
260
+ messageId,
261
+ mediaType,
262
+ mediaId,
263
+ mediaHandle,
264
+ parentServerId,
265
+ responseServerId,
266
+ interactionType,
267
+ aiContent
268
+ }) => {
269
+ assertNewsletterJid(jid)
270
+ if (!messageId) throw new TypeError('Newsletter status messageId is required')
271
+ assertMediaType(mediaType)
272
+ assertInteraction(interactionType)
273
+
274
+ const handle = isPresent(mediaHandle) ? mediaHandle : mediaId
275
+ if (isPresent(handle) && !mediaType) {
276
+ throw new TypeError('mediaId requires a media newsletter status')
277
+ }
278
+ if (mediaType && !isPresent(handle)) {
279
+ throw new TypeError('Native newsletter status media requires the media handle returned by the newsletter upload')
280
+ }
281
+ if (interactionType === 'question_reshare' && !mediaType) {
282
+ throw new TypeError('question_reshare requires media')
283
+ }
284
+ if (interactionType === 'question_response') {
285
+ if (mediaType) throw new TypeError('question_response is published as a text status')
286
+ if (!isPresent(parentServerId)) throw new TypeError('question_response requires parentServerId')
287
+ }
288
+
289
+ const attrs = {
290
+ to: jid,
291
+ id: messageId,
292
+ type: mediaType ? 'media' : 'text'
293
+ }
294
+ if (mediaType) attrs.media_id = String(handle)
295
+ if (interactionType === 'question_response') {
296
+ attrs.server_id = toServerId(parentServerId, 'parentServerId')
297
+ }
298
+
299
+ const content = [{
300
+ tag: 'plaintext',
301
+ attrs: mediaType ? { mediatype: mediaType } : {},
302
+ content: resolveStatusPayload({ message, payload })
303
+ }]
304
+
305
+ const metaNode = buildMetaNode({ interactionType, parentServerId, responseServerId, aiContent })
306
+ if (metaNode) content.push(metaNode)
307
+
308
+ return { tag: 'status', attrs, content }
309
+ }
310
+
311
+ const buildNewsletterStatusReactionNode = exports.buildNewsletterStatusReactionNode = ({ jid, messageId, parentServerId, reaction }) => {
312
+ assertNewsletterJid(jid)
313
+ if (!messageId) throw new TypeError('Newsletter status reaction messageId is required')
314
+ if (!isPresent(parentServerId)) {
315
+ throw new TypeError('Newsletter status reaction requires parentServerId')
316
+ }
317
+
318
+ const isRevoke = !isPresent(reaction)
319
+ const attrs = {
320
+ to: jid,
321
+ id: messageId,
322
+ server_id: toServerId(parentServerId, 'parentServerId'),
323
+ type: 'reaction'
324
+ }
325
+ if (isRevoke) attrs.edit = NEWSLETTER_STATUS_EDIT_REACTION_REVOKE
326
+
327
+ return {
328
+ tag: 'status',
329
+ attrs,
330
+ content: [{
331
+ tag: 'reaction',
332
+ attrs: isRevoke ? {} : { code: reaction },
333
+ content: undefined
334
+ }]
335
+ }
336
+ }
337
+
338
+ const buildNewsletterStatusRevokeNode = exports.buildNewsletterStatusRevokeNode = ({ jid, statusId }) => {
339
+ assertNewsletterJid(jid)
340
+ if (!statusId) throw new TypeError('Newsletter status revoke requires the status id')
341
+
342
+ return {
343
+ tag: 'status',
344
+ attrs: {
345
+ to: jid,
346
+ id: statusId,
347
+ type: 'text',
348
+ edit: NEWSLETTER_STATUS_EDIT_ADMIN_REVOKE
349
+ },
350
+ content: [{ tag: 'plaintext', attrs: {}, content: undefined }]
351
+ }
352
+ }
353
+
354
+ const sendStatusNode = async (sock, node, { jid, messageId, timeoutMs }) => {
355
+ const diagnostics = collectStatusCallbacks(sock)
356
+ const responsePromise = sock.waitForMessage(messageId, timeoutMs)
357
+
358
+ try {
359
+ await sock.sendNode(node)
360
+ const response = await responsePromise
361
+ return assertStatusServerResponse(response, { jid, messageId, callbacks: diagnostics.frames })
362
+ }
363
+ finally {
364
+ diagnostics.stop()
365
+ }
366
+ }
367
+
368
+ const makeNewsletterStatusSender = exports.makeNewsletterStatusSender = (sock, config) => async (jid, content, options = {}) => {
369
+ assertNewsletterJid(jid)
370
+ if (!content || typeof content !== 'object' || Array.isArray(content)) {
371
+ throw new TypeError('Newsletter status content must be an object')
372
+ }
373
+
374
+ const userJid = sock.authState?.creds?.me?.id
375
+ if (!userJid) throw new TypeError('Not authenticated')
376
+
377
+ const {
378
+ mediaId,
379
+ mediaHandle: requestedMediaHandle,
380
+ parentServerId,
381
+ responseServerId,
382
+ interactionType: requestedInteractionType,
383
+ aiContent,
384
+ statusAttribution = true,
385
+ messageId: requestedMessageId,
386
+ ackTimeoutMs,
387
+ resolveServerId,
388
+ serverIdTimeoutMs,
389
+ transport,
390
+ ...messageOptions
391
+ } = options
392
+
393
+ if (transport !== undefined) {
394
+ config?.logger?.warn?.({ transport }, 'newsletter status "transport" option is obsolete, the verified status-publish transport is always used')
395
+ }
396
+
397
+ let uploadedMediaHandle
398
+ const upload = async (...args) => {
399
+ const result = await sock.waUploadToServer(...args)
400
+ if (args[1]?.newsletter) {
401
+ uploadedMediaHandle = result?.handle ?? result?.media_id ?? result?.mediaId ?? result?.fbid ?? uploadedMediaHandle
402
+ }
403
+ return result
404
+ }
405
+
406
+ const preparedContent = prepareModernMessageContent(content)
407
+ const fullMsg = await generateWAMessage(jid, statusAttribution ? withNewsletterStatusAttribution(preparedContent) : preparedContent, {
408
+ logger: config?.logger,
409
+ userJid,
410
+ upload,
411
+ mediaCache: config?.mediaCache,
412
+ options: config?.options,
413
+ ...messageOptions,
414
+ messageId: requestedMessageId || generateMessageIDV2(userJid)
415
+ })
416
+
417
+ const normalized = normalizeMessageContent(fullMsg.message)
418
+ const mediaType = getNewsletterStatusMediaType(fullMsg.message)
419
+ if (!mediaType && (normalized?.documentMessage || normalized?.stickerMessage)) {
420
+ throw new TypeError('Native newsletter status supports text, image, video, gif, and audio')
421
+ }
422
+ if (mediaType && !NEWSLETTER_STATUS_WEB_MEDIA_TYPES.has(mediaType)) {
423
+ config?.logger?.warn?.({ mediaType }, 'newsletter status media type is not published by WhatsApp Web itself, the server may reject it')
424
+ }
425
+
426
+ const interactionType = requestedInteractionType || (content.question ? 'question' : undefined)
427
+ if (interactionType === 'question' && !mediaType) {
428
+ config?.logger?.warn?.('WhatsApp Web only publishes question newsletter statuses on top of media, a text question status may be rejected')
429
+ }
430
+
431
+ const node = buildNewsletterStatusNode({
432
+ jid,
433
+ message: fullMsg.message,
434
+ messageId: fullMsg.key.id,
435
+ mediaType,
436
+ mediaHandle: requestedMediaHandle ?? mediaId ?? uploadedMediaHandle,
437
+ parentServerId,
438
+ responseServerId,
439
+ interactionType,
440
+ aiContent
441
+ })
442
+
443
+ const echo = resolveServerId === false
444
+ ? null
445
+ : waitForNewsletterStatusServerId(sock, {
446
+ jid,
447
+ messageId: fullMsg.key.id,
448
+ timeoutMs: serverIdTimeoutMs ?? NEWSLETTER_STATUS_SERVER_ID_TIMEOUT_MS
449
+ })
450
+
451
+ let ack
452
+ try {
453
+ ack = await sendStatusNode(sock, node, {
454
+ jid,
455
+ messageId: fullMsg.key.id,
456
+ timeoutMs: ackTimeoutMs ?? NEWSLETTER_STATUS_ACK_TIMEOUT_MS
457
+ })
458
+ }
459
+ catch (error) {
460
+ echo?.cancel()
461
+ throw error
462
+ }
463
+
464
+ const delivered = echo ? await echo : undefined
465
+
466
+ fullMsg.status = WAMessageStatus.SERVER_ACK
467
+ fullMsg.newsletterStatusServerId = ack.serverId ?? delivered?.serverId
468
+ fullMsg.newsletterStatusAck = ack
469
+ fullMsg.newsletterStatusResponse = ack.node
470
+ if (delivered) fullMsg.newsletterStatusDelivered = delivered.node
471
+ return fullMsg
472
+ }
473
+
474
+ const makeNewsletterStatusReactionSender = exports.makeNewsletterStatusReactionSender = sock => async (jid, parentServerId, reaction, options = {}) => {
475
+ assertNewsletterJid(jid)
476
+ const userJid = sock.authState?.creds?.me?.id
477
+ if (!userJid) throw new TypeError('Not authenticated')
478
+
479
+ const messageId = options.messageId || generateMessageIDV2(userJid)
480
+ const node = buildNewsletterStatusReactionNode({ jid, messageId, parentServerId, reaction })
481
+ const ack = await sendStatusNode(sock, node, {
482
+ jid,
483
+ messageId,
484
+ timeoutMs: options.ackTimeoutMs ?? NEWSLETTER_STATUS_ACK_TIMEOUT_MS
485
+ })
486
+
487
+ return {
488
+ key: {
489
+ remoteJid: jid,
490
+ fromMe: true,
491
+ id: messageId
492
+ },
493
+ status: WAMessageStatus.SERVER_ACK,
494
+ newsletterStatusServerId: ack.serverId,
495
+ newsletterStatusAck: ack,
496
+ newsletterStatusResponse: ack.node
497
+ }
498
+ }
499
+
500
+ const makeNewsletterStatusRevokeSender = exports.makeNewsletterStatusRevokeSender = sock => async (jid, statusId, options = {}) => {
501
+ assertNewsletterJid(jid)
502
+ const userJid = sock.authState?.creds?.me?.id
503
+ if (!userJid) throw new TypeError('Not authenticated')
504
+
505
+ const node = buildNewsletterStatusRevokeNode({ jid, statusId })
506
+ const ack = await sendStatusNode(sock, node, {
507
+ jid,
508
+ messageId: statusId,
509
+ timeoutMs: options.ackTimeoutMs ?? NEWSLETTER_STATUS_ACK_TIMEOUT_MS
510
+ })
511
+
512
+ return {
513
+ key: {
514
+ remoteJid: jid,
515
+ fromMe: true,
516
+ id: statusId
517
+ },
518
+ status: WAMessageStatus.SERVER_ACK,
519
+ newsletterStatusAck: ack,
520
+ newsletterStatusResponse: ack.node
521
+ }
522
+ }
523
+
524
+ const decodeStatusPayload = plaintext => {
525
+ const bytes = plaintext?.content
526
+ if (!bytes || Array.isArray(bytes)) return undefined
527
+ return proto.Message.decode(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes))
528
+ }
529
+
530
+ const parseStatusAdminProfile = meta => {
531
+ const adminProfile = meta && getBinaryNodeChild(meta, 'admin_profile')
532
+ if (!adminProfile) return undefined
533
+
534
+ const name = getBinaryNodeChild(adminProfile, 'name')
535
+ const picture = getBinaryNodeChild(adminProfile, 'picture')
536
+ const content = name?.content
537
+ return {
538
+ id: adminProfile.attrs?.id,
539
+ name: typeof content === 'string'
540
+ ? content
541
+ : content instanceof Uint8Array
542
+ ? Buffer.from(content).toString('utf-8')
543
+ : undefined,
544
+ pictureId: picture?.attrs?.id,
545
+ pictureDirectPath: picture?.attrs?.direct_path
546
+ }
547
+ }
548
+
549
+ const parseStatusNode = status => {
550
+ const plaintext = getBinaryNodeChild(status, 'plaintext')
551
+ const reaction = getBinaryNodeChild(status, 'reaction')
552
+ const meta = getBinaryNodeChild(status, 'meta')
553
+ const reactions = getBinaryNodeChild(status, 'reactions')
554
+ const viewsCount = getBinaryNodeChild(status, 'views_count')
555
+ const responsesCount = getBinaryNodeChild(status, 'responses_count')
556
+ return {
557
+ id: status.attrs?.id,
558
+ serverId: readIntAttr(status.attrs, 'server_id'),
559
+ t: readIntAttr(status.attrs, 't'),
560
+ isSender: status.attrs?.is_sender === 'true',
561
+ type: status.attrs?.type,
562
+ edit: status.attrs?.edit,
563
+ mediaType: plaintext?.attrs?.mediatype,
564
+ interactionType: meta?.attrs?.interaction_type,
565
+ reaction: reaction ? reaction.attrs?.code ?? '' : undefined,
566
+ adminProfile: parseStatusAdminProfile(meta),
567
+ paidPartnership: meta ? !!getBinaryNodeChild(meta, 'paid_partnership') : false,
568
+ aiContent: meta ? !!getBinaryNodeChild(meta, 'ai_content') : false,
569
+ editTimestamp: readIntAttr(meta?.attrs, 'msg_edit_t'),
570
+ originalTimestamp: readIntAttr(meta?.attrs, 'original_msg_t'),
571
+ reactionCounts: reactions
572
+ ? getBinaryNodeChildren(reactions, 'reaction').map(entry => ({
573
+ code: entry.attrs?.code,
574
+ count: readIntAttr(entry.attrs, 'count')
575
+ }))
576
+ : undefined,
577
+ viewsCount: readIntAttr(viewsCount?.attrs, 'count'),
578
+ responsesCount: readIntAttr(responsesCount?.attrs, 'count'),
579
+ message: decodeStatusPayload(plaintext),
580
+ node: status
581
+ }
582
+ }
583
+
584
+ const parseNewsletterStatusUpdatesResponse = exports.parseNewsletterStatusUpdatesResponse = node => {
585
+ const updates = getBinaryNodeChild(node, 'status_updates')
586
+ if (!updates) {
587
+ const children = Array.isArray(node?.content) ? node.content.map(child => child?.tag) : []
588
+ const error = new Error(`Newsletter status updates response has no <status_updates> child, got [${children.join(', ')}]`)
589
+ error.data = node
590
+ throw error
591
+ }
592
+
593
+ return parseNewsletterStatusesResponse(updates)
594
+ }
595
+
596
+ const makeNewsletterStatusUpdatesFetcher = exports.makeNewsletterStatusUpdatesFetcher = sock => async (jid, options = {}) => {
597
+ assertNewsletterJid(jid)
598
+
599
+ const { count = 20, since, before, after } = options
600
+ const attrs = { count: String(count) }
601
+ if (isPresent(since)) attrs.since = String(since)
602
+ if (isPresent(before)) attrs.before = toServerId(before, 'before')
603
+ else if (isPresent(after)) attrs.after = toServerId(after, 'after')
604
+
605
+ const result = await sock.query({
606
+ tag: 'iq',
607
+ attrs: {
608
+ to: jid,
609
+ xmlns: 'newsletter',
610
+ type: 'get'
611
+ },
612
+ content: [{ tag: 'status_updates', attrs, content: undefined }]
613
+ })
614
+
615
+ return parseNewsletterStatusUpdatesResponse(result)
616
+ }
617
+
618
+ const parseNewsletterStatusesResponse = exports.parseNewsletterStatusesResponse = node => {
619
+ const statuses = getBinaryNodeChild(node, 'statuses')
620
+ if (!statuses) {
621
+ const children = Array.isArray(node?.content) ? node.content.map(child => child?.tag) : []
622
+ const error = new Error(`Newsletter statuses response has no <statuses> child, got [${children.join(', ')}]`)
623
+ error.data = node
624
+ throw error
625
+ }
626
+
627
+ return {
628
+ jid: statuses.attrs?.jid,
629
+ t: readIntAttr(statuses.attrs, 't'),
630
+ statuses: getBinaryNodeChildren(statuses, 'status').map(parseStatusNode)
631
+ }
632
+ }
633
+
634
+ const makeNewsletterStatusFetcher = exports.makeNewsletterStatusFetcher = sock => async (jid, options = {}) => {
635
+ assertNewsletterJid(jid)
636
+
637
+ const { count = 20, before, after, viewRole } = options
638
+ const attrs = { type: 'jid', jid }
639
+ if (isPresent(viewRole)) attrs.view_role = String(viewRole).toLowerCase()
640
+ attrs.count = String(count)
641
+ if (isPresent(before)) attrs.before = toServerId(before, 'before')
642
+ else if (isPresent(after)) attrs.after = toServerId(after, 'after')
643
+
644
+ const result = await sock.query({
645
+ tag: 'iq',
646
+ attrs: {
647
+ to: S_WHATSAPP_NET,
648
+ xmlns: 'newsletter',
649
+ type: 'get'
650
+ },
651
+ content: [{ tag: 'statuses', attrs, content: undefined }]
652
+ })
653
+
654
+ return parseNewsletterStatusesResponse(result)
655
+ }
656
+
657
+ const sendNewsletterStatus = exports.sendNewsletterStatus = (sock, inputOrJid, content, options = {}) => {
658
+ let jid;
659
+ let actualContent;
660
+ let actualOptions;
661
+
662
+ if (typeof inputOrJid === "object" && inputOrJid !== null && ("jid" in inputOrJid || "content" in inputOrJid)) {
663
+ const { jid: targetJid, content: targetContent, ...rest } = inputOrJid;
664
+ jid = targetJid;
665
+ actualContent = targetContent;
666
+ actualOptions = { ...rest, ...content };
667
+ } else {
668
+ jid = inputOrJid;
669
+ actualContent = content;
670
+ actualOptions = options;
671
+ }
672
+
673
+ const sender = makeNewsletterStatusSender(sock, sock?.config);
674
+ return sender(jid, actualContent, actualOptions);
675
+ };
676
+
677
+ const sendNewsletterStatusReaction = exports.sendNewsletterStatusReaction = (sock, jid, parentServerId, reaction, options) => {
678
+ return makeNewsletterStatusReactionSender(sock)(jid, parentServerId, reaction, options);
679
+ };
680
+
681
+ const revokeNewsletterStatus = exports.revokeNewsletterStatus = (sock, jid, serverId, options) => {
682
+ return makeNewsletterStatusRevokeSender(sock)(jid, serverId, options);
683
+ };
684
+
685
+ const getNewsletterStatuses = exports.getNewsletterStatuses = (sock, jid, options) => {
686
+ return makeNewsletterStatusFetcher(sock)(jid, options);
687
+ };
688
+
689
+ const getNewsletterStatusUpdates = exports.getNewsletterStatusUpdates = (sock, jid, options) => {
690
+ return makeNewsletterStatusUpdatesFetcher(sock)(jid, options);
691
+ };
692
+
693
+ exports.NEWSLETTER_STATUS_CONTENT_TYPES = NEWSLETTER_STATUS_CONTENT_TYPES;
694
+ exports.NEWSLETTER_STATUS_MEDIA_TYPES = NEWSLETTER_STATUS_MEDIA_TYPES;
695
+ exports.NEWSLETTER_STATUS_WEB_MEDIA_TYPES = NEWSLETTER_STATUS_WEB_MEDIA_TYPES;