@vinzsocket/baileys 2.1.0 → 2.8.10

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 (35) hide show
  1. package/lib/Signal/Group/group_cipher.d.ts +1 -0
  2. package/lib/Signal/Group/group_cipher.js +38 -28
  3. package/lib/Signal/Group/queue-job.d.ts +2 -0
  4. package/lib/Signal/Group/queue-job.js +57 -0
  5. package/lib/Socket/groups.js +2 -0
  6. package/lib/Socket/messages-send.js +450 -496
  7. package/lib/Store/index.d.ts +4 -0
  8. package/lib/Store/index.js +4 -0
  9. package/lib/Store/make-cache-manager-store.d.ts +17 -0
  10. package/lib/Store/make-cache-manager-store.js +102 -0
  11. package/lib/Store/make-in-memory-store.d.ts +118 -0
  12. package/lib/Store/make-in-memory-store.js +427 -0
  13. package/lib/Store/make-ordered-dictionary.d.ts +14 -0
  14. package/lib/Store/make-ordered-dictionary.js +79 -0
  15. package/lib/Store/object-repository.d.ts +10 -0
  16. package/lib/Store/object-repository.js +23 -0
  17. package/lib/Types/Message.d.ts +12 -42
  18. package/lib/Utils/extended-messages.d.ts +73 -0
  19. package/lib/Utils/extended-messages.js +231 -0
  20. package/lib/Utils/index.d.ts +3 -0
  21. package/lib/Utils/index.js +3 -0
  22. package/lib/Utils/lid-resolver.d.ts +17 -0
  23. package/lib/Utils/lid-resolver.js +67 -0
  24. package/lib/Utils/mention.d.ts +27 -0
  25. package/lib/Utils/mention.js +134 -0
  26. package/lib/Utils/messages.js +44 -143
  27. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +8 -0
  28. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  29. package/lib/WAUSync/Protocols/index.d.ts +1 -0
  30. package/lib/WAUSync/Protocols/index.js +1 -0
  31. package/lib/WAUSync/USyncQuery.d.ts +1 -0
  32. package/lib/WAUSync/USyncQuery.js +5 -0
  33. package/lib/index.d.ts +1 -0
  34. package/lib/index.js +1 -0
  35. package/package.json +9 -8
@@ -0,0 +1,27 @@
1
+ export declare function normalizeMentions(mentions: string | string[] | null | undefined): string[];
2
+ export declare function applyMentions<T extends {
3
+ messageContextInfo?: {
4
+ mentionedJid?: string[];
5
+ };
6
+ interactiveMessage?: {
7
+ contextInfo?: {
8
+ mentionedJid?: string[];
9
+ };
10
+ };
11
+ }>(msg: T, mentions: string | string[] | null | undefined, contextInfo?: {
12
+ mentionedJid?: string[];
13
+ }): T;
14
+ export type TagAllOptions = {
15
+ getDisplayName?: (jid: string | undefined) => string | undefined;
16
+ header?: string;
17
+ footer?: string;
18
+ };
19
+ export type TagAllParticipant = {
20
+ id: string;
21
+ jid?: string;
22
+ phoneNumber?: string;
23
+ };
24
+ export declare function buildTagAllText(participants: TagAllParticipant[] | undefined, options?: TagAllOptions): {
25
+ text: string;
26
+ mentions: string[];
27
+ };
@@ -0,0 +1,134 @@
1
+ // mention.js
2
+ // Mention helpers: normalize mention JIDs into proper @s.whatsapp.net / @lid
3
+ // form, apply them onto a message object/contextInfo, and build a "tag all"
4
+ // text block from group participants — LID-aware, so it doesn't print raw
5
+ // LID digits as if they were a phone number when WhatsApp didn't disclose one.
6
+ import * as lidResolver from './lid-resolver.js';
7
+ const mentionCache = new Map();
8
+ /**
9
+ * Normalize mentions to proper JID format
10
+ * @param {string|string[]|null|undefined} mentions
11
+ * @returns {string[]}
12
+ */
13
+ export function normalizeMentions(mentions) {
14
+ const cacheKey = JSON.stringify(mentions);
15
+ if (mentionCache.has(cacheKey)) {
16
+ return mentionCache.get(cacheKey);
17
+ }
18
+ if (!mentions)
19
+ return [];
20
+ if (!Array.isArray(mentions))
21
+ mentions = [mentions];
22
+ const result = mentions
23
+ .map(jid => {
24
+ if (typeof jid !== 'string')
25
+ return null;
26
+ jid = jid.trim();
27
+ if (!jid)
28
+ return null;
29
+ // Already has @s.whatsapp.net or @lid
30
+ if (jid.includes('@s.whatsapp.net') || jid.includes('@lid')) {
31
+ return jid;
32
+ }
33
+ // Has @ but not complete
34
+ if (jid.includes('@')) {
35
+ return jid;
36
+ }
37
+ // Plain number
38
+ return jid + '@s.whatsapp.net';
39
+ })
40
+ .filter(Boolean);
41
+ mentionCache.set(cacheKey, result);
42
+ // Simple cache size limit
43
+ if (mentionCache.size > 1000)
44
+ mentionCache.clear();
45
+ return result;
46
+ }
47
+ /**
48
+ * Apply mentions into a message object (for use by custom content builders)
49
+ * @param {object} msg - The message content object
50
+ * @param {string|string[]|null} mentions
51
+ * @param {object} contextInfo - Optional contextInfo to also update
52
+ * @returns {object} msg
53
+ */
54
+ export function applyMentions(msg, mentions, contextInfo = {}) {
55
+ const normalized = normalizeMentions(mentions);
56
+ if (normalized.length === 0)
57
+ return msg;
58
+ // messageContextInfo
59
+ if (!msg.messageContextInfo)
60
+ msg.messageContextInfo = {};
61
+ if (!msg.messageContextInfo.mentionedJid)
62
+ msg.messageContextInfo.mentionedJid = [];
63
+ const existing = new Set(msg.messageContextInfo.mentionedJid);
64
+ for (const jid of normalized) {
65
+ if (!existing.has(jid)) {
66
+ msg.messageContextInfo.mentionedJid.push(jid);
67
+ existing.add(jid);
68
+ }
69
+ }
70
+ // contextInfo
71
+ if (contextInfo && typeof contextInfo === 'object') {
72
+ if (!contextInfo.mentionedJid)
73
+ contextInfo.mentionedJid = [];
74
+ for (const jid of normalized) {
75
+ if (!contextInfo.mentionedJid.includes(jid)) {
76
+ contextInfo.mentionedJid.push(jid);
77
+ }
78
+ }
79
+ }
80
+ // Extra for interactiveMessage
81
+ if (msg.interactiveMessage?.contextInfo) {
82
+ if (!msg.interactiveMessage.contextInfo.mentionedJid) {
83
+ msg.interactiveMessage.contextInfo.mentionedJid = [];
84
+ }
85
+ for (const jid of normalized) {
86
+ if (!msg.interactiveMessage.contextInfo.mentionedJid.includes(jid)) {
87
+ msg.interactiveMessage.contextInfo.mentionedJid.push(jid);
88
+ }
89
+ }
90
+ }
91
+ return msg;
92
+ }
93
+ /**
94
+ * Build a "tag all" text block + mentionedJid list from a group's participants,
95
+ * the way you'd get from sock.groupMetadata(jid).participants
96
+ *
97
+ * Handles the WhatsApp "LID" privacy rollout correctly: when a participant's
98
+ * phone number was NOT disclosed by WhatsApp (group addressingMode = 'lid' and
99
+ * no phone_number attr came back), we do NOT print the raw LID digits as if
100
+ * they were a phone number (e.g. "@206244447002720") since that's meaningless
101
+ * to humans. Instead we fall back to the member's display name if you have one
102
+ * (e.g. from your contact store / pushName cache), or a generic label.
103
+ *
104
+ * @param {Array<object>} participants - group.participants from groupMetadata()
105
+ * @param {object} [options]
106
+ * @param {(jid: string) => string|undefined} [options.getDisplayName] - optional lookup (e.g. store.contacts[jid]?.notify)
107
+ * @param {string} [options.header] - text placed above the list
108
+ * @param {string} [options.footer] - text placed below the list
109
+ * @returns {{ text: string, mentions: string[] }}
110
+ */
111
+ export function buildTagAllText(participants, options = {}) {
112
+ const { getDisplayName = lidResolver.getDisplayName, header = '', footer = '' } = options;
113
+ const lines = [];
114
+ const mentions = [];
115
+ for (const p of participants || []) {
116
+ // Prefer a real phone-number JID when WhatsApp actually disclosed one.
117
+ const realJid = p.jid && p.jid.endsWith('@s.whatsapp.net')
118
+ ? p.jid
119
+ : (p.phoneNumber ? (p.phoneNumber.includes('@') ? p.phoneNumber : `${p.phoneNumber}@s.whatsapp.net`) : null);
120
+ const mentionJid = realJid || p.id; // what we actually tag/ping (lid is fine for this)
121
+ mentions.push(mentionJid);
122
+ if (realJid) {
123
+ // We know the real phone number — safe & useful to show it.
124
+ lines.push(`@${realJid.split('@')[0]}`);
125
+ }
126
+ else {
127
+ // LID-only participant: don't print fake-looking digits.
128
+ const name = getDisplayName ? getDisplayName(p.id) : null;
129
+ lines.push(name ? `@${name}` : '@Member');
130
+ }
131
+ }
132
+ const body = [header, lines.join('\n'), footer].filter(Boolean).join('\n\n');
133
+ return { text: body, mentions };
134
+ }
@@ -1,4 +1,5 @@
1
1
  import { Boom } from '@hapi/boom';
2
+ import axios from 'axios';
2
3
  import { randomBytes } from 'crypto';
3
4
  import { promises as fs } from 'fs';
4
5
  import {} from 'stream';
@@ -9,7 +10,6 @@ import { isJidGroup, isJidNewsletter, isJidStatusBroadcast, jidNormalizedUser }
9
10
  import { sha256 } from './crypto.js';
10
11
  import { generateMessageIDV2, getKeyAuthor, unixTimestampSeconds } from './generics.js';
11
12
  import { downloadContentFromMessage, encryptedStream, generateThumbnail, getAudioDuration, getAudioWaveform, getRawMediaUploadData } from './messages-media.js';
12
- import { shouldIncludeReportingToken } from './reporting-utils.js';
13
13
  const MIMETYPE_MAP = {
14
14
  image: 'image/jpeg',
15
15
  video: 'video/mp4',
@@ -87,10 +87,10 @@ export const prepareWAMessageMedia = async (message, options) => {
87
87
  uploadData.mimetype = MIMETYPE_MAP[mediaType];
88
88
  }
89
89
  if (cacheableKey) {
90
- const mediaBuff = await options.mediaCache.get(cacheableKey);
90
+ const mediaBuff = options.mediaCache.get(cacheableKey);
91
91
  if (mediaBuff) {
92
92
  logger?.debug({ cacheableKey }, 'got media cache hit');
93
- const obj = proto.Message.decode(mediaBuff);
93
+ const obj = WAProto.Message.decode(mediaBuff);
94
94
  const key = `${mediaType}Message`;
95
95
  Object.assign(obj[key], { ...uploadData, media: undefined });
96
96
  return obj;
@@ -107,9 +107,9 @@ export const prepareWAMessageMedia = async (message, options) => {
107
107
  timeoutMs: options.mediaUploadTimeoutMs
108
108
  });
109
109
  await fs.unlink(filePath);
110
- const obj = WAProto.Message.fromObject({
110
+ const obj = WAProto.Message.create({
111
111
  // todo: add more support here
112
- [`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
112
+ [`${mediaType}Message`]: MessageTypeProto[mediaType].create({
113
113
  url: mediaUrl,
114
114
  directPath,
115
115
  fileSha256,
@@ -122,18 +122,15 @@ export const prepareWAMessageMedia = async (message, options) => {
122
122
  obj.ptvMessage = obj.videoMessage;
123
123
  delete obj.videoMessage;
124
124
  }
125
- if (obj.stickerMessage) {
126
- obj.stickerMessage.stickerSentTs = Date.now();
127
- }
128
125
  if (cacheableKey) {
129
126
  logger?.debug({ cacheableKey }, 'set cache');
130
- await options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish());
127
+ options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish());
131
128
  }
132
129
  return obj;
133
130
  }
134
131
  const requiresDurationComputation = mediaType === 'audio' && typeof uploadData.seconds === 'undefined';
135
132
  const requiresThumbnailComputation = (mediaType === 'image' || mediaType === 'video') && typeof uploadData['jpegThumbnail'] === 'undefined';
136
- const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true && typeof uploadData.waveform === 'undefined';
133
+ const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true;
137
134
  const requiresAudioBackground = options.backgroundColor && mediaType === 'audio' && uploadData.ptt === true;
138
135
  const requiresOriginalForSomeProcessing = requiresDurationComputation || requiresThumbnailComputation;
139
136
  const { mediaKey, encFilePath, originalFilePath, fileEncSha256, fileSha256, fileLength } = await encryptedStream(uploadData.media, options.mediaTypeOverride || mediaType, {
@@ -193,8 +190,8 @@ export const prepareWAMessageMedia = async (message, options) => {
193
190
  logger?.warn('failed to remove tmp file');
194
191
  }
195
192
  });
196
- const obj = WAProto.Message.fromObject({
197
- [`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
193
+ const obj = WAProto.Message.create({
194
+ [`${mediaType}Message`]: MessageTypeProto[mediaType].create({
198
195
  url: mediaUrl,
199
196
  directPath,
200
197
  mediaKey,
@@ -212,7 +209,7 @@ export const prepareWAMessageMedia = async (message, options) => {
212
209
  }
213
210
  if (cacheableKey) {
214
211
  logger?.debug({ cacheableKey }, 'set cache');
215
- await options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish());
212
+ options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish());
216
213
  }
217
214
  return obj;
218
215
  };
@@ -228,7 +225,7 @@ export const prepareDisappearingMessageSettingContent = (ephemeralExpiration) =>
228
225
  }
229
226
  }
230
227
  };
231
- return WAProto.Message.fromObject(content);
228
+ return WAProto.Message.create(content);
232
229
  };
233
230
  /**
234
231
  * Generate forwarded message content like WA does
@@ -260,20 +257,10 @@ export const generateForwardMessageContent = (message, forceForward) => {
260
257
  }
261
258
  return content;
262
259
  };
263
- export const hasNonNullishProperty = (message, key) => {
264
- return (typeof message === 'object' &&
265
- message !== null &&
266
- key in message &&
267
- message[key] !== null &&
268
- message[key] !== undefined);
269
- };
270
- function hasOptionalProperty(obj, key) {
271
- return typeof obj === 'object' && obj !== null && key in obj && obj[key] !== null;
272
- }
273
260
  export const generateWAMessageContent = async (message, options) => {
274
261
  var _a, _b;
275
262
  let m = {};
276
- if (hasNonNullishProperty(message, 'text')) {
263
+ if ('text' in message) {
277
264
  const extContent = { text: message.text };
278
265
  let urlInfo = message.linkPreview;
279
266
  if (typeof urlInfo === 'undefined') {
@@ -304,7 +291,7 @@ export const generateWAMessageContent = async (message, options) => {
304
291
  }
305
292
  m.extendedTextMessage = extContent;
306
293
  }
307
- else if (hasNonNullishProperty(message, 'contacts')) {
294
+ else if ('contacts' in message) {
308
295
  const contactLen = message.contacts.contacts.length;
309
296
  if (!contactLen) {
310
297
  throw new Boom('require atleast 1 contact', { statusCode: 400 });
@@ -316,25 +303,25 @@ export const generateWAMessageContent = async (message, options) => {
316
303
  m.contactsArrayMessage = WAProto.Message.ContactsArrayMessage.create(message.contacts);
317
304
  }
318
305
  }
319
- else if (hasNonNullishProperty(message, 'location')) {
306
+ else if ('location' in message) {
320
307
  m.locationMessage = WAProto.Message.LocationMessage.create(message.location);
321
308
  }
322
- else if (hasNonNullishProperty(message, 'react')) {
309
+ else if ('react' in message) {
323
310
  if (!message.react.senderTimestampMs) {
324
311
  message.react.senderTimestampMs = Date.now();
325
312
  }
326
313
  m.reactionMessage = WAProto.Message.ReactionMessage.create(message.react);
327
314
  }
328
- else if (hasNonNullishProperty(message, 'delete')) {
315
+ else if ('delete' in message) {
329
316
  m.protocolMessage = {
330
317
  key: message.delete,
331
318
  type: WAProto.Message.ProtocolMessage.Type.REVOKE
332
319
  };
333
320
  }
334
- else if (hasNonNullishProperty(message, 'forward')) {
321
+ else if ('forward' in message) {
335
322
  m = generateForwardMessageContent(message.forward, message.force);
336
323
  }
337
- else if (hasNonNullishProperty(message, 'disappearingMessagesInChat')) {
324
+ else if ('disappearingMessagesInChat' in message) {
338
325
  const exp = typeof message.disappearingMessagesInChat === 'boolean'
339
326
  ? message.disappearingMessagesInChat
340
327
  ? WA_DEFAULT_EPHEMERAL
@@ -342,7 +329,7 @@ export const generateWAMessageContent = async (message, options) => {
342
329
  : message.disappearingMessagesInChat;
343
330
  m = prepareDisappearingMessageSettingContent(exp);
344
331
  }
345
- else if (hasNonNullishProperty(message, 'groupInvite')) {
332
+ else if ('groupInvite' in message) {
346
333
  m.groupInviteMessage = {};
347
334
  m.groupInviteMessage.inviteCode = message.groupInvite.inviteCode;
348
335
  m.groupInviteMessage.inviteExpiration = message.groupInvite.inviteExpiration;
@@ -354,15 +341,14 @@ export const generateWAMessageContent = async (message, options) => {
354
341
  if (options.getProfilePicUrl) {
355
342
  const pfpUrl = await options.getProfilePicUrl(message.groupInvite.jid, 'preview');
356
343
  if (pfpUrl) {
357
- const resp = await fetch(pfpUrl, { method: 'GET', dispatcher: options?.options?.dispatcher });
358
- if (resp.ok) {
359
- const buf = Buffer.from(await resp.arrayBuffer());
360
- m.groupInviteMessage.jpegThumbnail = buf;
344
+ const resp = await axios.get(pfpUrl, { responseType: 'arraybuffer' });
345
+ if (resp.status === 200) {
346
+ m.groupInviteMessage.jpegThumbnail = resp.data;
361
347
  }
362
348
  }
363
349
  }
364
350
  }
365
- else if (hasNonNullishProperty(message, 'pin')) {
351
+ else if ('pin' in message) {
366
352
  m.pinInChatMessage = {};
367
353
  m.messageContextInfo = {};
368
354
  m.pinInChatMessage.key = message.pin;
@@ -370,7 +356,7 @@ export const generateWAMessageContent = async (message, options) => {
370
356
  m.pinInChatMessage.senderTimestampMs = Date.now();
371
357
  m.messageContextInfo.messageAddOnDurationInSecs = message.type === 1 ? message.time || 86400 : 0;
372
358
  }
373
- else if (hasNonNullishProperty(message, 'buttonReply')) {
359
+ else if ('buttonReply' in message) {
374
360
  switch (message.type) {
375
361
  case 'template':
376
362
  m.templateButtonReplyMessage = {
@@ -388,11 +374,11 @@ export const generateWAMessageContent = async (message, options) => {
388
374
  break;
389
375
  }
390
376
  }
391
- else if (hasOptionalProperty(message, 'ptv') && message.ptv) {
377
+ else if ('ptv' in message && message.ptv) {
392
378
  const { videoMessage } = await prepareWAMessageMedia({ video: message.video }, options);
393
379
  m.ptvMessage = videoMessage;
394
380
  }
395
- else if (hasNonNullishProperty(message, 'product')) {
381
+ else if ('product' in message) {
396
382
  const { imageMessage } = await prepareWAMessageMedia({ image: message.product.productImage }, options);
397
383
  m.productMessage = WAProto.Message.ProductMessage.create({
398
384
  ...message,
@@ -402,10 +388,10 @@ export const generateWAMessageContent = async (message, options) => {
402
388
  }
403
389
  });
404
390
  }
405
- else if (hasNonNullishProperty(message, 'listReply')) {
391
+ else if ('listReply' in message) {
406
392
  m.listResponseMessage = { ...message.listReply };
407
393
  }
408
- else if (hasNonNullishProperty(message, 'event')) {
394
+ else if ('event' in message) {
409
395
  m.eventMessage = {};
410
396
  const startTime = Math.floor(message.event.startDate.getTime() / 1000);
411
397
  if (message.event.call && options.getCallLink) {
@@ -425,7 +411,7 @@ export const generateWAMessageContent = async (message, options) => {
425
411
  m.eventMessage.isScheduleCall = message.event.isScheduleCall ?? false;
426
412
  m.eventMessage.location = message.event.location;
427
413
  }
428
- else if (hasNonNullishProperty(message, 'poll')) {
414
+ else if ('poll' in message) {
429
415
  (_a = message.poll).selectableCount || (_a.selectableCount = 0);
430
416
  (_b = message.poll).toAnnouncementGroup || (_b.toAnnouncementGroup = false);
431
417
  if (!Array.isArray(message.poll.values)) {
@@ -460,70 +446,33 @@ export const generateWAMessageContent = async (message, options) => {
460
446
  }
461
447
  }
462
448
  }
463
- else if (hasNonNullishProperty(message, 'album')) {
464
- m.albumMessage = {
465
- expectedImageCount: message.album.expectedImageCount,
466
- expectedVideoCount: message.album.expectedVideoCount
467
- };
468
- }
469
- else if (hasNonNullishProperty(message, 'sharePhoneNumber')) {
449
+ else if ('sharePhoneNumber' in message) {
470
450
  m.protocolMessage = {
471
451
  type: proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER
472
452
  };
473
453
  }
474
- else if (hasNonNullishProperty(message, 'requestPhoneNumber')) {
454
+ else if ('requestPhoneNumber' in message) {
475
455
  m.requestPhoneNumberMessage = {};
476
456
  }
477
- else if (hasNonNullishProperty(message, 'limitSharing')) {
478
- m.protocolMessage = {
479
- type: proto.Message.ProtocolMessage.Type.LIMIT_SHARING,
480
- limitSharing: {
481
- sharingLimited: message.limitSharing === true,
482
- trigger: 1,
483
- limitSharingSettingTimestamp: Date.now(),
484
- initiatedByMe: true
485
- }
486
- };
487
- }
488
457
  else {
489
458
  m = await prepareWAMessageMedia(message, options);
490
459
  }
491
- if (hasNonNullishProperty(message, 'sections')) {
492
- m = {
493
- listMessage: {
494
- sections: message.sections,
495
- buttonText: message.buttonText,
496
- title: message.title,
497
- footerText: message.footer,
498
- description: message.text,
499
- listType: WAProto.Message.ListMessage.ListType.SINGLE_SELECT
500
- }
501
- };
502
- }
503
- if (hasOptionalProperty(message, 'viewOnce') && !!message.viewOnce) {
460
+ if ('viewOnce' in message && !!message.viewOnce) {
504
461
  m = { viewOnceMessage: { message: m } };
505
462
  }
506
- if ((hasOptionalProperty(message, 'mentions') && message.mentions?.length) ||
507
- (hasOptionalProperty(message, 'mentionAll') && message.mentionAll)) {
463
+ if ('mentions' in message && message.mentions?.length) {
508
464
  const messageType = Object.keys(m)[0];
509
465
  const key = m[messageType];
510
- if (key && 'contextInfo' in key) {
511
- key.contextInfo = key.contextInfo || {};
512
- if (message.mentions?.length) {
513
- key.contextInfo.mentionedJid = message.mentions;
514
- }
515
- if (message.mentionAll) {
516
- key.contextInfo.nonJidMentions = 1;
517
- }
466
+ if ('contextInfo' in key && !!key.contextInfo) {
467
+ key.contextInfo.mentionedJid = message.mentions;
518
468
  }
519
469
  else if (key) {
520
470
  key.contextInfo = {
521
- mentionedJid: message.mentions,
522
- nonJidMentions: message.mentionAll ? 1 : 0
471
+ mentionedJid: message.mentions
523
472
  };
524
473
  }
525
474
  }
526
- if (hasOptionalProperty(message, 'edit')) {
475
+ if ('edit' in message) {
527
476
  m = {
528
477
  protocolMessage: {
529
478
  key: message.edit,
@@ -533,7 +482,7 @@ export const generateWAMessageContent = async (message, options) => {
533
482
  }
534
483
  };
535
484
  }
536
- if (hasOptionalProperty(message, 'contextInfo') && !!message.contextInfo) {
485
+ if ('contextInfo' in message && !!message.contextInfo) {
537
486
  const messageType = Object.keys(m)[0];
538
487
  const key = m[messageType];
539
488
  if ('contextInfo' in key && !!key.contextInfo) {
@@ -543,21 +492,6 @@ export const generateWAMessageContent = async (message, options) => {
543
492
  key.contextInfo = message.contextInfo;
544
493
  }
545
494
  }
546
- if (hasOptionalProperty(message, 'albumParentKey') && !!message.albumParentKey) {
547
- m.messageContextInfo = {
548
- ...m.messageContextInfo,
549
- messageAssociation: {
550
- associationType: WAProto.MessageAssociation.AssociationType.MEDIA_ALBUM,
551
- parentMessageKey: message.albumParentKey
552
- }
553
- };
554
- }
555
- if (shouldIncludeReportingToken(m)) {
556
- m.messageContextInfo = m.messageContextInfo || {};
557
- if (!m.messageContextInfo.messageSecret) {
558
- m.messageContextInfo.messageSecret = randomBytes(32);
559
- }
560
- }
561
495
  return WAProto.Message.create(m);
562
496
  };
563
497
  export const generateWAMessageFromContent = (jid, message, options) => {
@@ -572,7 +506,7 @@ export const generateWAMessageFromContent = (jid, message, options) => {
572
506
  const { quoted, userJid } = options;
573
507
  if (quoted && !isJidNewsletter(jid)) {
574
508
  const participant = quoted.key.fromMe
575
- ? userJid // TODO: Add support for LIDs
509
+ ? userJid
576
510
  : quoted.participant || quoted.key.participant || quoted.key.remoteJid;
577
511
  let quotedMsg = normalizeMessageContent(quoted.message);
578
512
  const msgType = getContentType(quotedMsg);
@@ -622,10 +556,10 @@ export const generateWAMessageFromContent = (jid, message, options) => {
622
556
  message: message,
623
557
  messageTimestamp: timestamp,
624
558
  messageStubParameters: [],
625
- participant: isJidGroup(jid) || isJidStatusBroadcast(jid) ? userJid : undefined, // TODO: Add support for LIDs
559
+ participant: isJidGroup(jid) || isJidStatusBroadcast(jid) ? userJid : undefined,
626
560
  status: WAMessageStatus.PENDING
627
561
  };
628
- return WAProto.WebMessageInfo.fromObject(messageJSON);
562
+ return WAProto.WebMessageInfo.create(messageJSON);
629
563
  };
630
564
  export const generateWAMessage = async (jid, content, options) => {
631
565
  // ensure msg ID is with every log
@@ -666,10 +600,7 @@ export const normalizeMessageContent = (content) => {
666
600
  message?.documentWithCaptionMessage ||
667
601
  message?.viewOnceMessageV2 ||
668
602
  message?.viewOnceMessageV2Extension ||
669
- message?.editedMessage ||
670
- message?.associatedChildMessage ||
671
- message?.groupStatusMessage ||
672
- message?.groupStatusMessageV2);
603
+ message?.editedMessage);
673
604
  }
674
605
  };
675
606
  /**
@@ -751,13 +682,6 @@ export const updateMessageWithPollUpdate = (msg, update) => {
751
682
  }
752
683
  msg.pollUpdates = reactions;
753
684
  };
754
- /** Update the message with a new event response */
755
- export const updateMessageWithEventResponse = (msg, update) => {
756
- const authorID = getKeyAuthor(update.eventResponseMessageKey);
757
- const responses = (msg.eventResponses || []).filter(r => getKeyAuthor(r.eventResponseMessageKey) !== authorID);
758
- responses.push(update);
759
- msg.eventResponses = responses;
760
- };
761
685
  /**
762
686
  * Aggregates all poll updates in a poll.
763
687
  * @param msg the poll creation message
@@ -797,29 +721,6 @@ export function getAggregateVotesInPollMessage({ message, pollUpdates }, meId) {
797
721
  }
798
722
  return Object.values(voteHashMap);
799
723
  }
800
- /**
801
- * Aggregates all event responses in an event message.
802
- * @param msg the event creation message
803
- * @param meId your jid
804
- * @returns A list of response types & their responders
805
- */
806
- export function getAggregateResponsesInEventMessage({ eventResponses }, meId) {
807
- const responseTypes = ['GOING', 'NOT_GOING', 'MAYBE'];
808
- const responseMap = {};
809
- for (const type of responseTypes) {
810
- responseMap[type] = {
811
- response: type,
812
- responders: []
813
- };
814
- }
815
- for (const update of eventResponses || []) {
816
- const responseType = update.eventResponse || 'UNKNOWN';
817
- if (responseType !== 'UNKNOWN' && responseMap[responseType]) {
818
- responseMap[responseType].responders.push(getKeyAuthor(update.eventResponseMessageKey, meId));
819
- }
820
- }
821
- return Object.values(responseMap);
822
- }
823
724
  /** Given a list of message keys, aggregates them by chat & sender. Useful for sending read receipts in bulk */
824
725
  export const aggregateMessageKeysNotFromMe = (keys) => {
825
726
  const keyMap = {};
@@ -845,8 +746,8 @@ const REUPLOAD_REQUIRED_STATUS = [410, 404];
845
746
  export const downloadMediaMessage = async (message, type, options, ctx) => {
846
747
  const result = await downloadMsg().catch(async (error) => {
847
748
  if (ctx &&
848
- typeof error?.status === 'number' && // treat errors with status as HTTP failures requiring reupload
849
- REUPLOAD_REQUIRED_STATUS.includes(error.status)) {
749
+ axios.isAxiosError(error) && // check if the message requires a reupload
750
+ REUPLOAD_REQUIRED_STATUS.includes(error.response?.status)) {
850
751
  ctx.logger.info({ key: message.key }, 'sending reupload media request...');
851
752
  // request reupload
852
753
  message = await ctx.reuploadRequest(message);
@@ -0,0 +1,8 @@
1
+ import type { USyncQueryProtocol } from '../../Types/USync.js';
2
+ import type { BinaryNode } from '../../WABinary/index.js';
3
+ export declare class USyncUsernameProtocol implements USyncQueryProtocol {
4
+ name: string;
5
+ getQueryElement(): BinaryNode;
6
+ getUserElement(): null;
7
+ parser(node: BinaryNode): string | null;
8
+ }
@@ -0,0 +1,24 @@
1
+ import { assertNodeErrorFree } from '../../WABinary/index.js';
2
+ // Look up a user's WhatsApp username via a USync query.
3
+ // Mirrors the existing protocol files (UsyncLIDProtocol.js etc) in this folder.
4
+ export class USyncUsernameProtocol {
5
+ constructor() {
6
+ this.name = 'username';
7
+ }
8
+ getQueryElement() {
9
+ return {
10
+ tag: 'username',
11
+ attrs: {}
12
+ };
13
+ }
14
+ getUserElement() {
15
+ return null;
16
+ }
17
+ parser(node) {
18
+ if (node.tag === 'username') {
19
+ assertNodeErrorFree(node);
20
+ return typeof node.content === 'string' ? node.content : null;
21
+ }
22
+ return null;
23
+ }
24
+ }
@@ -2,4 +2,5 @@ export * from './USyncDeviceProtocol.js';
2
2
  export * from './USyncContactProtocol.js';
3
3
  export * from './USyncStatusProtocol.js';
4
4
  export * from './USyncDisappearingModeProtocol.js';
5
+ export * from './USyncUsernameProtocol.js';
5
6
  //# sourceMappingURL=index.d.ts.map
@@ -2,4 +2,5 @@ export * from './USyncDeviceProtocol.js';
2
2
  export * from './USyncContactProtocol.js';
3
3
  export * from './USyncStatusProtocol.js';
4
4
  export * from './USyncDisappearingModeProtocol.js';
5
+ export * from './USyncUsernameProtocol.js';
5
6
  //# sourceMappingURL=index.js.map
@@ -25,5 +25,6 @@ export declare class USyncQuery {
25
25
  withDisappearingModeProtocol(): this;
26
26
  withBotProfileProtocol(): this;
27
27
  withLIDProtocol(): this;
28
+ withUsernameProtocol(): this;
28
29
  }
29
30
  //# sourceMappingURL=USyncQuery.d.ts.map
@@ -1,6 +1,7 @@
1
1
  import { getBinaryNodeChild } from '../WABinary/index.js';
2
2
  import { USyncBotProfileProtocol } from './Protocols/UsyncBotProfileProtocol.js';
3
3
  import { USyncLIDProtocol } from './Protocols/UsyncLIDProtocol.js';
4
+ import { USyncUsernameProtocol } from './Protocols/USyncUsernameProtocol.js';
4
5
  import { USyncContactProtocol, USyncDeviceProtocol, USyncDisappearingModeProtocol, USyncStatusProtocol } from './Protocols/index.js';
5
6
  import { USyncUser } from './USyncUser.js';
6
7
  export class USyncQuery {
@@ -87,5 +88,9 @@ export class USyncQuery {
87
88
  this.protocols.push(new USyncLIDProtocol());
88
89
  return this;
89
90
  }
91
+ withUsernameProtocol() {
92
+ this.protocols.push(new USyncUsernameProtocol());
93
+ return this;
94
+ }
90
95
  }
91
96
  //# sourceMappingURL=USyncQuery.js.map
package/lib/index.d.ts CHANGED
@@ -2,6 +2,7 @@ import makeWASocket from './Socket/index.js';
2
2
  export * from '../WAProto/index.js';
3
3
  export * from './Utils/index.js';
4
4
  export * from './Types/index.js';
5
+ export * from './Store/index.js';
5
6
  export * from './Defaults/index.js';
6
7
  export * from './WABinary/index.js';
7
8
  export * from './WAM/index.js';
package/lib/index.js CHANGED
@@ -2,6 +2,7 @@ import makeWASocket from './Socket/index.js';
2
2
  export * from '../WAProto/index.js';
3
3
  export * from './Utils/index.js';
4
4
  export * from './Types/index.js';
5
+ export * from './Store/index.js';
5
6
  export * from './Defaults/index.js';
6
7
  export * from './WABinary/index.js';
7
8
  export * from './WAM/index.js';