@oxidezap/baileyrs 0.3.6 → 0.3.8

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 (130) hide show
  1. package/README.md +67 -8
  2. package/lib/Bridge/history-sync-wire.d.ts +2 -2
  3. package/lib/Bridge/history-sync-wire.js +4 -4
  4. package/lib/Bridge/schema.js +7 -1
  5. package/lib/Bridge/types.d.ts +7 -1
  6. package/lib/Compatibility/auth-state.d.ts +30 -0
  7. package/lib/Compatibility/auth-state.js +96 -0
  8. package/lib/Compatibility/encode-proto-core.d.ts +31 -0
  9. package/lib/Compatibility/encode-proto-core.js +51 -0
  10. package/lib/Compatibility/encode-proto.d.ts +0 -19
  11. package/lib/Compatibility/encode-proto.js +3 -35
  12. package/lib/Compatibility/host-auth-state.d.ts +6 -0
  13. package/lib/Compatibility/host-auth-state.js +162 -0
  14. package/lib/Compatibility/internal/auth-state.d.ts +3 -7
  15. package/lib/Compatibility/internal/auth-state.js +34 -1
  16. package/lib/Compatibility/internal/host-auth-state.d.ts +4 -0
  17. package/lib/Compatibility/internal/host-auth-state.js +14 -0
  18. package/lib/Compatibility/legacy-store/device.js +5 -5
  19. package/lib/Compatibility/message-ids.d.ts +17 -0
  20. package/lib/Compatibility/message-ids.js +47 -0
  21. package/lib/Compatibility/message-relay.d.ts +2 -2
  22. package/lib/Compatibility/message-relay.js +4 -4
  23. package/lib/Compatibility/proto-runtime.d.ts +5 -0
  24. package/lib/Compatibility/proto-runtime.js +214 -32
  25. package/lib/Compatibility/socket-results.d.ts +1 -1
  26. package/lib/Compatibility/tagged-message-waiter.d.ts +5 -2
  27. package/lib/Compatibility/tagged-message-waiter.js +5 -5
  28. package/lib/Compatibility/usync/adapter.d.ts +1 -1
  29. package/lib/Compatibility/websocket-client.d.ts +11 -3
  30. package/lib/Compatibility/websocket-client.js +84 -11
  31. package/lib/Defaults/index.d.ts +8 -8
  32. package/lib/Defaults/index.js +8 -8
  33. package/lib/Media/content.d.ts +28 -0
  34. package/lib/Media/content.js +129 -0
  35. package/lib/Media/core.d.ts +34 -0
  36. package/lib/Media/core.js +120 -0
  37. package/lib/Media/mutations.d.ts +24 -0
  38. package/lib/Media/mutations.js +38 -0
  39. package/lib/Runtime/aes-gcm.d.ts +4 -0
  40. package/lib/Runtime/aes-gcm.js +11 -0
  41. package/lib/Runtime/bridge.d.ts +44 -0
  42. package/lib/Runtime/bridge.js +76 -0
  43. package/lib/Runtime/buffer.d.ts +9 -0
  44. package/lib/Runtime/buffer.js +22 -0
  45. package/lib/Runtime/bytes.d.ts +61 -0
  46. package/lib/Runtime/bytes.js +270 -0
  47. package/lib/Runtime/host.d.ts +22 -0
  48. package/lib/Runtime/host.js +43 -0
  49. package/lib/Runtime/long.d.ts +33 -0
  50. package/lib/Runtime/long.js +64 -0
  51. package/lib/Runtime/node-media-processors.d.ts +4 -0
  52. package/lib/Runtime/node-media-processors.js +29 -0
  53. package/lib/Runtime/node-media.d.ts +28 -0
  54. package/lib/Runtime/node-media.js +115 -0
  55. package/lib/Runtime/node.d.ts +14 -0
  56. package/lib/Runtime/node.js +81 -0
  57. package/lib/Runtime/paths.d.ts +4 -0
  58. package/lib/Runtime/paths.js +7 -0
  59. package/lib/Runtime/stream.d.ts +11 -0
  60. package/lib/Runtime/stream.js +25 -0
  61. package/lib/Runtime/types.d.ts +98 -0
  62. package/lib/Runtime/types.js +13 -0
  63. package/lib/Socket/core.d.ts +312 -0
  64. package/lib/Socket/core.js +1122 -0
  65. package/lib/Socket/events-core.d.ts +75 -0
  66. package/lib/Socket/events-core.js +1058 -0
  67. package/lib/Socket/events.d.ts +1 -63
  68. package/lib/Socket/events.js +4 -1047
  69. package/lib/Socket/groups.js +4 -3
  70. package/lib/Socket/index.d.ts +521 -103
  71. package/lib/Socket/index.js +10 -1007
  72. package/lib/Socket/messages-core.d.ts +41 -0
  73. package/lib/Socket/messages-core.js +270 -0
  74. package/lib/Socket/messages.d.ts +9 -36
  75. package/lib/Socket/messages.js +3 -260
  76. package/lib/Socket/newsletter.js +3 -3
  77. package/lib/Socket/profile.js +1 -1
  78. package/lib/Socket/terminal-close-reporter.d.ts +2 -0
  79. package/lib/Socket/terminal-close-reporter.js +3 -3
  80. package/lib/Socket/transport.d.ts +2 -0
  81. package/lib/Socket/transport.js +16 -1
  82. package/lib/Socket/types.d.ts +2 -0
  83. package/lib/Types/Auth.d.ts +11 -0
  84. package/lib/Types/Message.d.ts +1 -1
  85. package/lib/Types/Socket.d.ts +2 -2
  86. package/lib/Types/index.d.ts +6 -1
  87. package/lib/Utils/browser-utils.d.ts +4 -0
  88. package/lib/Utils/browser-utils.js +53 -2
  89. package/lib/Utils/crypto.d.ts +1 -0
  90. package/lib/Utils/crypto.js +1 -0
  91. package/lib/Utils/event-buffer.d.ts +6 -1
  92. package/lib/Utils/event-buffer.js +28 -27
  93. package/lib/Utils/link-preview.d.ts +4 -3
  94. package/lib/Utils/logger.d.ts +3 -0
  95. package/lib/Utils/logger.js +35 -6
  96. package/lib/Utils/messages-core.d.ts +174 -0
  97. package/lib/Utils/messages-core.js +1042 -0
  98. package/lib/Utils/messages-media-core.d.ts +73 -0
  99. package/lib/Utils/messages-media-core.js +319 -0
  100. package/lib/Utils/messages-media.d.ts +1 -72
  101. package/lib/Utils/messages-media.js +9 -358
  102. package/lib/Utils/messages.d.ts +1 -166
  103. package/lib/Utils/messages.js +7 -1040
  104. package/lib/Utils/optional-peer.js +14 -5
  105. package/lib/Utils/process-history-message-core.d.ts +36 -0
  106. package/lib/Utils/process-history-message-core.js +187 -0
  107. package/lib/Utils/process-history-message.d.ts +5 -43
  108. package/lib/Utils/process-history-message.js +11 -197
  109. package/lib/Utils/process-message-core.d.ts +29 -0
  110. package/lib/Utils/process-message-core.js +112 -0
  111. package/lib/Utils/process-message.d.ts +4 -24
  112. package/lib/Utils/process-message.js +6 -111
  113. package/lib/WABinary/generic-utils.js +7 -5
  114. package/lib/host-shared.d.ts +74 -0
  115. package/lib/host-shared.js +15 -0
  116. package/lib/host-socket-operations.d.ts +3 -0
  117. package/lib/host-socket-operations.js +2 -0
  118. package/lib/host-surface.d.ts +21 -0
  119. package/lib/host-surface.js +35 -0
  120. package/lib/host-types.d.ts +356 -0
  121. package/lib/host-types.js +2 -0
  122. package/lib/host.d.ts +33 -0
  123. package/lib/host.js +31 -0
  124. package/lib/node-surface.d.ts +9 -0
  125. package/lib/node-surface.js +15 -0
  126. package/lib/surface.d.ts +5 -0
  127. package/lib/surface.js +6 -0
  128. package/lib/wasm.d.ts +27 -0
  129. package/lib/wasm.js +27 -0
  130. package/package.json +18 -6
@@ -1,1044 +1,11 @@
1
- import { Buffer } from 'node:buffer';
2
- import LongRuntime from 'long';
3
- import { Readable } from 'node:stream';
4
- import { toBridgeMediaType } from '../Compatibility/media-type.js';
5
- import { CALL_AUDIO_PREFIX, CALL_VIDEO_PREFIX, MEDIA_KEYS, URL_REGEX, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
6
- import { WAMessageStatus, WAProto } from '../Types/index.js';
7
- import { proto } from '../WAProto/runtime.js';
8
- import { isJidGroup, isJidNewsletter, isJidStatusBroadcast, jidNormalizedUser } from '../WABinary/index.js';
9
- import { assertArgumentDomain } from './argument-domain.js';
10
- import { Boom } from './boom.js';
11
- import { randomBytes } from 'node:crypto';
12
- import { sha256 } from './crypto.js';
13
- import { getKeyAuthor, toNumber, unixTimestampSeconds } from './generics.js';
14
- import { generateThumbnail, getAudioDuration, getAudioWaveform, getStream, toBuffer } from './messages-media.js';
15
- const MIMETYPE_MAP = {
16
- image: 'image/jpeg',
17
- video: 'video/mp4',
18
- document: 'application/pdf',
19
- audio: 'audio/ogg; codecs=opus',
20
- sticker: 'image/webp',
21
- 'product-catalog-image': 'image/jpeg'
22
- };
23
- const MessageTypeProto = {
24
- image: WAProto.Message.ImageMessage,
25
- video: WAProto.Message.VideoMessage,
26
- audio: WAProto.Message.AudioMessage,
27
- sticker: WAProto.Message.StickerMessage,
28
- document: WAProto.Message.DocumentMessage
29
- };
30
1
  /**
31
- * Uses a regex to test whether the string contains a URL, and returns the URL if it does.
32
- * @param text eg. hello https://google.com
33
- * @returns the URL, eg. https://google.com
34
- */
35
- export const extractUrlFromText = (text) => text.match(URL_REGEX)?.[0];
36
- export const generateLinkPreviewIfRequired = async (text, getUrlInfo, logger) => {
37
- if (!getUrlInfo)
38
- return;
39
- const url = extractUrlFromText(text);
40
- if (url) {
41
- try {
42
- const urlInfo = await getUrlInfo(url);
43
- return urlInfo;
44
- }
45
- catch (error) {
46
- // ignore if fails
47
- logger?.warn({ trace: error.stack }, 'url generation failed');
48
- }
49
- }
50
- };
51
- const assertColor = (color) => {
52
- if (typeof color === 'number') {
53
- return color > 0 ? color : 0xffffffff + Number(color) + 1;
54
- }
55
- let hex = color.trim().replace('#', '');
56
- if (hex.length <= 6) {
57
- hex = 'FF' + hex.padStart(6, '0');
58
- }
59
- return parseInt(hex, 16);
60
- };
61
- export const prepareWAMessageMedia = async (message, options) => {
62
- const logger = options.logger;
63
- let mediaType;
64
- for (const key of MEDIA_KEYS) {
65
- if (key in message) {
66
- mediaType = key;
67
- }
68
- }
69
- if (!mediaType) {
70
- throw new Boom('Invalid media type', { statusCode: 400 });
71
- }
72
- const messageRecord = message;
73
- const uploadData = {
74
- ...message,
75
- media: messageRecord[mediaType]
76
- };
77
- delete uploadData[mediaType];
78
- // check if cacheable + generate cache key
79
- const cacheableKey = typeof uploadData.media === 'object' &&
80
- 'url' in uploadData.media &&
81
- !!uploadData.media.url &&
82
- !!options.mediaCache &&
83
- mediaType + ':' + uploadData.media.url.toString();
84
- if (mediaType === 'document' && !uploadData.fileName) {
85
- uploadData.fileName = 'file';
86
- }
87
- if (!uploadData.mimetype) {
88
- uploadData.mimetype = MIMETYPE_MAP[mediaType];
89
- }
90
- if (cacheableKey) {
91
- const mediaBuff = await options.mediaCache.get(cacheableKey);
92
- if (mediaBuff) {
93
- logger?.debug({ cacheableKey }, 'got media cache hit');
94
- const obj = proto.Message.decode(mediaBuff);
95
- const key = `${mediaType}Message`;
96
- // `obj[key]` is a discriminated-union slot; cache hits always store
97
- // a media submessage (not e.g. `conversation: string`), so cast to
98
- // `object` for `Object.assign`'s benefit.
99
- Object.assign(obj[key], { ...uploadData, media: undefined });
100
- return obj;
101
- }
102
- }
103
- // Read media into buffer — needed for both upload and metadata extraction
104
- const { stream } = await getStream(uploadData.media, options.options);
105
- const buffer = await toBuffer(stream);
106
- const effectiveMediaType = options.mediaTypeOverride || mediaType;
107
- const bridgeMediaType = toBridgeMediaType(effectiveMediaType);
108
- // Run upload + metadata extraction in parallel
109
- let uploadResult;
110
- if (options.processMedia) {
111
- // User-provided processing pipeline (streaming encrypt, custom thumbnails, etc.)
112
- const { upload, metadata } = await options.processMedia(buffer, bridgeMediaType, options.waClient);
113
- uploadResult = upload;
114
- if (metadata) {
115
- if (metadata.jpegThumbnail !== undefined)
116
- uploadData.jpegThumbnail = metadata.jpegThumbnail;
117
- if (metadata.width !== undefined)
118
- uploadData.width = metadata.width;
119
- if (metadata.height !== undefined)
120
- uploadData.height = metadata.height;
121
- if (metadata.seconds !== undefined)
122
- uploadData.seconds = metadata.seconds;
123
- if (metadata.waveform !== undefined)
124
- uploadData.waveform = metadata.waveform;
125
- }
126
- }
127
- else if (options.upload) {
128
- // Legacy upstream-Baileys compat: { upload: sock.waUploadToServer }.
129
- // Same plaintext-in / UploadMediaResult-out contract as waClient.uploadMedia.
130
- const [result] = await Promise.all([
131
- options.upload(buffer, { mediaType: effectiveMediaType }),
132
- extractBuiltInMetadata(buffer, mediaType, uploadData, options)
133
- ]);
134
- uploadResult = result;
135
- }
136
- else {
137
- // Default: in-memory encrypt + upload via Rust, built-in metadata extraction
138
- const [result] = await Promise.all([
139
- options.waClient.uploadMedia(buffer, bridgeMediaType),
140
- extractBuiltInMetadata(buffer, mediaType, uploadData, options)
141
- ]);
142
- uploadResult = result;
143
- }
144
- // Coerce any string-form `jpegThumbnail` (the legacy upstream Baileys output)
145
- // into bytes — the bridge's ts-proto encoder reads `.byteLength` directly
146
- // and throws `invalid uint32: undefined` on strings. Done here (not at
147
- // extraction time) so values arriving via `processMedia`, link-preview
148
- // builders, or direct user input go through the same coercion.
149
- if (typeof uploadData.jpegThumbnail === 'string') {
150
- uploadData.jpegThumbnail = Buffer.from(uploadData.jpegThumbnail, 'base64');
151
- }
152
- const obj = WAProto.Message.fromObject({
153
- [`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
154
- url: uploadResult.url,
155
- directPath: uploadResult.directPath,
156
- mediaKey: uploadResult.mediaKey,
157
- fileEncSha256: uploadResult.fileEncSha256,
158
- fileSha256: uploadResult.fileSha256,
159
- fileLength: uploadResult.fileLength,
160
- mediaKeyTimestamp: unixTimestampSeconds(),
161
- ...uploadData,
162
- media: undefined
163
- })
164
- });
165
- if (uploadData.ptv) {
166
- obj.ptvMessage = obj.videoMessage;
167
- delete obj.videoMessage;
168
- }
169
- if (obj.stickerMessage) {
170
- obj.stickerMessage.stickerSentTs = Date.now();
171
- }
172
- if (cacheableKey) {
173
- logger?.debug({ cacheableKey }, 'set cache');
174
- await options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish());
175
- }
176
- return obj;
177
- };
178
- /** Extract metadata (thumbnail, duration, waveform) from buffer using built-in JS libraries */
179
- async function extractBuiltInMetadata(buffer, mediaType, uploadData, options) {
180
- try {
181
- const requiresThumbnailComputation = (mediaType === 'image' || mediaType === 'video') && typeof uploadData.jpegThumbnail === 'undefined';
182
- const requiresDurationComputation = mediaType === 'audio' && typeof uploadData.seconds === 'undefined';
183
- const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true;
184
- const requiresAudioBackground = options.backgroundColor && mediaType === 'audio' && uploadData.ptt === true;
185
- if (requiresThumbnailComputation) {
186
- const { thumbnail, originalImageDimensions } = await generateThumbnail(buffer, mediaType, options);
187
- uploadData.jpegThumbnail = thumbnail;
188
- if (!uploadData.width && originalImageDimensions) {
189
- uploadData.width = originalImageDimensions.width;
190
- uploadData.height = originalImageDimensions.height;
191
- }
192
- }
193
- if (requiresDurationComputation) {
194
- uploadData.seconds = await getAudioDuration(buffer);
195
- }
196
- if (requiresWaveformProcessing) {
197
- uploadData.waveform = await getAudioWaveform(buffer, options.logger);
198
- }
199
- if (requiresAudioBackground) {
200
- uploadData.backgroundArgb = await assertColor(options.backgroundColor);
201
- }
202
- }
203
- catch (error) {
204
- options.logger?.warn({ trace: error.stack }, 'failed to obtain extra info');
205
- }
206
- }
207
- export const prepareDisappearingMessageSettingContent = (ephemeralExpiration) => {
208
- ephemeralExpiration = ephemeralExpiration || 0;
209
- const content = {
210
- ephemeralMessage: {
211
- message: {
212
- protocolMessage: {
213
- type: WAProto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
214
- ephemeralExpiration
215
- }
216
- }
217
- }
218
- };
219
- return WAProto.Message.fromObject(content);
220
- };
221
- /**
222
- * Generate forwarded message content like WA does
223
- * @param message the message to forward
224
- * @param options.forceForward will show the message as forwarded even if it is from you
225
- */
226
- export const generateForwardMessageContent = (message, forceForward) => {
227
- let content = message.message;
228
- if (!content) {
229
- throw new Boom('no content in message', { statusCode: 400 });
230
- }
231
- content = normalizeMessageContent(content);
232
- // Shallow clone of the outer map — one entry on it is rewritten below.
233
- content = { ...content };
234
- let key = Object.keys(content)[0];
235
- let score = content?.[key]?.contextInfo?.forwardingScore || 0;
236
- score += message.key.fromMe && !forceForward ? 0 : 1;
237
- const contextInfo = score > 0 ? { forwardingScore: score, isForwarded: true } : {};
238
- // The nested message object is the *caller's*, reached through the shallow
239
- // clone above, so writing `contextInfo` onto it wrote into their argument.
240
- // And it replaces rather than merges: a caller who forwarded a quoted message
241
- // found `stanzaId` and `participant` gone from their own object afterwards.
242
- // Upstream leaves the argument untouched.
243
- //
244
- // Rebuilt rather than deep-copied, and only the one object being written.
245
- // Upstream's copy is `proto.Message.decode(proto.Message.encode(content))` —
246
- // a full serialise/parse round trip on a hot send path — which is not worth
247
- // paying to fix an aliasing bug.
248
- if (key === 'conversation') {
249
- // This object is created here, so nothing of the caller's is aliased and
250
- // the `contextInfo` goes straight in. Same allocation count as before.
251
- content.extendedTextMessage = { text: content[key], contextInfo };
252
- delete content.conversation;
253
- key = 'extendedTextMessage';
254
- return content;
255
- }
256
- const nested = content[key];
257
- // A plain object is the only thing worth copying, and the only thing that can
258
- // be the caller's to damage. Anything else — an absent slot on an empty
259
- // message, a primitive, an array — keeps the original assignment, which
260
- // throws for exactly the inputs it threw for before and that upstream throws
261
- // for too. Spreading those instead invented a property named `"undefined"`
262
- // where upstream raised a TypeError.
263
- if (typeof nested === 'object' && nested !== null && !Array.isArray(nested)) {
264
- // One shallow spread, of exactly the object being modified. This is the
265
- // whole cost of the fix, and it is unavoidable: not writing into the
266
- // caller's object means writing into a different one.
267
- content[key] = { ...nested, contextInfo };
268
- }
269
- else {
270
- nested.contextInfo = contextInfo;
271
- }
272
- return content;
273
- };
274
- export const hasNonNullishProperty = (message, key) => {
275
- return (typeof message === 'object' &&
276
- message !== null &&
277
- key in message &&
278
- message[key] !== null &&
279
- message[key] !== undefined);
280
- };
281
- function hasOptionalProperty(obj, key) {
282
- return typeof obj === 'object' && obj !== null && key in obj && obj[key] !== null;
283
- }
284
- export const generateWAMessageContent = async (message, options) => {
285
- var _a, _b;
286
- let m = {};
287
- if (hasNonNullishProperty(message, 'text')) {
288
- const extContent = { text: message.text };
289
- let urlInfo = message.linkPreview;
290
- // Gate on the resolver before awaiting: without one the helper resolves
291
- // to undefined anyway, and every plain text send would still pay for a
292
- // promise plus a microtask turn.
293
- if (typeof urlInfo === 'undefined' && options.getUrlInfo) {
294
- urlInfo = await generateLinkPreviewIfRequired(message.text, options.getUrlInfo, options.logger);
295
- }
296
- if (urlInfo) {
297
- extContent.matchedText = urlInfo['matched-text'];
298
- extContent.jpegThumbnail = urlInfo.jpegThumbnail;
299
- extContent.description = urlInfo.description;
300
- extContent.title = urlInfo.title;
301
- extContent.previewType = 0;
302
- const img = urlInfo.highQualityThumbnail;
303
- if (img) {
304
- extContent.thumbnailDirectPath = img.directPath;
305
- extContent.mediaKey = img.mediaKey;
306
- extContent.mediaKeyTimestamp = img.mediaKeyTimestamp;
307
- extContent.thumbnailWidth = img.width;
308
- extContent.thumbnailHeight = img.height;
309
- extContent.thumbnailSha256 = img.fileSha256;
310
- extContent.thumbnailEncSha256 = img.fileEncSha256;
311
- }
312
- }
313
- if (options.backgroundColor) {
314
- extContent.backgroundArgb = await assertColor(options.backgroundColor);
315
- }
316
- if (options.font) {
317
- extContent.font = options.font;
318
- }
319
- m.extendedTextMessage = extContent;
320
- }
321
- else if (hasNonNullishProperty(message, 'contacts')) {
322
- const contactLen = message.contacts.contacts.length;
323
- if (!contactLen) {
324
- throw new Boom('require atleast 1 contact', { statusCode: 400 });
325
- }
326
- if (contactLen === 1) {
327
- m.contactMessage = WAProto.Message.ContactMessage.create(message.contacts.contacts[0]);
328
- }
329
- else {
330
- m.contactsArrayMessage = WAProto.Message.ContactsArrayMessage.create(message.contacts);
331
- }
332
- }
333
- else if (hasNonNullishProperty(message, 'location')) {
334
- m.locationMessage = WAProto.Message.LocationMessage.create(message.location);
335
- }
336
- else if (hasNonNullishProperty(message, 'react')) {
337
- if (!message.react.senderTimestampMs) {
338
- message.react.senderTimestampMs = Date.now();
339
- }
340
- m.reactionMessage = WAProto.Message.ReactionMessage.create(message.react);
341
- }
342
- else if (hasNonNullishProperty(message, 'delete')) {
343
- m.protocolMessage = {
344
- key: message.delete,
345
- type: WAProto.Message.ProtocolMessage.Type.REVOKE
346
- };
347
- }
348
- else if (hasNonNullishProperty(message, 'forward')) {
349
- m = generateForwardMessageContent(message.forward, message.force);
350
- }
351
- else if (hasNonNullishProperty(message, 'disappearingMessagesInChat')) {
352
- const exp = typeof message.disappearingMessagesInChat === 'boolean'
353
- ? message.disappearingMessagesInChat
354
- ? WA_DEFAULT_EPHEMERAL
355
- : 0
356
- : message.disappearingMessagesInChat;
357
- m = prepareDisappearingMessageSettingContent(exp);
358
- }
359
- else if (hasNonNullishProperty(message, 'groupInvite')) {
360
- m.groupInviteMessage = {};
361
- m.groupInviteMessage.inviteCode = message.groupInvite.inviteCode;
362
- m.groupInviteMessage.inviteExpiration = message.groupInvite.inviteExpiration;
363
- m.groupInviteMessage.caption = message.groupInvite.text;
364
- m.groupInviteMessage.groupJid = message.groupInvite.jid;
365
- m.groupInviteMessage.groupName = message.groupInvite.subject;
366
- //TODO: use built-in interface and get disappearing mode info etc.
367
- //TODO: cache / use store!?
368
- if (options.getProfilePicUrl) {
369
- const pfpUrl = await options.getProfilePicUrl(message.groupInvite.jid, 'preview');
370
- if (pfpUrl) {
371
- const resp = await fetch(pfpUrl, { method: 'GET', dispatcher: options?.options?.dispatcher });
372
- if (resp.ok) {
373
- const buf = Buffer.from(await resp.arrayBuffer());
374
- m.groupInviteMessage.jpegThumbnail = buf;
375
- }
376
- }
377
- }
378
- }
379
- else if (hasNonNullishProperty(message, 'pin')) {
380
- m.pinInChatMessage = {};
381
- m.messageContextInfo = {};
382
- m.pinInChatMessage.key = message.pin;
383
- m.pinInChatMessage.type = message.type;
384
- m.pinInChatMessage.senderTimestampMs = Date.now();
385
- m.messageContextInfo.messageAddOnDurationInSecs =
386
- message.type === proto.PinInChat.Type.PIN_FOR_ALL ? message.time || 86400 : 0;
387
- }
388
- else if (hasNonNullishProperty(message, 'buttonReply')) {
389
- switch (message.type) {
390
- case 'template':
391
- m.templateButtonReplyMessage = {
392
- selectedDisplayText: message.buttonReply.displayText,
393
- selectedId: message.buttonReply.id,
394
- selectedIndex: message.buttonReply.index
395
- };
396
- break;
397
- case 'plain':
398
- m.buttonsResponseMessage = {
399
- selectedButtonId: message.buttonReply.id,
400
- selectedDisplayText: message.buttonReply.displayText,
401
- type: proto.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT
402
- };
403
- break;
404
- }
405
- }
406
- else if (hasOptionalProperty(message, 'ptv') && message.ptv) {
407
- const { videoMessage } = await prepareWAMessageMedia({ video: message.video }, options);
408
- m.ptvMessage = videoMessage;
409
- }
410
- else if (hasNonNullishProperty(message, 'product')) {
411
- const { imageMessage } = await prepareWAMessageMedia({ image: message.product.productImage }, options);
412
- m.productMessage = WAProto.Message.ProductMessage.create({
413
- ...message,
414
- product: {
415
- ...message.product,
416
- productImage: imageMessage
417
- }
418
- });
419
- }
420
- else if (hasNonNullishProperty(message, 'listReply')) {
421
- m.listResponseMessage = { ...message.listReply };
422
- }
423
- else if (hasNonNullishProperty(message, 'event')) {
424
- m.eventMessage = {};
425
- const startTime = Math.floor(message.event.startDate.getTime() / 1000);
426
- if (message.event.call && options.getCallLink) {
427
- const token = await options.getCallLink(message.event.call, { startTime });
428
- m.eventMessage.joinLink = (message.event.call === 'audio' ? CALL_AUDIO_PREFIX : CALL_VIDEO_PREFIX) + token;
429
- }
430
- m.eventMessage.name = message.event.name;
431
- m.eventMessage.description = message.event.description;
432
- m.eventMessage.startTime = startTime;
433
- m.eventMessage.endTime = message.event.endDate ? Math.floor(message.event.endDate.getTime() / 1000) : undefined;
434
- m.eventMessage.isCanceled = message.event.isCancelled ?? false;
435
- m.eventMessage.extraGuestsAllowed = message.event.extraGuestsAllowed;
436
- m.eventMessage.isScheduleCall = message.event.isScheduleCall ?? false;
437
- m.eventMessage.location = message.event.location;
438
- // The sender's copy of the key that encrypts responses to this event;
439
- // `decryptEventResponse` takes it as `eventEncKey`. WhatsApp Web writes it
440
- // on the sender at creation (`WAWebSendEventCreationMsgAction`) and refuses
441
- // to build an event edit without it (`WAWebCreateEncryptedEventEditMsgData`
442
- // throws `EventCreationValidationError`).
443
- //
444
- // The core settles `messageSecret` on relay for messages that reach it
445
- // without one — see the comment in `Socket/messages.ts` — but it settles it
446
- // on the wire, where the caller never sees it. That is right for the
447
- // reporting token and wrong for a key the caller has to keep.
448
- //
449
- // Written after `m.eventMessage`, for the reason spelled out on the poll
450
- // branch below: the blocks that attach `contextInfo` take `Object.keys(m)[0]`
451
- // as the content key. `event` is not `Mentionable` or `Contextable` today,
452
- // so this is ordering that stays correct rather than ordering that is
453
- // currently load-bearing — but it costs nothing and the poll branch shows
454
- // what getting it wrong looks like.
455
- //
456
- // Spread rather than upstream's wholesale assignment: nothing else writes
457
- // `messageContextInfo` on this branch today, so the two cannot differ, and
458
- // this cannot silently drop a field a later change puts there.
459
- m.messageContextInfo = {
460
- ...m.messageContextInfo,
461
- messageSecret: message.event.messageSecret || randomBytes(32)
462
- };
463
- }
464
- else if (hasNonNullishProperty(message, 'poll')) {
465
- (_a = message.poll).selectableCount || (_a.selectableCount = 0);
466
- (_b = message.poll).toAnnouncementGroup || (_b.toAnnouncementGroup = false);
467
- if (!Array.isArray(message.poll.values)) {
468
- throw new Boom('Invalid poll values', { statusCode: 400 });
469
- }
470
- if (message.poll.selectableCount < 0 || message.poll.selectableCount > message.poll.values.length) {
471
- throw new Boom(`poll.selectableCount in poll should be >= 0 and <= ${message.poll.values.length}`, {
472
- statusCode: 400
473
- });
474
- }
475
- const pollCreationMessage = {
476
- name: message.poll.name,
477
- selectableOptionsCount: message.poll.selectableCount,
478
- options: message.poll.values.map(optionName => ({ optionName }))
479
- };
480
- if (message.poll.toAnnouncementGroup) {
481
- // poll v2 is for community announcement groups (single select and multiple)
482
- m.pollCreationMessageV2 = pollCreationMessage;
483
- }
484
- else {
485
- if (message.poll.selectableCount === 1) {
486
- //poll v3 is for single select polls
487
- m.pollCreationMessageV3 = pollCreationMessage;
488
- }
489
- else {
490
- // poll for multiple choice polls
491
- m.pollCreationMessage = pollCreationMessage;
492
- }
493
- }
494
- // The key that encrypts the votes. `decryptPollVote` takes it as
495
- // `pollEncKey`, and without it here the poll goes out fine but its own
496
- // sender can never read the votes: the copy they store — the message
497
- // `sendMessage` returns and emits as `messages.upsert` — is this object,
498
- // and only `key.id` is patched from the relay result. WhatsApp Web writes it
499
- // on the sender at creation too (`WAWebPollsSendPollCreationMsgAction`) and
500
- // reuses the stored one for poll edits
501
- // (`WAWebPollsGeneratePollEditMessageProto`).
502
- //
503
- // After the payload, not before, and that ordering is load-bearing: the
504
- // `mentions` and `contextInfo` blocks below pick their target with
505
- // `Object.keys(m)[0]`, so a `messageContextInfo` written first becomes the
506
- // content key they attach to. `contextInfo` is not a field of
507
- // `IMessageContextInfo`, so the encoder drops it and a poll sent with
508
- // mentions loses them silently. `poll` is `Mentionable & Contextable`, so
509
- // that is a combination callers can and do write. Upstream assigns it
510
- // before the payload and has exactly that bug; measured on
511
- // `{poll, mentions:['x@s.whatsapp.net']}`, its output carries no
512
- // `mentionedJid` at all.
513
- m.messageContextInfo = {
514
- ...m.messageContextInfo,
515
- messageSecret: message.poll.messageSecret || randomBytes(32)
516
- };
517
- }
518
- else if (hasNonNullishProperty(message, 'sharePhoneNumber')) {
519
- m.protocolMessage = {
520
- type: proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER
521
- };
522
- }
523
- else if (hasNonNullishProperty(message, 'requestPhoneNumber')) {
524
- m.requestPhoneNumberMessage = {};
525
- }
526
- else if (hasNonNullishProperty(message, 'limitSharing')) {
527
- m.protocolMessage = {
528
- type: proto.Message.ProtocolMessage.Type.LIMIT_SHARING,
529
- limitSharing: {
530
- sharingLimited: message.limitSharing === true,
531
- trigger: 1,
532
- limitSharingSettingTimestamp: Date.now(),
533
- initiatedByMe: true
534
- }
535
- };
536
- }
537
- else {
538
- m = await prepareWAMessageMedia(message, options);
539
- }
540
- if (hasOptionalProperty(message, 'viewOnce') && !!message.viewOnce) {
541
- m = { viewOnceMessage: { message: m } };
542
- }
543
- if ((hasOptionalProperty(message, 'mentions') && message.mentions?.length) ||
544
- (hasOptionalProperty(message, 'mentionAll') && message.mentionAll)) {
545
- const messageType = Object.keys(m)[0];
546
- const key = m[messageType];
547
- // `contextInfo` is declared by the proto schema but isn't an own
548
- // property on freshly-built messages — create-if-absent, then merge.
549
- if (key && typeof key === 'object') {
550
- const target = key;
551
- const ci = (target.contextInfo ?? (target.contextInfo = {}));
552
- if (message.mentions?.length) {
553
- ci.mentionedJid = message.mentions;
554
- }
555
- if (message.mentionAll) {
556
- ci.nonJidMentions = 1;
557
- }
558
- }
559
- }
560
- if (hasOptionalProperty(message, 'edit')) {
561
- m = {
562
- protocolMessage: {
563
- key: message.edit,
564
- editedMessage: m,
565
- timestampMs: Date.now(),
566
- type: WAProto.Message.ProtocolMessage.Type.MESSAGE_EDIT
567
- }
568
- };
569
- }
570
- if (hasOptionalProperty(message, 'contextInfo') && !!message.contextInfo) {
571
- const messageType = Object.keys(m)[0];
572
- const key = m[messageType];
573
- if (key) {
574
- key.contextInfo = key.contextInfo ? Object.assign(key.contextInfo, message.contextInfo) : message.contextInfo;
575
- }
576
- }
577
- return WAProto.Message.create(m);
578
- };
579
- export const generateWAMessageFromContent = (jid, message, options) => {
580
- const innerMessage = normalizeMessageContent(message);
581
- const timestamp = unixTimestampSeconds(options.timestamp);
582
- const { quoted, userJid } = options;
583
- // Only the quote and ephemeral branches read the content key, and a plain
584
- // send takes neither, so resolve it on demand instead of on every send.
585
- let key;
586
- if (quoted && !isJidNewsletter(jid)) {
587
- const contentKey = getContentType(innerMessage);
588
- key = contentKey;
589
- const participant = quoted.key.fromMe
590
- ? userJid // TODO: Add support for LIDs
591
- : quoted.participant || quoted.key.participant || quoted.key.remoteJid;
592
- let quotedMsg = normalizeMessageContent(quoted.message);
593
- const msgType = getContentType(quotedMsg);
594
- // strip any redundant properties
595
- quotedMsg = proto.Message.create({ [msgType]: quotedMsg[msgType] });
596
- const quotedContent = quotedMsg[msgType];
597
- if (typeof quotedContent === 'object' && quotedContent && 'contextInfo' in quotedContent) {
598
- delete quotedContent.contextInfo;
599
- }
600
- const contextInfo = ('contextInfo' in innerMessage[contentKey] && innerMessage[contentKey]?.contextInfo) || {};
601
- contextInfo.participant = jidNormalizedUser(participant);
602
- contextInfo.stanzaId = quoted.key.id;
603
- contextInfo.quotedMessage = quotedMsg;
604
- // if a participant is quoted, then it must be a group
605
- // hence, remoteJid of group must also be entered
606
- if (jid !== quoted.key.remoteJid) {
607
- contextInfo.remoteJid = quoted.key.remoteJid;
608
- }
609
- if (contextInfo && innerMessage[contentKey]) {
610
- /* @ts-ignore */
611
- innerMessage[contentKey].contextInfo = contextInfo;
612
- }
613
- }
614
- if (
615
- // if we want to send a disappearing message
616
- !!options?.ephemeralExpiration &&
617
- // newsletters don't support ephemeral messages
618
- !isJidNewsletter(jid)) {
619
- const contentKey = key ?? getContentType(innerMessage);
620
- // skip protocol messages -- delete, toggle disappear message -- and
621
- // content already converted to a disappearing message
622
- if (contentKey !== 'protocolMessage' && contentKey !== 'ephemeralMessage') {
623
- /* @ts-ignore */
624
- innerMessage[contentKey].contextInfo = {
625
- ...innerMessage[contentKey].contextInfo,
626
- expiration: options.ephemeralExpiration || WA_DEFAULT_EPHEMERAL
627
- //ephemeralSettingTimestamp: options.ephemeralOptions.eph_setting_ts?.toString()
628
- };
629
- }
630
- }
631
- // `create` copies into a fresh instance; content built by
632
- // `generateWAMessageContent` already is one, and the branches above mutate
633
- // it in place regardless, so copying it again only duplicates the tree.
634
- if (!(message instanceof WAProto.Message))
635
- message = WAProto.Message.create(message);
636
- // Direct construction instead of a `WebMessageInfo.fromObject` envelope:
637
- // every value is already in its runtime type (`message` came from
638
- // `Message.create` above), so the schema walk would only re-derive them.
639
- // `new` keeps protobufjs parity, including the constructor's own
640
- // `messageStubParameters` array. The `Long` cast mirrors the published
641
- // facade shape for 64-bit fields (source-side WAProto types them as plain
642
- // numbers via the bridge shapes).
643
- const messageKey = new WAProto.MessageKey();
644
- messageKey.remoteJid = jid;
645
- messageKey.fromMe = true;
646
- messageKey.id = options?.messageId || ''; // Rust generates the real message ID
647
- const wm = new WAProto.WebMessageInfo();
648
- wm.key = messageKey;
649
- wm.message = message;
650
- wm.messageTimestamp = LongRuntime.fromValue(timestamp);
651
- // TODO: Add support for LIDs
652
- const participant = isJidGroup(jid) || isJidStatusBroadcast(jid) ? userJid : undefined;
653
- if (participant !== undefined)
654
- wm.participant = participant;
655
- wm.status = WAMessageStatus.PENDING;
656
- return wm;
657
- };
658
- export const generateWAMessage = async (jid, content, options) => {
659
- const contentOptions = options.messageId && options.logger
660
- ? { ...options, logger: options.logger.child({ msgId: options.messageId }) }
661
- : options;
662
- return generateWAMessageFromContent(jid, await generateWAMessageContent(content, contentOptions), options);
663
- };
664
- /**
665
- * The content keys that carry almost every message on a live socket, settled by
666
- * identity before the structural predicate runs. Every name here already
667
- * satisfies that predicate, so this only shortcuts the substring scan; it never
668
- * changes which key wins.
669
- */
670
- const isCommonContentKey = (key) => {
671
- switch (key) {
672
- case 'conversation':
673
- case 'extendedTextMessage':
674
- case 'imageMessage':
675
- case 'videoMessage':
676
- case 'audioMessage':
677
- case 'stickerMessage':
678
- case 'documentMessage':
679
- case 'reactionMessage':
680
- case 'protocolMessage':
681
- case 'pollCreationMessage':
682
- return true;
683
- default:
684
- return false;
685
- }
686
- };
687
- /** Get the key to access the true type of content */
688
- export const getContentType = (content) => {
689
- if (!content) {
690
- return undefined;
691
- }
692
- // The answer stays positional (the first own key naming content wins), but
693
- // the scan is an indexed loop with an early return instead of `Array.find`,
694
- // so no closure is allocated and the common keys never reach `includes`.
695
- //
696
- // Deliberately still `Object.keys` and not `for..in`: a decoded
697
- // `WAProto.Message` inherits a default for every field of the schema, so
698
- // `for..in` would enumerate ~100 prototype keys per call (and would have to
699
- // filter them back out with `hasOwn` to stay positional) where `Object.keys`
700
- // yields only the handful that were actually set.
701
- const keys = Object.keys(content);
702
- for (let i = 0; i < keys.length; i++) {
703
- const key = keys[i];
704
- if (isCommonContentKey(key)) {
705
- return key;
706
- }
707
- if (key.includes('Message') && key !== 'senderKeyDistributionMessage') {
708
- return key;
709
- }
710
- }
711
- return undefined;
712
- };
713
- const getFutureProofMessage = (message) => message?.ephemeralMessage ||
714
- message?.viewOnceMessage ||
715
- message?.documentWithCaptionMessage ||
716
- message?.viewOnceMessageV2 ||
717
- message?.viewOnceMessageV2Extension ||
718
- message?.editedMessage ||
719
- message?.associatedChildMessage ||
720
- message?.groupStatusMessage ||
721
- message?.groupStatusMessageV2;
722
- const extractFromTemplateMessage = (msg) => {
723
- if (msg.imageMessage) {
724
- return { imageMessage: msg.imageMessage };
725
- }
726
- else if (msg.documentMessage) {
727
- return { documentMessage: msg.documentMessage };
728
- }
729
- else if (msg.videoMessage) {
730
- return { videoMessage: msg.videoMessage };
731
- }
732
- else if (msg.locationMessage) {
733
- return { locationMessage: msg.locationMessage };
734
- }
735
- else {
736
- return {
737
- conversation: 'contentText' in msg ? msg.contentText : 'hydratedContentText' in msg ? msg.hydratedContentText : ''
738
- };
739
- }
740
- };
741
- /**
742
- * Normalizes ephemeral, view once messages to regular message content
743
- * Eg. image messages in ephemeral messages, in view once messages etc.
744
- * @param content
745
- * @returns
746
- */
747
- export const normalizeMessageContent = (content) => {
748
- if (!content) {
749
- return undefined;
750
- }
751
- // set max iterations to prevent an infinite loop
752
- for (let i = 0; i < 5; i++) {
753
- const inner = getFutureProofMessage(content);
754
- if (!inner) {
755
- break;
756
- }
757
- content = inner.message;
758
- }
759
- return content;
760
- };
761
- /**
762
- * Extract the true message content from a message
763
- * Eg. extracts the inner message from a disappearing message/view once message
764
- */
765
- export const extractMessageContent = (content) => {
766
- content = normalizeMessageContent(content);
767
- if (content?.buttonsMessage) {
768
- return extractFromTemplateMessage(content.buttonsMessage);
769
- }
770
- if (content?.templateMessage?.hydratedFourRowTemplate) {
771
- return extractFromTemplateMessage(content?.templateMessage?.hydratedFourRowTemplate);
772
- }
773
- if (content?.templateMessage?.hydratedTemplate) {
774
- return extractFromTemplateMessage(content?.templateMessage?.hydratedTemplate);
775
- }
776
- if (content?.templateMessage?.fourRowTemplate) {
777
- return extractFromTemplateMessage(content?.templateMessage?.fourRowTemplate);
778
- }
779
- return content;
780
- };
781
- export const MEDIA_DOWNLOAD_TYPES = ['buffer', 'stream'];
782
- /**
783
- * Downloads the given message. Throws an error if it's not a media message.
784
- *
785
- * Uses the Rust bridge for download — provides CDN failover, automatic auth
786
- * refresh on 401/404, HMAC-SHA256 integrity verification, and AES-256-CBC
787
- * decryption, so a bridge client has to reach it.
788
- *
789
- * `ctx` is optional, as upstream has it: without one the client registered by
790
- * the most recent `makeWASocket` is used, the same fallback
791
- * `downloadContentFromMessage` offers for standalone calls. A host juggling
792
- * several sockets should pass `ctx` explicitly, because the registration points
793
- * at whichever client was created last.
794
- */
795
- export const downloadMediaMessage = async (message, type, options, ctx) => {
796
- // Anything but 'buffer' used to take the stream branch, so a typo returned
797
- // a Readable to a caller holding it as a Buffer.
798
- assertArgumentDomain('downloadMediaMessage', 'type', type, MEDIA_DOWNLOAD_TYPES);
799
- const waClient = ctx?.waClient ?? activeBridgeClient;
800
- if (!waClient) {
801
- throw new Boom('downloadMediaMessage: no bridge client available, and the download, its CDN failover and its decryption all happen in the engine. Pass `{ waClient: sock.waClient }`, use `sock.downloadMedia(message, type, options)`, or call after `makeWASocket()` has initialized.', { statusCode: 500 });
802
- }
803
- const withClient = { ...ctx, waClient };
804
- return (await downloadMsg());
805
- async function downloadMsg() {
806
- const mContent = extractMessageContent(message.message);
807
- if (!mContent) {
808
- throw new Boom('No message present', { statusCode: 400, data: message });
809
- }
810
- const contentType = getContentType(mContent);
811
- let mediaType = String(contentType)?.replace('Message', '');
812
- const media = mContent[contentType];
813
- if (!media || typeof media !== 'object' || (!('url' in media) && !('thumbnailDirectPath' in media))) {
814
- throw new Boom(`"${String(contentType)}" message is not a media message`);
815
- }
816
- if ('thumbnailDirectPath' in media && !('url' in media)) {
817
- mediaType = 'thumbnail-link';
818
- }
819
- if (!('directPath' in media) || !media.directPath || !('mediaKey' in media) || !media.mediaKey) {
820
- throw new Boom('Media message missing directPath or mediaKey', { statusCode: 400 });
821
- }
822
- const mediaObj = media;
823
- if (!mediaObj.fileSha256 || !mediaObj.fileEncSha256) {
824
- throw new Boom('Media message missing fileSha256 or fileEncSha256', { statusCode: 400 });
825
- }
826
- const args = [
827
- mediaObj.directPath,
828
- mediaObj.mediaKey,
829
- mediaObj.fileSha256,
830
- mediaObj.fileEncSha256,
831
- toNumber(mediaObj.fileLength ?? 0),
832
- toBridgeMediaType(mediaType)
833
- ];
834
- if (type === 'buffer') {
835
- const data = await withClient.waClient.downloadMedia(...args);
836
- return Buffer.from(data);
837
- }
838
- // Stream mode: Web ReadableStream from Rust → Node.js Readable
839
- const webStream = withClient.waClient.downloadMediaStream(...args);
840
- return Readable.fromWeb(webStream);
841
- }
842
- };
843
- /**
844
- * Module-level pointer to the most-recently created bridge client. Updated by
845
- * `makeWASocket` so standalone helpers like {@link downloadContentFromMessage}
846
- * (which carry no socket reference) can find the bridge without forcing the
847
- * caller to plumb `waClient` through. Multi-account hosts that juggle several
848
- * sockets should pass `opts.client` explicitly; otherwise this points at the
849
- * client created last.
850
- */
851
- let activeBridgeClient;
852
- let activeBridgeLogger;
853
- export const _registerActiveBridgeClient = (client, logger) => {
854
- activeBridgeClient = client;
855
- activeBridgeLogger = logger;
856
- };
857
- /**
858
- * Drop the module-level pointer when `sock.end()` frees the client it points
859
- * at. Without this the global keeps a strong reference to a freed
860
- * `WasmWhatsAppClient`, so the next standalone `downloadContentFromMessage()`
861
- * call reaches into a null wasm pointer and fails with an opaque
862
- * wasm-bindgen error instead of the actionable "no bridge client" Boom.
863
- *
864
- * Identity-checked on purpose: a multi-account host that ends socket A after
865
- * creating socket B must not clear B's registration.
866
- */
867
- export const _unregisterActiveBridgeClient = (client) => {
868
- if (activeBridgeClient !== client)
869
- return;
870
- activeBridgeClient = undefined;
871
- activeBridgeLogger = undefined;
872
- };
873
- const noopLogger = {
874
- level: 'silent',
875
- child: () => noopLogger,
876
- trace: () => { },
877
- debug: () => { },
878
- info: () => { },
879
- warn: () => { },
880
- error: () => { }
881
- };
882
- /**
883
- * Upstream-Baileys-compatible standalone media download. Builds a synthetic
884
- * `WAMessage` from the supplied media subcontent (image/video/audio/etc fields)
885
- * and routes it through {@link downloadMediaMessage}, so CDN failover, auth
886
- * refresh, HMAC verification, and AES-256-CBC decryption all happen inside the
887
- * Rust bridge — same code path as `sock.downloadMedia`.
888
- *
889
- * The bridge client is required. Pass it explicitly via `opts.client` for
890
- * multi-account hosts; otherwise the helper falls back to the most-recently
891
- * created bridge client (registered automatically by `makeWASocket`).
892
- */
893
- export const downloadContentFromMessage = async (mediaContent, type, opts = {}) => {
894
- const client = opts.client ?? activeBridgeClient;
895
- if (!client) {
896
- throw new Boom('downloadContentFromMessage: no bridge client available. ' +
897
- 'Pass `opts.client = sock.waClient`, or call after `makeWASocket()` has initialized.', { statusCode: 500 });
898
- }
899
- // `url` is seeded because the media guard downstream keys off its presence,
900
- // and content addressed only by `directPath` (history-sync notifications
901
- // carry no `url` field at all) would otherwise be rejected as non-media.
902
- const fakeMessage = {
903
- key: {},
904
- message: { [`${type}Message`]: { url: null, ...mediaContent } }
905
- };
906
- return downloadMediaMessage(fakeMessage, 'stream', opts, {
907
- logger: opts.logger ?? activeBridgeLogger ?? noopLogger,
908
- reuploadRequest: async (m) => m,
909
- waClient: client
910
- });
911
- };
912
- /** Infer the originating client family from WhatsApp's message-id format. */
913
- export const getDevice = (id) => /^3A.{18}$/.test(id)
914
- ? 'ios'
915
- : /^3E.{20}$/.test(id)
916
- ? 'web'
917
- : /^(.{21}|.{32})$/.test(id)
918
- ? 'android'
919
- : /^(3F|.{18}$)/.test(id)
920
- ? 'desktop'
921
- : 'unknown';
922
- /**
923
- * Aggregate votes from a poll message.
924
- *
925
- * Takes a poll creation message and its accumulated poll updates (from
926
- * `messages.update` events) and returns the vote tally per option.
927
- *
928
- * `pollUpdates` should contain pre-decrypted votes where `vote.selectedOptions`
929
- * are the SHA-256 hashes of the voted option names.
2
+ * Node-facing wrapper for the historical public deep import.
930
3
  *
931
- * @example
932
- * ```ts
933
- * sock.ev.on('messages.update', event => {
934
- * for (const { key, update } of event) {
935
- * if (update.pollUpdates) {
936
- * const pollMsg = await getMessageFromStore(key)
937
- * const votes = getAggregateVotesInPollMessage({
938
- * message: pollMsg.message,
939
- * pollUpdates: pollMsg.pollUpdates
940
- * })
941
- * console.log(votes) // [{ name: 'Yes', voters: ['jid1'] }, ...]
942
- * }
943
- * }
944
- * })
945
- * ```
4
+ * The shared socket graph imports `messages-core.ts` directly; consumers of
5
+ * this Node deep import get the same filesystem/media initialization as the
6
+ * package root without introducing Node runtime code into `/host`.
946
7
  */
947
- export function getAggregateVotesInPollMessage({ message, pollUpdates }, meId) {
948
- const opts = message?.pollCreationMessage?.options ||
949
- message?.pollCreationMessageV2?.options ||
950
- message?.pollCreationMessageV3?.options ||
951
- [];
952
- const voteHashMap = {};
953
- for (const opt of opts) {
954
- const name = opt.optionName || '';
955
- voteHashMap[sha256(Buffer.from(name)).toString()] = { name, voters: [] };
956
- }
957
- for (const update of pollUpdates || []) {
958
- const { vote } = update;
959
- if (!vote?.selectedOptions?.length)
960
- continue;
961
- for (const optionHash of vote.selectedOptions) {
962
- const hash = Buffer.from(optionHash).toString();
963
- let aggregate = voteHashMap[hash];
964
- if (!aggregate)
965
- aggregate = voteHashMap[hash] = { name: 'Unknown', voters: [] };
966
- aggregate.voters.push(getKeyAuthor(update.pollUpdateMessageKey, meId));
967
- }
968
- }
969
- return Object.values(voteHashMap);
970
- }
971
- export function getAggregateResponsesInEventMessage({ eventResponses }, meId) {
972
- const responseMap = {};
973
- for (const response of ['GOING', 'NOT_GOING', 'MAYBE']) {
974
- responseMap[response] = { response, responders: [] };
975
- }
976
- for (const update of eventResponses || []) {
977
- // Decrypted event responses carry this convenience field at runtime;
978
- // it is intentionally not part of the wire protobuf interface.
979
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
980
- const responseType = update.eventResponse || 'UNKNOWN';
981
- if (responseType !== 'UNKNOWN' && responseMap[responseType]) {
982
- responseMap[responseType].responders.push(getKeyAuthor(update.eventResponseMessageKey, meId));
983
- }
984
- }
985
- return Object.values(responseMap);
986
- }
987
- /** Group non-self message keys by chat and participant for bulk receipts. */
988
- export const aggregateMessageKeysNotFromMe = (keys) => {
989
- const keyMap = {};
990
- for (const { remoteJid, id, participant, fromMe } of keys) {
991
- if (fromMe)
992
- continue;
993
- const uniqueKey = `${remoteJid}:${participant || ''}`;
994
- keyMap[uniqueKey] || (keyMap[uniqueKey] = { jid: remoteJid, participant: participant, messageIds: [] });
995
- keyMap[uniqueKey].messageIds.push(id);
996
- }
997
- return Object.values(keyMap);
998
- };
999
- /** Upsert one receipt into a message's `userReceipt` collection. */
1000
- export const updateMessageWithReceipt = (msg, receipt) => {
1001
- msg.userReceipt = msg.userReceipt || [];
1002
- const existing = msg.userReceipt.find(item => item.userJid === receipt.userJid);
1003
- if (existing)
1004
- Object.assign(existing, receipt);
1005
- else
1006
- msg.userReceipt.push(receipt);
1007
- };
1008
- /** Replace the previous reaction from the same author, then append the latest. */
1009
- export const updateMessageWithReaction = (msg, reaction) => {
1010
- const author = getKeyAuthor(reaction.key || {});
1011
- const reactions = (msg.reactions || []).filter(item => getKeyAuthor(item.key || {}) !== author);
1012
- reaction.text = reaction.text || '';
1013
- reactions.push(reaction);
1014
- msg.reactions = reactions;
1015
- };
1016
- /** Replace the previous poll update from the same author. Empty votes remove it. */
1017
- export const updateMessageWithPollUpdate = (msg, update) => {
1018
- const author = getKeyAuthor(update.pollUpdateMessageKey);
1019
- const pollUpdates = (msg.pollUpdates || []).filter(item => getKeyAuthor(item.pollUpdateMessageKey) !== author);
1020
- if (update.vote?.selectedOptions?.length)
1021
- pollUpdates.push(update);
1022
- msg.pollUpdates = pollUpdates;
1023
- };
1024
- /** Replace the previous event response from the same author. */
1025
- export const updateMessageWithEventResponse = (msg, update) => {
1026
- const author = getKeyAuthor(update.eventResponseMessageKey);
1027
- const responses = (msg.eventResponses || []).filter(item => getKeyAuthor(item.eventResponseMessageKey) !== author);
1028
- responses.push(update);
1029
- msg.eventResponses = responses;
1030
- };
1031
- /** Checks whether the message contains one of the upstream media payloads. */
1032
- export const assertMediaContent = (content) => {
1033
- content = extractMessageContent(content);
1034
- const mediaContent = content?.documentMessage ||
1035
- content?.imageMessage ||
1036
- content?.videoMessage ||
1037
- content?.audioMessage ||
1038
- content?.stickerMessage;
1039
- if (!mediaContent) {
1040
- throw new Boom('given message is not a media message', { statusCode: 400, data: content });
1041
- }
1042
- return mediaContent;
1043
- };
8
+ import { nodeRuntime as initializedNodeRuntime } from '../Runtime/node.js';
9
+ void initializedNodeRuntime;
10
+ export * from './messages-core.js';
1044
11
  //# sourceMappingURL=messages.js.map