@pontalabs/baileys 1.0.6 → 1.0.7

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 (185) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +839 -267
  3. package/WAProto/GenerateStatics.sh +4 -3
  4. package/WAProto/WAProto.proto +511 -1215
  5. package/WAProto/index.d.ts +55 -14017
  6. package/WAProto/index.js +29 -97689
  7. package/lib/Defaults/index.d.ts +74 -72
  8. package/lib/Defaults/index.js +108 -94
  9. package/lib/Signal/Group/ciphertext-message.d.ts +7 -8
  10. package/lib/Signal/Group/ciphertext-message.js +16 -9
  11. package/lib/Signal/Group/group-session-builder.d.ts +13 -11
  12. package/lib/Signal/Group/group-session-builder.js +61 -19
  13. package/lib/Signal/Group/group_cipher.d.ts +16 -14
  14. package/lib/Signal/Group/group_cipher.js +70 -41
  15. package/lib/Signal/Group/index.d.ts +11 -12
  16. package/lib/Signal/Group/index.js +61 -12
  17. package/lib/Signal/Group/keyhelper.d.ts +14 -9
  18. package/lib/Signal/Group/keyhelper.js +58 -10
  19. package/lib/Signal/Group/sender-chain-key.d.ts +13 -13
  20. package/lib/Signal/Group/sender-chain-key.js +34 -13
  21. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -16
  22. package/lib/Signal/Group/sender-key-distribution-message.js +36 -28
  23. package/lib/Signal/Group/sender-key-message.d.ts +18 -18
  24. package/lib/Signal/Group/sender-key-message.js +45 -38
  25. package/lib/Signal/Group/sender-key-name.d.ts +15 -14
  26. package/lib/Signal/Group/sender-key-name.js +31 -20
  27. package/lib/Signal/Group/sender-key-record.d.ts +25 -24
  28. package/lib/Signal/Group/sender-key-record.js +35 -18
  29. package/lib/Signal/Group/sender-key-state.d.ts +34 -29
  30. package/lib/Signal/Group/sender-key-state.js +100 -37
  31. package/lib/Signal/Group/sender-message-key.d.ts +10 -11
  32. package/lib/Signal/Group/sender-message-key.js +22 -15
  33. package/lib/Signal/libsignal.d.ts +8 -5
  34. package/lib/Signal/libsignal.js +142 -288
  35. package/lib/Signal/lid-mapping.d.ts +28 -23
  36. package/lib/Signal/lid-mapping.js +184 -277
  37. package/lib/Socket/Client/index.d.ts +2 -3
  38. package/lib/Socket/Client/index.js +22 -3
  39. package/lib/Socket/Client/types.d.ts +15 -15
  40. package/lib/Socket/Client/types.js +15 -8
  41. package/lib/Socket/Client/websocket.d.ts +12 -12
  42. package/lib/Socket/Client/websocket.js +37 -29
  43. package/lib/Socket/business.d.ts +178 -208
  44. package/lib/Socket/business.js +127 -91
  45. package/lib/Socket/chats.d.ts +93 -120
  46. package/lib/Socket/chats.js +652 -727
  47. package/lib/Socket/community.js +10 -2
  48. package/lib/Socket/groups.d.ts +111 -143
  49. package/lib/Socket/groups.js +186 -165
  50. package/lib/Socket/index.d.ts +183 -252
  51. package/lib/Socket/index.js +18 -38
  52. package/lib/Socket/messages-recv.d.ts +167 -196
  53. package/lib/Socket/messages-recv.js +1567 -1443
  54. package/lib/Socket/messages-send.d.ts +158 -192
  55. package/lib/Socket/messages-send.js +1208 -1102
  56. package/lib/Socket/newsletter.d.ts +138 -163
  57. package/lib/Socket/newsletter.js +249 -153
  58. package/lib/Socket/socket.d.ts +36 -50
  59. package/lib/Socket/socket.js +820 -749
  60. package/lib/Store/index.d.ts +4 -4
  61. package/lib/Store/index.js +24 -4
  62. package/lib/Store/make-in-memory-store.d.ts +104 -44
  63. package/lib/Store/make-in-memory-store.js +213 -199
  64. package/lib/Store/make-ordered-dictionary.d.ts +12 -13
  65. package/lib/Store/make-ordered-dictionary.js +45 -38
  66. package/lib/Store/object-repository.d.ts +10 -11
  67. package/lib/Store/object-repository.js +16 -9
  68. package/lib/Types/Auth.d.ts +97 -93
  69. package/lib/Types/Auth.js +3 -2
  70. package/lib/Types/Bussines.js +3 -2
  71. package/lib/Types/Call.d.ts +13 -14
  72. package/lib/Types/Call.js +3 -2
  73. package/lib/Types/Chat.d.ts +97 -78
  74. package/lib/Types/Chat.js +9 -8
  75. package/lib/Types/Contact.d.ts +9 -12
  76. package/lib/Types/Contact.js +3 -2
  77. package/lib/Types/Events.d.ts +176 -206
  78. package/lib/Types/Events.js +3 -2
  79. package/lib/Types/GroupMetadata.d.ts +48 -53
  80. package/lib/Types/GroupMetadata.js +3 -2
  81. package/lib/Types/Label.d.ts +14 -13
  82. package/lib/Types/Label.js +30 -24
  83. package/lib/Types/LabelAssociation.d.ts +20 -15
  84. package/lib/Types/LabelAssociation.js +12 -6
  85. package/lib/Types/Message.d.ts +412 -248
  86. package/lib/Types/Message.js +19 -17
  87. package/lib/Types/Product.d.ts +71 -58
  88. package/lib/Types/Product.js +3 -2
  89. package/lib/Types/Signal.d.ts +82 -71
  90. package/lib/Types/Signal.js +3 -2
  91. package/lib/Types/Socket.d.ts +81 -76
  92. package/lib/Types/Socket.js +3 -3
  93. package/lib/Types/State.d.ts +19 -75
  94. package/lib/Types/State.js +14 -56
  95. package/lib/Types/USync.d.ts +8 -8
  96. package/lib/Types/USync.js +3 -2
  97. package/lib/Types/index.d.ts +62 -47
  98. package/lib/Types/index.js +50 -26
  99. package/lib/Utils/auth-utils.d.ts +10 -13
  100. package/lib/Utils/auth-utils.js +472 -213
  101. package/lib/Utils/business.d.ts +20 -14
  102. package/lib/Utils/business.js +134 -110
  103. package/lib/Utils/chat-utils.d.ts +70 -88
  104. package/lib/Utils/chat-utils.js +403 -466
  105. package/lib/Utils/crypto.d.ts +46 -27
  106. package/lib/Utils/crypto.js +188 -117
  107. package/lib/Utils/decode-wa-message.d.ts +45 -58
  108. package/lib/Utils/decode-wa-message.js +311 -212
  109. package/lib/Utils/event-buffer.d.ts +17 -14
  110. package/lib/Utils/event-buffer.js +296 -321
  111. package/lib/Utils/generics.d.ts +92 -66
  112. package/lib/Utils/generics.js +436 -270
  113. package/lib/Utils/history.d.ts +23 -24
  114. package/lib/Utils/history.js +76 -106
  115. package/lib/Utils/index.d.ts +21 -24
  116. package/lib/Utils/index.js +41 -24
  117. package/lib/Utils/link-preview.d.ts +14 -12
  118. package/lib/Utils/link-preview.js +75 -40
  119. package/lib/Utils/logger.d.ts +11 -10
  120. package/lib/Utils/logger.js +7 -3
  121. package/lib/Utils/lt-hash.d.ts +14 -8
  122. package/lib/Utils/lt-hash.js +53 -3
  123. package/lib/Utils/make-mutex.d.ts +7 -7
  124. package/lib/Utils/make-mutex.js +44 -28
  125. package/lib/Utils/message-retry-manager.d.ts +88 -115
  126. package/lib/Utils/message-retry-manager.js +160 -265
  127. package/lib/Utils/messages-media.d.ts +107 -105
  128. package/lib/Utils/messages-media.js +619 -548
  129. package/lib/Utils/messages.d.ts +66 -52
  130. package/lib/Utils/messages.js +1558 -1730
  131. package/lib/Utils/noise-handler.d.ts +18 -18
  132. package/lib/Utils/noise-handler.js +130 -176
  133. package/lib/Utils/process-message.d.ts +32 -43
  134. package/lib/Utils/process-message.js +282 -484
  135. package/lib/Utils/rich-message-utils.js +724 -1220
  136. package/lib/Utils/signal.d.ts +32 -37
  137. package/lib/Utils/signal.js +105 -140
  138. package/lib/Utils/use-multi-file-auth-state.d.ts +5 -5
  139. package/lib/Utils/use-multi-file-auth-state.js +120 -70
  140. package/lib/Utils/use-single-file-auth-state.d.ts +13 -11
  141. package/lib/Utils/use-single-file-auth-state.js +66 -92
  142. package/lib/Utils/validate-connection.d.ts +13 -11
  143. package/lib/Utils/validate-connection.js +113 -128
  144. package/lib/WABinary/constants.d.ts +27 -25
  145. package/lib/WABinary/constants.js +1292 -1451
  146. package/lib/WABinary/decode.d.ts +9 -7
  147. package/lib/WABinary/decode.js +189 -163
  148. package/lib/WABinary/encode.d.ts +3 -3
  149. package/lib/WABinary/encode.js +155 -110
  150. package/lib/WABinary/generic-utils.d.ts +27 -14
  151. package/lib/WABinary/generic-utils.js +105 -177
  152. package/lib/WABinary/index.d.ts +5 -6
  153. package/lib/WABinary/index.js +25 -6
  154. package/lib/WABinary/jid-utils.d.ts +54 -41
  155. package/lib/WABinary/jid-utils.js +152 -83
  156. package/lib/WABinary/types.d.ts +13 -10
  157. package/lib/WABinary/types.js +3 -2
  158. package/lib/WAM/BinaryInfo.d.ts +15 -8
  159. package/lib/WAM/BinaryInfo.js +14 -7
  160. package/lib/WAM/constants.d.ts +37 -30
  161. package/lib/WAM/constants.js +11983 -19465
  162. package/lib/WAM/encode.d.ts +3 -3
  163. package/lib/WAM/encode.js +109 -95
  164. package/lib/WAM/index.d.ts +3 -4
  165. package/lib/WAM/index.js +23 -4
  166. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -9
  167. package/lib/WAUSync/Protocols/USyncContactProtocol.js +21 -37
  168. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -19
  169. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +26 -18
  170. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -11
  171. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +20 -12
  172. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -11
  173. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +24 -16
  174. package/lib/WAUSync/Protocols/index.d.ts +6 -6
  175. package/lib/WAUSync/Protocols/index.js +26 -6
  176. package/lib/WAUSync/USyncQuery.d.ts +28 -27
  177. package/lib/WAUSync/USyncQuery.js +62 -68
  178. package/lib/WAUSync/USyncUser.d.ts +10 -15
  179. package/lib/WAUSync/USyncUser.js +19 -20
  180. package/lib/WAUSync/index.d.ts +3 -4
  181. package/lib/WAUSync/index.js +23 -4
  182. package/lib/index.d.ts +12 -11
  183. package/lib/index.js +39 -12
  184. package/package.json +42 -86
  185. package/engine-requirements.js +0 -10
@@ -1,55 +1,66 @@
1
- import keyedDB from '@adiwajshing/keyed-db';
2
- import { writeFileSync, readFileSync, existsSync } from 'fs';
3
- import { WAProto } from '../Types/index.js';
4
- import { LabelAssociationType } from '../Types/LabelAssociation.js';
5
- import { DEFAULT_CONNECTION_CONFIG } from '../Defaults/index.js';
6
- import { md5, toNumber, updateMessageWithReceipt, updateMessageWithReaction } from '../Utils/index.js';
7
- import { jidDecode, jidNormalizedUser } from '../WABinary/index.js';
8
- import { makeOrderedDictionary } from './make-ordered-dictionary.js';
9
- import { ObjectRepository } from './object-repository.js';
10
- export const waChatKey = (pin) => ({
1
+ "use strict"
2
+
3
+ var __importDefault = (this && this.__importDefault) || function (mod) {
4
+ return (mod && mod.__esModule) ? mod : { "default": mod }
5
+ }
6
+
7
+ Object.defineProperty(exports, "__esModule", { value: true })
8
+
9
+ const WAProto_1 = require("../../WAProto")
10
+ const Defaults_1 = require("../Defaults")
11
+ const LabelAssociation_1 = require("../Types/LabelAssociation")
12
+ const Utils_1 = require("../Utils")
13
+ const WABinary_1 = require("../WABinary")
14
+ const Store_1 = require("./make-ordered-dictionary")
15
+ const object_repository_1 = require("./object-repository")
16
+
17
+ const waChatKey = (pin) => ({
11
18
  key: (c) => (pin ? (c.pinned ? '1' : '0') : '') + (c.archived ? '0' : '1') + (c.conversationTimestamp ? c.conversationTimestamp.toString(16).padStart(8, '0') : '') + c.id,
12
19
  compare: (k1, k2) => k2.localeCompare(k1)
13
- });
14
- export const waMessageID = (m) => m.key.id || '';
15
- export const waLabelAssociationKey = {
16
- key: (la) => (la.type === LabelAssociationType.Chat ? la.chatId + la.labelId : la.chatId + la.messageId + la.labelId),
20
+ })
21
+
22
+ const waMessageID = (m) => m.key.id || ''
23
+
24
+ const waLabelAssociationKey = {
25
+ key: (la) => (la.type === LabelAssociation_1.LabelAssociationType.Chat ? la.chatId + la.labelId : la.chatId + la.messageId + la.labelId),
17
26
  compare: (k1, k2) => k2.localeCompare(k1)
18
- };
19
- const makeMessagesDictionary = () => makeOrderedDictionary(waMessageID);
20
- export const makeInMemoryStore = (config = {}) => {
21
- const socket = config.socket;
22
- const chatKey = config.chatKey || waChatKey(true);
23
- const labelAssociationKey = config.labelAssociationKey || waLabelAssociationKey;
24
- const logger = config.logger || DEFAULT_CONNECTION_CONFIG.logger.child({ stream: 'in-mem-store' });
25
- const KeyedDB = keyedDB?.default ?? keyedDB;
26
- const chats = new KeyedDB(chatKey, c => c.id);
27
- const messages = {};
28
- const contacts = {};
29
- const groupMetadata = {};
30
- const presences = {};
31
- const state = { connection: 'close' };
32
- const labels = new ObjectRepository();
33
- const labelAssociations = new KeyedDB(labelAssociationKey, labelAssociationKey.key);
27
+ }
28
+
29
+ const makeMessagesDictionary = () => Store_1.makeOrderedDictionary(waMessageID)
30
+
31
+ const makeInMemoryStore = (config) => {
32
+ const socket = config.socket
33
+ const chatKey = config.chatKey || waChatKey(true)
34
+ const labelAssociationKey = config.labelAssociationKey || waLabelAssociationKey
35
+ const logger = config.logger || Defaults_1.DEFAULT_CONNECTION_CONFIG.logger.child({ stream: 'in-mem-store' })
36
+ const KeyedDB = require('@adiwajshing/keyed-db').default
37
+ const chats = new KeyedDB(chatKey, c => c.id)
38
+ const messages = {}
39
+ const contacts = {}
40
+ const groupMetadata = {}
41
+ const presences = {}
42
+ const state = { connection: 'close' }
43
+ const labels = new object_repository_1.ObjectRepository()
44
+ const labelAssociations = new KeyedDB(labelAssociationKey, labelAssociationKey.key)
34
45
  const assertMessageList = (jid) => {
35
46
  if (!messages[jid]) {
36
- messages[jid] = makeMessagesDictionary();
47
+ messages[jid] = makeMessagesDictionary()
37
48
  }
38
- return messages[jid];
39
- };
49
+ return messages[jid]
50
+ }
40
51
  const contactsUpsert = (newContacts) => {
41
- const oldContacts = new Set(Object.keys(contacts));
52
+ const oldContacts = new Set(Object.keys(contacts))
42
53
  for (const contact of newContacts) {
43
- oldContacts.delete(contact.id);
44
- contacts[contact.id] = Object.assign(contacts[contact.id] || {}, contact);
54
+ oldContacts.delete(contact.id)
55
+ contacts[contact.id] = Object.assign(contacts[contact.id] || {}, contact)
45
56
  }
46
- return oldContacts;
47
- };
57
+ return oldContacts
58
+ }
48
59
  const labelsUpsert = (newLabels) => {
49
60
  for (const label of newLabels) {
50
- labels.upsertById(label.id, label);
61
+ labels.upsertById(label.id, label)
51
62
  }
52
- };
63
+ }
53
64
  /**
54
65
  * binds to a BaileysEventEmitter.
55
66
  * It listens to all events and constructs a state that you can query accurate data from.
@@ -58,252 +69,237 @@ export const makeInMemoryStore = (config = {}) => {
58
69
  */
59
70
  const bind = (ev) => {
60
71
  ev.on('connection.update', update => {
61
- Object.assign(state, update);
62
- });
72
+ Object.assign(state, update)
73
+ })
63
74
  ev.on('messaging-history.set', ({ chats: newChats, contacts: newContacts, messages: newMessages, isLatest, syncType }) => {
64
- if (syncType === WAProto.HistorySync.HistorySyncType.ON_DEMAND) {
65
- return; // FOR NOW,
75
+ if (syncType === WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND) {
76
+ return // FOR NOW,
66
77
  //TODO: HANDLE
67
78
  }
68
79
  if (isLatest) {
69
- chats.clear();
80
+ chats.clear()
70
81
  for (const id in messages) {
71
- delete messages[id];
82
+ delete messages[id]
72
83
  }
73
84
  }
74
- const chatsAdded = chats.insertIfAbsent(...newChats).length;
75
- logger.debug({ chatsAdded }, 'synced chats');
76
- const oldContacts = contactsUpsert(newContacts);
85
+ const chatsAdded = chats.insertIfAbsent(...newChats).length
86
+ logger.debug({ chatsAdded }, 'synced chats')
87
+ const oldContacts = contactsUpsert(newContacts)
77
88
  if (isLatest) {
78
89
  for (const jid of oldContacts) {
79
- delete contacts[jid];
90
+ delete contacts[jid]
80
91
  }
81
92
  }
82
- logger.debug({ deletedContacts: isLatest ? oldContacts.size : 0, newContacts }, 'synced contacts');
93
+ logger.debug({ deletedContacts: isLatest ? oldContacts.size : 0, newContacts }, 'synced contacts')
83
94
  for (const msg of newMessages) {
84
- const jid = msg.key.remoteJidAlt || msg.key.remoteJid;
85
- const list = assertMessageList(jid);
86
- list.upsert(msg, 'prepend');
95
+ const jid = msg.key.remoteJid
96
+ const list = assertMessageList(jid)
97
+ list.upsert(msg, 'prepend')
87
98
  }
88
- logger.debug({ messages: newMessages.length }, 'synced messages');
89
- });
99
+ logger.debug({ messages: newMessages.length }, 'synced messages')
100
+ })
90
101
  ev.on('contacts.upsert', contacts => {
91
- contactsUpsert(contacts);
92
- });
102
+ contactsUpsert(contacts)
103
+ })
93
104
  ev.on('contacts.update', async (updates) => {
94
- var _a;
95
105
  for (const update of updates) {
96
- let contact;
106
+ let contact
97
107
  if (contacts[update.id]) {
98
- contact = contacts[update.id];
108
+ contact = contacts[update.id]
99
109
  }
100
110
  else {
101
111
  const contactHashes = await Promise.all(Object.keys(contacts).map(async (contactId) => {
102
- const { user } = jidDecode(contactId);
103
- return [contactId, (await md5(Buffer.from(user + 'WA_ADD_NOTIF', 'utf8'))).toString('base64').slice(0, 3)];
104
- }));
105
- contact = contacts[((_a = contactHashes.find(([, b]) => b === update.id)) === null || _a === void 0 ? void 0 : _a[0]) || '']; // find contact by attrs.hash, when user is not saved as a contact
112
+ const { user } = WABinary_1.jidDecode(contactId)
113
+ return [contactId, (await Utils_1.md5(Buffer.from(user + 'WA_ADD_NOTIF', 'utf8'))).toString('base64').slice(0, 3)]
114
+ }))
115
+ contact = contacts[contactHashes.find(([, b]) => b === update.id?.[0]) || ''] // find contact by attrs.hash, when user is not saved as a contact
106
116
  }
107
117
  if (contact) {
108
118
  if (update.imgUrl === 'changed') {
109
- contact.imgUrl = socket ? await (socket === null || socket === void 0 ? void 0 : socket.profilePictureUrl(contact.id)) : undefined;
119
+ contact.imgUrl = socket ? await socket.profilePictureUrl(contact.id) : undefined
110
120
  }
111
121
  else if (update.imgUrl === 'removed') {
112
- delete contact.imgUrl;
122
+ delete contact.imgUrl
113
123
  }
114
124
  }
115
125
  else {
116
- return logger.debug({ update }, 'got update for non-existant contact');
126
+ return logger.debug({ update }, 'got update for non-existant contact')
117
127
  }
118
- Object.assign(contacts[contact.id], contact);
128
+ Object.assign(contacts[contact.id], contact)
119
129
  }
120
- });
130
+ })
121
131
  ev.on('chats.upsert', newChats => {
122
- chats.upsert(...newChats);
123
- });
132
+ chats.upsert(...newChats)
133
+ })
124
134
  ev.on('chats.update', updates => {
125
135
  for (let update of updates) {
126
136
  const result = chats.update(update.id, chat => {
127
137
  if (update.unreadCount > 0) {
128
- update = { ...update };
129
- update.unreadCount = (chat.unreadCount || 0) + update.unreadCount;
138
+ update = { ...update }
139
+ update.unreadCount = (chat.unreadCount || 0) + update.unreadCount
130
140
  }
131
- Object.assign(chat, update);
132
- });
141
+ Object.assign(chat, update)
142
+ })
133
143
  if (!result) {
134
- logger.debug({ update }, 'got update for non-existant chat');
144
+ logger.debug({ update }, 'got update for non-existant chat')
135
145
  }
136
146
  }
137
- });
147
+ })
138
148
  ev.on('labels.edit', (label) => {
139
149
  if (label.deleted) {
140
- return labels.deleteById(label.id);
150
+ return labels.deleteById(label.id)
141
151
  }
142
152
  // WhatsApp can store only up to 20 labels
143
153
  if (labels.count() < 20) {
144
- return labels.upsertById(label.id, label);
154
+ return labels.upsertById(label.id, label)
145
155
  }
146
- logger.error('Labels count exceed');
147
- });
156
+ logger.error('Labels count exceed')
157
+ })
148
158
  ev.on('labels.association', ({ type, association }) => {
149
159
  switch (type) {
150
160
  case 'add':
151
- labelAssociations.upsert(association);
152
- break;
161
+ labelAssociations.upsert(association)
162
+ break
153
163
  case 'remove':
154
- labelAssociations.delete(association);
155
- break;
164
+ labelAssociations.delete(association)
165
+ break
156
166
  default:
157
- console.error(`unknown operation type [${type}]`);
167
+ console.error(`unknown operation type [${type}]`)
158
168
  }
159
- });
169
+ })
160
170
  ev.on('presence.update', ({ id, presences: update }) => {
161
- presences[id] = presences[id] || {};
162
- Object.assign(presences[id], update);
163
- });
171
+ presences[id] = presences[id] || {}
172
+ Object.assign(presences[id], update)
173
+ })
164
174
  ev.on('chats.delete', deletions => {
165
175
  for (const item of deletions) {
166
176
  if (chats.get(item)) {
167
- chats.deleteById(item);
177
+ chats.deleteById(item)
168
178
  }
169
179
  }
170
- });
180
+ })
171
181
  ev.on('messages.upsert', ({ messages: newMessages, type }) => {
172
182
  switch (type) {
173
183
  case 'append':
174
184
  case 'notify':
175
185
  for (const msg of newMessages) {
176
- const jid = jidNormalizedUser(msg.key.remoteJidAlt || msg.key.remoteJid);
177
- const list = assertMessageList(jid);
178
- list.upsert(msg, 'append');
186
+ const jid = WABinary_1.jidNormalizedUser(msg.key.remoteJid)
187
+ const list = assertMessageList(jid)
188
+ list.upsert(msg, 'append')
179
189
  if (type === 'notify' && !chats.get(jid)) {
180
190
  ev.emit('chats.upsert', [
181
191
  {
182
192
  id: jid,
183
- conversationTimestamp: toNumber(msg.messageTimestamp),
193
+ conversationTimestamp: Utils_1.toNumber(msg.messageTimestamp),
184
194
  unreadCount: 1
185
195
  }
186
- ]);
196
+ ])
187
197
  }
188
198
  }
189
- break;
199
+ break
190
200
  }
191
- });
201
+ })
192
202
  ev.on('messages.update', updates => {
193
- var _a;
194
203
  for (const { update, key } of updates) {
195
- const list = assertMessageList(jidNormalizedUser(key.remoteJid));
196
- if (update === null || update === void 0 ? void 0 : update.status) {
197
- const listStatus = (_a = list.get(key.id)) === null || _a === void 0 ? void 0 : _a.status;
198
- if (listStatus && (update === null || update === void 0 ? void 0 : update.status) <= listStatus) {
199
- logger.debug({ update, storedStatus: listStatus }, 'status stored newer then update');
200
- delete update.status;
201
- logger.debug({ update }, 'new update object');
204
+ const list = assertMessageList(WABinary_1.jidNormalizedUser(key.remoteJid))
205
+ if (update?.status) {
206
+ const listStatus = list.get(key.id)?.status
207
+ if (listStatus && update?.status <= listStatus) {
208
+ logger.debug({ update, storedStatus: listStatus }, 'status stored newer then update')
209
+ delete update.status
210
+ logger.debug({ update }, 'new update object')
202
211
  }
203
212
  }
204
- const result = list.updateAssign(key.id, update);
213
+ const result = list.updateAssign(key.id, update)
205
214
  if (!result) {
206
- logger.debug({ update }, 'got update for non-existent message');
215
+ logger.debug({ update }, 'got update for non-existent message')
207
216
  }
208
217
  }
209
- });
218
+ })
210
219
  ev.on('messages.delete', item => {
211
220
  if ('all' in item) {
212
- const list = messages[item.jid];
213
- list === null || list === void 0 ? void 0 : list.clear();
221
+ const list = messages[item.jid]
222
+ list?.clear()
214
223
  }
215
224
  else {
216
- const jid = item.keys[0].remoteJidAlt || item.keys[0].remoteJid;
217
- const list = messages[jid];
225
+ const jid = item.keys[0].remoteJid
226
+ const list = messages[jid]
218
227
  if (list) {
219
- const idSet = new Set(item.keys.map(k => k.id));
220
- list.filter(m => !idSet.has(m.key.id));
228
+ const idSet = new Set(item.keys.map(k => k.id))
229
+ list.filter(m => !idSet.has(m.key.id))
221
230
  }
222
231
  }
223
- });
232
+ })
224
233
  ev.on('groups.update', updates => {
225
234
  for (const update of updates) {
226
- const id = update.id;
235
+ const id = update.id
227
236
  if (groupMetadata[id]) {
228
- Object.assign(groupMetadata[id], update);
237
+ Object.assign(groupMetadata[id], update)
229
238
  }
230
239
  else {
231
- logger.debug({ update }, 'got update for non-existant group metadata');
240
+ logger.debug({ update }, 'got update for non-existant group metadata')
232
241
  }
233
242
  }
234
- });
243
+ })
235
244
  ev.on('group-participants.update', ({ id, participants, action }) => {
236
- const metadata = groupMetadata[id];
245
+ const metadata = groupMetadata[id]
237
246
  if (metadata) {
238
247
  switch (action) {
239
248
  case 'add':
240
- metadata.participants.push(...participants.map(participant => ({ id: participant.id, phoneNumber: participant.phoneNumber, admin: participant.admin })));
241
- break;
249
+ metadata.participants.push(...participants.map(id => ({ id, isAdmin: false, isSuperAdmin: false })))
250
+ break
242
251
  case 'demote':
243
252
  case 'promote':
244
253
  for (const participant of metadata.participants) {
245
- for (const participantData of participants) {
246
- if (participantData.id === participant.id || participantData.phoneNumber === participant.phoneNumber) {
247
- participant.admin = action === 'promote' && 'admin';
248
- }
254
+ if (participants.includes(participant.id)) {
255
+ participant.isAdmin = action === 'promote'
249
256
  }
250
257
  }
251
- break;
258
+ break
252
259
  case 'remove':
253
- const removeSet = new Set();
254
- for (const p of participants) {
255
- if (p.id)
256
- removeSet.add(p.id);
257
- if (p.phoneNumber)
258
- removeSet.add(p.phoneNumber);
259
- }
260
- metadata.participants = metadata.participants.reduce((acc, p) => {
261
- if (!removeSet.has(p.id) && !removeSet.has(p.phoneNumber))
262
- acc.push(p);
263
- return acc;
264
- }, []);
265
- break;
260
+ metadata.participants = metadata.participants.filter(p => !participants.includes(p.id))
261
+ break
266
262
  }
267
263
  }
268
- });
264
+ })
269
265
  ev.on('message-receipt.update', updates => {
270
266
  for (const { key, receipt } of updates) {
271
- const obj = messages[key.remoteJidAlt || key.remoteJid];
272
- const msg = obj === null || obj === void 0 ? void 0 : obj.get(key.id);
267
+ const obj = messages[key.remoteJid]
268
+ const msg = obj?.get(key.id)
273
269
  if (msg) {
274
- updateMessageWithReceipt(msg, receipt);
270
+ Utils_1.updateMessageWithReceipt(msg, receipt)
275
271
  }
276
272
  }
277
- });
273
+ })
278
274
  ev.on('messages.reaction', (reactions) => {
279
275
  for (const { key, reaction } of reactions) {
280
- const obj = messages[key.remoteJidAlt || key.remoteJid];
281
- const msg = obj === null || obj === void 0 ? void 0 : obj.get(key.id);
276
+ const obj = messages[key.remoteJid]
277
+ const msg = obj?.get(key.id)
282
278
  if (msg) {
283
- updateMessageWithReaction(msg, reaction);
279
+ Utils_1.updateMessageWithReaction(msg, reaction)
284
280
  }
285
281
  }
286
- });
287
- };
282
+ })
283
+ }
288
284
  const toJSON = () => ({
289
285
  chats,
290
286
  contacts,
291
287
  messages,
292
288
  labels,
293
289
  labelAssociations
294
- });
290
+ })
295
291
  const fromJSON = (json) => {
296
- chats.upsert(...json.chats);
297
- labelAssociations.upsert(...json.labelAssociations || []);
298
- contactsUpsert(Object.values(json.contacts));
299
- labelsUpsert(Object.values(json.labels || {}));
292
+ chats.upsert(...json.chats)
293
+ labelAssociations.upsert(...json.labelAssociations || [])
294
+ contactsUpsert(Object.values(json.contacts))
295
+ labelsUpsert(Object.values(json.labels || {}))
300
296
  for (const jid in json.messages) {
301
- const list = assertMessageList(jid);
297
+ const list = assertMessageList(jid)
302
298
  for (const msg of json.messages[jid]) {
303
- list.upsert(WAProto.WebMessageInfo.fromObject(msg), 'append');
299
+ list.upsert(WAProto_1.proto.WebMessageInfo.fromObject(msg), 'append')
304
300
  }
305
301
  }
306
- };
302
+ }
307
303
  return {
308
304
  chats,
309
305
  contacts,
@@ -316,28 +312,28 @@ export const makeInMemoryStore = (config = {}) => {
316
312
  bind,
317
313
  /** loads messages from the store, if not found -- uses the legacy connection */
318
314
  loadMessages: async (jid, count, cursor) => {
319
- const list = assertMessageList(jid);
320
- const mode = !cursor || 'before' in cursor ? 'before' : 'after';
321
- const cursorKey = !!cursor ? ('before' in cursor ? cursor.before : cursor.after) : undefined;
322
- const cursorValue = cursorKey ? list.get(cursorKey.id) : undefined;
323
- let messages;
315
+ const list = assertMessageList(jid)
316
+ const mode = !cursor || 'before' in cursor ? 'before' : 'after'
317
+ const cursorKey = !!cursor ? ('before' in cursor ? cursor.before : cursor.after) : undefined
318
+ const cursorValue = cursorKey ? list.get(cursorKey.id) : undefined
319
+ let messages
324
320
  if (list && mode === 'before' && (!cursorKey || cursorValue)) {
325
321
  if (cursorValue) {
326
- const msgIdx = list.array.findIndex(m => m.key.id === (cursorKey === null || cursorKey === void 0 ? void 0 : cursorKey.id));
327
- messages = list.array.slice(0, msgIdx);
322
+ const msgIdx = list.array.findIndex(m => m.key.id === cursorKey?.id)
323
+ messages = list.array.slice(0, msgIdx)
328
324
  }
329
325
  else {
330
- messages = list.array;
326
+ messages = list.array
331
327
  }
332
- const diff = count - messages.length;
328
+ const diff = count - messages.length
333
329
  if (diff < 0) {
334
- messages = messages.slice(-count); // get the last X messages
330
+ messages = messages.slice(-count) // get the last X messages
335
331
  }
336
332
  }
337
333
  else {
338
- messages = [];
334
+ messages = []
339
335
  }
340
- return messages;
336
+ return messages
341
337
  },
342
338
  /**
343
339
  * Get all available labels for profile
@@ -346,7 +342,7 @@ export const makeInMemoryStore = (config = {}) => {
346
342
  * that were "caught" during their editing.
347
343
  */
348
344
  getLabels: () => {
349
- return labels;
345
+ return labels
350
346
  },
351
347
  /**
352
348
  * Get labels for chat
@@ -354,7 +350,7 @@ export const makeInMemoryStore = (config = {}) => {
354
350
  * @returns Label IDs
355
351
  **/
356
352
  getChatLabels: (chatId) => {
357
- return labelAssociations.filter((la) => la.chatId === chatId).all();
353
+ return labelAssociations.filter((la) => la.chatId === chatId).all()
358
354
  },
359
355
  /**
360
356
  * Get labels for message
@@ -364,52 +360,70 @@ export const makeInMemoryStore = (config = {}) => {
364
360
  getMessageLabels: (messageId) => {
365
361
  const associations = labelAssociations
366
362
  .filter((la) => la.messageId === messageId)
367
- .all();
368
- return associations.map(({ labelId }) => labelId);
363
+ .all()
364
+ return associations.map(({ labelId }) => labelId)
369
365
  },
370
- loadMessage: async (jid, id) => { var _a; return (_a = messages[jid]) === null || _a === void 0 ? void 0 : _a.get(id); },
366
+ loadMessage: async (jid, id) => messages[jid]?.get(id),
371
367
  mostRecentMessage: async (jid) => {
372
- var _a;
373
- const message = (_a = messages[jid]) === null || _a === void 0 ? void 0 : _a.array.slice(-1)[0];
374
- return message;
368
+ const message = messages[jid]?.array.slice(-1)[0]
369
+ return message
375
370
  },
376
371
  fetchImageUrl: async (jid, sock) => {
377
- const contact = contacts[jid];
372
+ const contact = contacts[jid]
378
373
  if (!contact) {
379
- return sock === null || sock === void 0 ? void 0 : sock.profilePictureUrl(jid);
374
+ return sock?.profilePictureUrl(jid)
380
375
  }
381
376
  if (typeof contact.imgUrl === 'undefined') {
382
- contact.imgUrl = await (sock === null || sock === void 0 ? void 0 : sock.profilePictureUrl(jid));
377
+ contact.imgUrl = await sock?.profilePictureUrl(jid)
383
378
  }
384
- return contact.imgUrl;
379
+ return contact.imgUrl
385
380
  },
386
381
  fetchGroupMetadata: async (jid, sock) => {
387
382
  if (!groupMetadata[jid]) {
388
- const metadata = await (sock === null || sock === void 0 ? void 0 : sock.groupMetadata(jid));
383
+ const metadata = await sock?.groupMetadata(jid)
389
384
  if (metadata) {
390
- groupMetadata[jid] = metadata;
385
+ groupMetadata[jid] = metadata
391
386
  }
392
387
  }
393
- return groupMetadata[jid];
388
+ return groupMetadata[jid]
394
389
  },
390
+ // fetchBroadcastListInfo: async(jid: string, sock: WASocket | undefined) => {
391
+ // if(!groupMetadata[jid]) {
392
+ // const metadata = await sock?.getBroadcastListInfo(jid)
393
+ // if(metadata) {
394
+ // groupMetadata[jid] = metadata
395
+ // }
396
+ // }
397
+ // return groupMetadata[jid]
398
+ // },
395
399
  fetchMessageReceipts: async ({ remoteJid, id }) => {
396
- const list = messages[remoteJid];
397
- const msg = list === null || list === void 0 ? void 0 : list.get(id);
398
- return msg === null || msg === void 0 ? void 0 : msg.userReceipt;
400
+ const list = messages[remoteJid]
401
+ const msg = list?.get(id)
402
+ return msg?.userReceipt
399
403
  },
400
404
  toJSON,
401
405
  fromJSON,
402
406
  writeToFile: (path) => {
403
- writeFileSync(path, JSON.stringify(toJSON()));
407
+ // require fs here so that in case "fs" is not available -- the app does not crash
408
+ const { writeFileSync } = require('fs')
409
+ writeFileSync(path, JSON.stringify(toJSON()))
404
410
  },
405
411
  readFromFile: (path) => {
412
+ // require fs here so that in case "fs" is not available -- the app does not crash
413
+ const { readFileSync, existsSync } = require('fs')
406
414
  if (existsSync(path)) {
407
- logger.debug({ path }, 'reading from file');
408
- const jsonStr = readFileSync(path, { encoding: 'utf-8' });
409
- const json = JSON.parse(jsonStr);
410
- fromJSON(json);
415
+ logger.debug({ path }, 'reading from file')
416
+ const jsonStr = readFileSync(path, { encoding: 'utf-8' })
417
+ const json = JSON.parse(jsonStr)
418
+ fromJSON(json)
411
419
  }
412
420
  }
413
- };
414
- };
415
- //# sourceMappingURL=make-in-memory-store.js.map
421
+ }
422
+ }
423
+
424
+ module.exports = {
425
+ waChatKey,
426
+ waMessageID,
427
+ waLabelAssociationKey,
428
+ makeInMemoryStore
429
+ }
@@ -1,13 +1,12 @@
1
- export function makeOrderedDictionary(idGetter: any): {
2
- array: any[];
3
- get: (id: any) => any;
4
- upsert: (item: any, mode: any) => void;
5
- update: (item: any) => boolean;
6
- remove: (item: any) => boolean;
7
- updateAssign: (id: any, update: any) => boolean;
8
- clear: () => void;
9
- filter: (contain: any) => void;
10
- toJSON: () => any[];
11
- fromJSON: (newItems: any) => void;
12
- };
13
- //# sourceMappingURL=make-ordered-dictionary.d.ts.map
1
+ export declare function makeOrderedDictionary<T>(idGetter: (item: T) => string): {
2
+ array: T[]
3
+ get: (id: string) => T | undefined
4
+ upsert: (item: T, mode: 'append' | 'prepend') => void
5
+ update: (item: T) => boolean
6
+ remove: (item: T) => boolean
7
+ updateAssign: (id: string, update: Partial<T>) => boolean
8
+ clear: () => void
9
+ filter: (contain: (item: T) => boolean) => void
10
+ toJSON: () => T[]
11
+ fromJSON: (newItems: T[]) => void
12
+ }