@mrlegendbot/baileys 1.2.3 → 1.2.4

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 (212) hide show
  1. package/README.upstream.md +1312 -0
  2. package/WAProto/WAProto.json +1 -0
  3. package/WAProto/WAProto.proto +6275 -0
  4. package/WAProto/compiler.js +550 -0
  5. package/WAProto/index.js +2 -97691
  6. package/lib/Defaults/index.js +89 -92
  7. package/lib/Signal/Group/ciphertext-message.js +9 -10
  8. package/lib/Signal/Group/group-session-builder.js +21 -22
  9. package/lib/Signal/Group/group_cipher.js +75 -69
  10. package/lib/Signal/Group/index.js +0 -1
  11. package/lib/Signal/Group/keyhelper.js +9 -10
  12. package/lib/Signal/Group/sender-chain-key.js +21 -22
  13. package/lib/Signal/Group/sender-key-distribution-message.js +51 -60
  14. package/lib/Signal/Group/sender-key-message.js +56 -62
  15. package/lib/Signal/Group/sender-key-name.js +38 -40
  16. package/lib/Signal/Group/sender-key-record.js +33 -34
  17. package/lib/Signal/Group/sender-key-state.js +72 -76
  18. package/lib/Signal/Group/sender-message-key.js +22 -23
  19. package/lib/Signal/libsignal.js +506 -405
  20. package/lib/Signal/lid-mapping.js +276 -258
  21. package/lib/Socket/Client/index.js +0 -1
  22. package/lib/Socket/Client/types.js +6 -7
  23. package/lib/Socket/Client/websocket.js +48 -49
  24. package/lib/Socket/business.js +349 -369
  25. package/lib/Socket/chats.js +1172 -1148
  26. package/lib/Socket/communities.js +473 -413
  27. package/lib/Socket/groups.js +387 -331
  28. package/lib/Socket/index.js +6 -8
  29. package/lib/Socket/messages-recv.js +1782 -1719
  30. package/lib/Socket/messages-send.js +1503 -2450
  31. package/lib/Socket/mex.js +40 -35
  32. package/lib/Socket/newsletter.js +239 -191
  33. package/lib/Socket/socket.js +992 -923
  34. package/lib/Store/index.js +8 -0
  35. package/lib/Store/keyed-db.js +108 -0
  36. package/lib/Store/make-cache-manager-store.js +70 -0
  37. package/lib/Store/make-in-memory-store.js +417 -0
  38. package/lib/Store/make-ordered-dictionary.js +69 -0
  39. package/lib/Store/object-repository.js +27 -0
  40. package/lib/Types/Auth.js +0 -1
  41. package/lib/Types/Bussines.js +0 -1
  42. package/lib/Types/Call.js +0 -1
  43. package/lib/Types/Chat.js +1 -8
  44. package/lib/Types/Contact.js +0 -1
  45. package/lib/Types/Events.js +1 -2
  46. package/lib/Types/GroupMetadata.js +0 -1
  47. package/lib/Types/Label.js +20 -22
  48. package/lib/Types/LabelAssociation.js +2 -4
  49. package/lib/Types/Message.js +3 -5
  50. package/lib/Types/Mex.js +26 -31
  51. package/lib/Types/Product.js +0 -1
  52. package/lib/Types/Signal.js +1 -2
  53. package/lib/Types/Socket.js +2 -3
  54. package/lib/Types/State.js +4 -52
  55. package/lib/Types/USync.js +0 -1
  56. package/lib/Types/index.js +10 -11
  57. package/lib/Utils/auth-utils.js +240 -277
  58. package/lib/Utils/browser-utils.js +20 -23
  59. package/lib/Utils/business.js +200 -204
  60. package/lib/Utils/chat-utils.js +836 -810
  61. package/lib/Utils/companion-reg-client-utils.js +23 -25
  62. package/lib/Utils/crypto.js +70 -86
  63. package/lib/Utils/decode-wa-message.js +277 -284
  64. package/lib/Utils/event-buffer.js +592 -595
  65. package/lib/Utils/generics.js +312 -335
  66. package/lib/Utils/history.js +123 -115
  67. package/lib/Utils/index.js +1 -2
  68. package/lib/Utils/link-preview.js +74 -73
  69. package/lib/Utils/logger.js +3 -2
  70. package/lib/Utils/lt-hash.js +0 -6
  71. package/lib/Utils/make-mutex.js +27 -27
  72. package/lib/Utils/message-retry-manager.js +213 -254
  73. package/lib/Utils/messages-media.js +741 -715
  74. package/lib/Utils/messages.js +791 -827
  75. package/lib/Utils/noise-handler.js +215 -187
  76. package/lib/Utils/pre-key-manager.js +69 -98
  77. package/lib/Utils/process-message.js +617 -586
  78. package/lib/Utils/reporting-utils.js +553 -234
  79. package/lib/Utils/signal.js +217 -170
  80. package/lib/Utils/stanza-ack.js +27 -35
  81. package/lib/Utils/sync-action-utils.js +37 -41
  82. package/lib/Utils/tc-token-utils.js +120 -141
  83. package/lib/Utils/use-multi-file-auth-state.js +87 -105
  84. package/lib/Utils/use-sqlite-auth-state.js +162 -0
  85. package/lib/Utils/validate-connection.js +190 -188
  86. package/lib/WABinary/constants.js +28 -1294
  87. package/lib/WABinary/decode.js +245 -249
  88. package/lib/WABinary/encode.js +201 -206
  89. package/lib/WABinary/generic-utils.js +86 -89
  90. package/lib/WABinary/index.js +0 -1
  91. package/lib/WABinary/jid-utils.js +68 -77
  92. package/lib/WABinary/types.js +0 -1
  93. package/lib/WAM/BinaryInfo.js +7 -8
  94. package/lib/WAM/constants.js +19892 -22853
  95. package/lib/WAM/encode.js +121 -132
  96. package/lib/WAM/index.js +0 -1
  97. package/lib/WAUSync/Protocols/USyncContactProtocol.js +46 -43
  98. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +47 -48
  99. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +22 -23
  100. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +30 -33
  101. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +19 -20
  102. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -44
  103. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -24
  104. package/lib/WAUSync/Protocols/index.js +0 -1
  105. package/lib/WAUSync/USyncQuery.js +79 -88
  106. package/lib/WAUSync/USyncUser.js +28 -29
  107. package/lib/WAUSync/index.js +0 -1
  108. package/lib/index.js +2 -2
  109. package/package.json +22 -86
  110. package/WAProto/GenerateStatics.sh +0 -3
  111. package/WAProto/fix-imports.js +0 -85
  112. package/WAProto/index.d.ts +0 -14017
  113. package/lib/Defaults/index.d.ts +0 -75
  114. package/lib/Signal/Group/ciphertext-message.d.ts +0 -10
  115. package/lib/Signal/Group/group-session-builder.d.ts +0 -15
  116. package/lib/Signal/Group/group_cipher.d.ts +0 -17
  117. package/lib/Signal/Group/index.d.ts +0 -12
  118. package/lib/Signal/Group/keyhelper.d.ts +0 -11
  119. package/lib/Signal/Group/sender-chain-key.d.ts +0 -14
  120. package/lib/Signal/Group/sender-key-distribution-message.d.ts +0 -17
  121. package/lib/Signal/Group/sender-key-message.d.ts +0 -19
  122. package/lib/Signal/Group/sender-key-name.d.ts +0 -18
  123. package/lib/Signal/Group/sender-key-record.d.ts +0 -31
  124. package/lib/Signal/Group/sender-key-state.d.ts +0 -39
  125. package/lib/Signal/Group/sender-message-key.d.ts +0 -12
  126. package/lib/Signal/libsignal.d.ts +0 -5
  127. package/lib/Signal/lid-mapping.d.ts +0 -23
  128. package/lib/Socket/Client/index.d.ts +0 -3
  129. package/lib/Socket/Client/types.d.ts +0 -16
  130. package/lib/Socket/Client/websocket.d.ts +0 -13
  131. package/lib/Socket/business.d.ts +0 -217
  132. package/lib/Socket/chats.d.ts +0 -125
  133. package/lib/Socket/communities.d.ts +0 -273
  134. package/lib/Socket/groups.d.ts +0 -161
  135. package/lib/Socket/index.d.ts +0 -260
  136. package/lib/Socket/messages-recv.d.ts +0 -203
  137. package/lib/Socket/messages-send.d.ts +0 -199
  138. package/lib/Socket/mex.d.ts +0 -3
  139. package/lib/Socket/newsletter.d.ts +0 -170
  140. package/lib/Socket/socket.d.ts +0 -59
  141. package/lib/Types/Auth.d.ts +0 -117
  142. package/lib/Types/Bussines.d.ts +0 -25
  143. package/lib/Types/Call.d.ts +0 -15
  144. package/lib/Types/Chat.d.ts +0 -124
  145. package/lib/Types/Contact.d.ts +0 -26
  146. package/lib/Types/Events.d.ts +0 -256
  147. package/lib/Types/GroupMetadata.d.ts +0 -71
  148. package/lib/Types/Label.d.ts +0 -47
  149. package/lib/Types/LabelAssociation.d.ts +0 -30
  150. package/lib/Types/Message.d.ts +0 -320
  151. package/lib/Types/Mex.d.ts +0 -141
  152. package/lib/Types/Product.d.ts +0 -79
  153. package/lib/Types/Signal.d.ts +0 -87
  154. package/lib/Types/Socket.d.ts +0 -136
  155. package/lib/Types/State.d.ts +0 -97
  156. package/lib/Types/USync.d.ts +0 -26
  157. package/lib/Types/index.d.ts +0 -66
  158. package/lib/Utils/auth-utils.d.ts +0 -24
  159. package/lib/Utils/browser-utils.d.ts +0 -4
  160. package/lib/Utils/business.d.ts +0 -23
  161. package/lib/Utils/chat-utils.d.ts +0 -100
  162. package/lib/Utils/companion-reg-client-utils.d.ts +0 -17
  163. package/lib/Utils/crypto.d.ts +0 -37
  164. package/lib/Utils/decode-wa-message.d.ts +0 -66
  165. package/lib/Utils/event-buffer.d.ts +0 -36
  166. package/lib/Utils/generics.d.ts +0 -92
  167. package/lib/Utils/history.d.ts +0 -24
  168. package/lib/Utils/identity-change-handler.d.ts +0 -44
  169. package/lib/Utils/identity-change-handler.js +0 -50
  170. package/lib/Utils/index.d.ts +0 -22
  171. package/lib/Utils/link-preview.d.ts +0 -21
  172. package/lib/Utils/logger.d.ts +0 -12
  173. package/lib/Utils/lt-hash.d.ts +0 -8
  174. package/lib/Utils/make-mutex.d.ts +0 -9
  175. package/lib/Utils/message-retry-manager.d.ts +0 -115
  176. package/lib/Utils/messages-media.d.ts +0 -133
  177. package/lib/Utils/messages.d.ts +0 -91
  178. package/lib/Utils/noise-handler.d.ts +0 -20
  179. package/lib/Utils/offline-node-processor.d.ts +0 -17
  180. package/lib/Utils/offline-node-processor.js +0 -40
  181. package/lib/Utils/pre-key-manager.d.ts +0 -28
  182. package/lib/Utils/process-message.d.ts +0 -60
  183. package/lib/Utils/reporting-utils.d.ts +0 -11
  184. package/lib/Utils/signal.d.ts +0 -47
  185. package/lib/Utils/stanza-ack.d.ts +0 -11
  186. package/lib/Utils/sync-action-utils.d.ts +0 -19
  187. package/lib/Utils/tc-token-utils.d.ts +0 -37
  188. package/lib/Utils/use-multi-file-auth-state.d.ts +0 -13
  189. package/lib/Utils/validate-connection.d.ts +0 -11
  190. package/lib/WABinary/constants.d.ts +0 -28
  191. package/lib/WABinary/decode.d.ts +0 -7
  192. package/lib/WABinary/encode.d.ts +0 -3
  193. package/lib/WABinary/generic-utils.d.ts +0 -15
  194. package/lib/WABinary/index.d.ts +0 -6
  195. package/lib/WABinary/jid-utils.d.ts +0 -48
  196. package/lib/WABinary/types.d.ts +0 -19
  197. package/lib/WAM/BinaryInfo.d.ts +0 -9
  198. package/lib/WAM/constants.d.ts +0 -40
  199. package/lib/WAM/encode.d.ts +0 -3
  200. package/lib/WAM/index.d.ts +0 -4
  201. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +0 -10
  202. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +0 -23
  203. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +0 -13
  204. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +0 -13
  205. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +0 -10
  206. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +0 -26
  207. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +0 -10
  208. package/lib/WAUSync/Protocols/index.d.ts +0 -6
  209. package/lib/WAUSync/USyncQuery.d.ts +0 -30
  210. package/lib/WAUSync/USyncUser.d.ts +0 -17
  211. package/lib/WAUSync/index.d.ts +0 -4
  212. package/lib/index.d.ts +0 -12
@@ -0,0 +1,8 @@
1
+ export * from './make-cache-manager-store.js';
2
+ export * from './make-ordered-dictionary.js';
3
+ export * from './object-repository.js';
4
+ export * from './make-in-memory-store.js';
5
+ export { default as makeInMemoryStore } from './make-in-memory-store.js';
6
+ export { default as MakeCacheManagerStore } from './make-cache-manager-store.js';
7
+ export { default as MakeOrderedDictionary } from './make-ordered-dictionary.js';
8
+ export { default as ObjectRepository } from './object-repository.js';
@@ -0,0 +1,108 @@
1
+ export default class KeyedDB {
2
+ constructor(compareFn, idGetter) {
3
+ if (typeof compareFn !== "function" || typeof idGetter !== "function") {
4
+ throw new Error("KeyedDB requires compare and idGetter functions");
5
+ }
6
+ this._compare = compareFn;
7
+ this._idGetter = idGetter;
8
+ this._array = [];
9
+ this._dict = {};
10
+ }
11
+ get length() {
12
+ return this._array.length;
13
+ }
14
+ get(id) {
15
+ return this._dict[id];
16
+ }
17
+ insert(entry, mode = "insert") {
18
+ const id = this._idGetter(entry);
19
+ const existing = this._dict[id];
20
+ if (existing && mode === "insert") {
21
+ return false;
22
+ }
23
+ this._dict[id] = entry;
24
+ let inserted = false;
25
+ for (let i = 0; i < this._array.length; i++) {
26
+ const cmp = this._compare(entry, this._array[i]);
27
+ if (cmp < 0) {
28
+ this._array.splice(i, 0, entry);
29
+ inserted = true;
30
+ break;
31
+ }
32
+ }
33
+ if (!inserted) this._array.push(entry);
34
+ return true;
35
+ }
36
+ insertIfAbsent(...entries) {
37
+ const added = [];
38
+ for (const entry of entries) {
39
+ if (!this._dict[this._idGetter(entry)]) {
40
+ this.insert(entry);
41
+ added.push(entry);
42
+ }
43
+ }
44
+ return added;
45
+ }
46
+ upsert(...entries) {
47
+ const added = [];
48
+ for (const entry of entries) {
49
+ const id = this._idGetter(entry);
50
+ if (this._dict[id]) {
51
+ const idx = this._array.findIndex(e => this._idGetter(e) === id);
52
+ if (idx >= 0) this._array[idx] = entry;
53
+ this._dict[id] = entry;
54
+ } else {
55
+ this.insert(entry);
56
+ added.push(entry);
57
+ }
58
+ }
59
+ return added;
60
+ }
61
+ update(id, updater) {
62
+ const item = this._dict[id];
63
+ if (!item) return false;
64
+ updater(item);
65
+ const idx = this._array.findIndex(e => this._idGetter(e) === id);
66
+ if (idx >= 0) this._array[idx] = item;
67
+ return true;
68
+ }
69
+ updateAssign(id, update) {
70
+ const item = this._dict[id];
71
+ if (!item) return false;
72
+ Object.assign(item, update);
73
+ const idx = this._array.findIndex(e => this._idGetter(e) === id);
74
+ if (idx >= 0) this._array[idx] = item;
75
+ return true;
76
+ }
77
+ deleteById(id) {
78
+ if (!this._dict[id]) return false;
79
+ delete this._dict[id];
80
+ const idx = this._array.findIndex(e => this._idGetter(e) === id);
81
+ if (idx >= 0) this._array.splice(idx, 1);
82
+ return true;
83
+ }
84
+ clear() {
85
+ this._array = [];
86
+ this._dict = {};
87
+ }
88
+ all() {
89
+ return [...this._array];
90
+ }
91
+ filter(predicate) {
92
+ this._array = this._array.filter(predicate);
93
+ this._dict = {};
94
+ for (const entry of this._array) {
95
+ this._dict[this._idGetter(entry)] = entry;
96
+ }
97
+ }
98
+ count() {
99
+ return this._array.length;
100
+ }
101
+ toJSON() {
102
+ return this._array;
103
+ }
104
+ fromJSON(array) {
105
+ this.clear();
106
+ for (const entry of array) this.insert(entry);
107
+ }
108
+ }
@@ -0,0 +1,70 @@
1
+ import { createRequire } from "module";
2
+ const require = createRequire(import.meta.url);
3
+ const cacheManager = require("cache-manager");
4
+ import * as WAProto_1 from "../../WAProto/compiler.js";
5
+ import * as Utils_1 from "../Utils/index.js";
6
+ import logger from "../Utils/logger.js";
7
+ export default async function makeCacheManagerAuthState(store, sessionKey) {
8
+ const defaultKey = file => `${sessionKey}:${file}`;
9
+ const databaseConn = await cacheManager.caching(store);
10
+ const writeData = async (file, data) => {
11
+ let ttl = undefined;
12
+ if (file === "creds") ttl = 63115200;
13
+ await databaseConn.set(defaultKey(file), JSON.stringify(data, Utils_1.BufferJSON.replacer), ttl);
14
+ };
15
+ const readData = async file => {
16
+ try {
17
+ const data = await databaseConn.get(defaultKey(file));
18
+ if (data) return JSON.parse(data, Utils_1.BufferJSON.reviver);
19
+ return null;
20
+ } catch (error) {
21
+ logger.error(error);
22
+ return null;
23
+ }
24
+ };
25
+ const removeData = async file => {
26
+ try {
27
+ return await databaseConn.del(defaultKey(file));
28
+ } catch {
29
+ logger.error(`Error removing ${file} from session ${sessionKey}`);
30
+ }
31
+ };
32
+ const clearState = async () => {
33
+ try {
34
+ const result = await databaseConn.store.keys(`${sessionKey}*`);
35
+ await Promise.all(result.map(async key => databaseConn.del(key)));
36
+ } catch {}
37
+ };
38
+ const creds = (await readData("creds")) || Utils_1.initAuthCreds();
39
+ return {
40
+ clearState,
41
+ saveCreds: () => writeData("creds", creds),
42
+ state: {
43
+ creds,
44
+ keys: {
45
+ get: async (type, ids) => {
46
+ const data = {};
47
+ await Promise.all(ids.map(async id => {
48
+ let value = await readData(`${type}-${id}`);
49
+ if (type === "app-state-sync-key" && value) {
50
+ value = WAProto_1.proto.Message.AppStateSyncKeyData.fromObject(value);
51
+ }
52
+ data[id] = value;
53
+ }));
54
+ return data;
55
+ },
56
+ set: async data => {
57
+ const tasks = [];
58
+ for (const category in data) {
59
+ for (const id in data[category]) {
60
+ const value = data[category][id];
61
+ const key = `${category}-${id}`;
62
+ tasks.push(value ? writeData(key, value) : removeData(key));
63
+ }
64
+ }
65
+ await Promise.all(tasks);
66
+ }
67
+ }
68
+ }
69
+ };
70
+ }
@@ -0,0 +1,417 @@
1
+ import { existsSync, readFileSync, writeFileSync } from 'fs';
2
+ import { DEFAULT_CONNECTION_CONFIG } from '../Defaults/index.js';
3
+ import { toNumber, updateMessageWithPollUpdate, updateMessageWithReaction, updateMessageWithReceipt } from '../Utils/index.js';
4
+ import { jidNormalizedUser } from '../WABinary/index.js';
5
+ import KeyedDB from './keyed-db.js';
6
+ import makeOrderedDictionary from './make-ordered-dictionary.js';
7
+ import { ObjectRepository } from './object-repository.js';
8
+ const waChatKey = pin => (c1, c2) => {
9
+ const pinnedDiff = pin ? Number(!!c2.pinned) - Number(!!c1.pinned) : 0;
10
+ if (pinnedDiff) return pinnedDiff;
11
+ const t1 = toNumber(c1.conversationTimestamp) || 0;
12
+ const t2 = toNumber(c2.conversationTimestamp) || 0;
13
+ if (t1 !== t2) return t2 - t1;
14
+ return (c1.id || '').localeCompare(c2.id || '');
15
+ };
16
+ const waMessageID = m => m.key?.id || '';
17
+ const waLabelAssociationKey = (a1, a2) => (a1.type || '').localeCompare(a2.type || '') || (a1.chatId || '').localeCompare(a2.chatId || '') || (a1.labelId || '').localeCompare(a2.labelId || '');
18
+ const labelAssociationId = a => (a.type || '') + ':' + (a.chatId || a.messageId || '') + ':' + (a.labelId || '');
19
+ const makeMessagesDictionary = () => makeOrderedDictionary(waMessageID);
20
+ export const makeInMemoryStore = (config = {}) => {
21
+ const socket = config.socket;
22
+ const chatKeyCompare = config.chatKey || waChatKey(true);
23
+ const labelAssociationKeyCompare = config.labelAssociationKey || waLabelAssociationKey;
24
+ const logger = config.logger || DEFAULT_CONNECTION_CONFIG.logger?.child?.({
25
+ stream: 'in-mem-store'
26
+ });
27
+ const chats = new KeyedDB(chatKeyCompare, c => c.id);
28
+ const messages = {};
29
+ const contacts = {};
30
+ const groupMetadata = {};
31
+ const presences = {};
32
+ const state = {
33
+ connection: 'close'
34
+ };
35
+ const labels = new ObjectRepository();
36
+ const labelAssociations = new KeyedDB(labelAssociationKeyCompare, labelAssociationId);
37
+ const assertMessageList = jid => {
38
+ if (!messages[jid]) {
39
+ messages[jid] = makeMessagesDictionary();
40
+ }
41
+ return messages[jid];
42
+ };
43
+ const contactsUpsert = newContacts => {
44
+ const oldContacts = new Set(Object.keys(contacts));
45
+ for (const contact of newContacts) {
46
+ oldContacts.delete(contact.id);
47
+ contacts[contact.id] = Object.assign(contacts[contact.id] || {}, contact);
48
+ }
49
+ return oldContacts;
50
+ };
51
+ const labelsUpsert = newLabels => {
52
+ for (const label of newLabels) {
53
+ labels.upsertById(label.id, label);
54
+ }
55
+ };
56
+ const bind = ev => {
57
+ ev.on('connection.update', update => {
58
+ Object.assign(state, update);
59
+ });
60
+ ev.on('messaging-history.set', ({
61
+ chats: newChats,
62
+ contacts: newContacts,
63
+ messages: newMessages,
64
+ isLatest,
65
+ syncType
66
+ }) => {
67
+ if (isLatest) {
68
+ chats.clear();
69
+ for (const id of Object.keys(messages)) {
70
+ delete messages[id];
71
+ }
72
+ }
73
+ const chatsAdded = chats.insertIfAbsent(...newChats).length;
74
+ logger?.debug?.({
75
+ chatsAdded
76
+ }, 'synced chats');
77
+ const oldContacts = contactsUpsert(newContacts);
78
+ logger?.debug?.({
79
+ deletedContacts: oldContacts.size,
80
+ newContacts
81
+ }, 'synced contacts');
82
+ for (const msg of newMessages) {
83
+ const jid = jidNormalizedUser(msg.key.remoteJid);
84
+ const list = assertMessageList(jid);
85
+ list.upsert(msg, 'prepend');
86
+ }
87
+ logger?.debug?.({
88
+ messages: newMessages.length
89
+ }, 'synced messages');
90
+ });
91
+ ev.on('contacts.upsert', newContacts => {
92
+ contactsUpsert(newContacts);
93
+ });
94
+ ev.on('contacts.update', updates => {
95
+ for (const update of updates) {
96
+ let contact;
97
+ if (update.id && (contact = contacts[update.id])) {
98
+ Object.assign(contact, update);
99
+ } else {
100
+ logger?.debug?.({
101
+ update
102
+ }, 'got update for non-existant contact');
103
+ }
104
+ }
105
+ });
106
+ ev.on('chats.upsert', newChats => {
107
+ chats.upsert(...newChats);
108
+ });
109
+ ev.on('chats.update', updates => {
110
+ for (let update of updates) {
111
+ const existing = chats.get(update.id);
112
+ if (existing) {
113
+ chats.upsert(Object.assign(existing, update));
114
+ } else {
115
+ logger?.debug?.({
116
+ update
117
+ }, 'got update for non-existant chat');
118
+ }
119
+ }
120
+ });
121
+ ev.on('labels.edit', label => {
122
+ if (label.deleted) {
123
+ labels.deleteById(label.id);
124
+ return;
125
+ }
126
+ labels.upsertById(label.id, label);
127
+ });
128
+ ev.on('labels.association', ({
129
+ type,
130
+ association
131
+ }) => {
132
+ switch (type) {
133
+ case 'add':
134
+ labelAssociations.upsert(association);
135
+ break;
136
+ case 'remove':
137
+ labelAssociations.deleteById(labelAssociationId(association));
138
+ break;
139
+ default:
140
+ logger?.error?.(`unknown operation type ${type}`);
141
+ }
142
+ });
143
+ ev.on('presence.update', ({
144
+ id,
145
+ presences: update
146
+ }) => {
147
+ presences[id] = presences[id] || {};
148
+ Object.assign(presences[id], update);
149
+ });
150
+ ev.on('chats.delete', deletions => {
151
+ for (const item of deletions) {
152
+ if (chats.get(item)) {
153
+ chats.deleteById(item);
154
+ }
155
+ }
156
+ });
157
+ ev.on('messages.upsert', ({
158
+ messages: newMessages,
159
+ type
160
+ }) => {
161
+ switch (type) {
162
+ case 'append':
163
+ case 'notify':
164
+ for (const msg of newMessages) {
165
+ const jid = jidNormalizedUser(msg.key.remoteJid);
166
+ const list = assertMessageList(jid);
167
+ list.upsert(msg, 'append');
168
+ if (type === 'notify') {
169
+ if (!chats.get(jid)) {
170
+ ev.emit('chats.upsert', [{
171
+ id: jid,
172
+ conversationTimestamp: toNumber(msg.messageTimestamp),
173
+ unreadCount: 1
174
+ }]);
175
+ }
176
+ }
177
+ }
178
+ break;
179
+ }
180
+ });
181
+ ev.on('messages.update', updates => {
182
+ for (const {
183
+ update,
184
+ key
185
+ } of updates) {
186
+ const list = assertMessageList(jidNormalizedUser(key.remoteJid));
187
+ if (update?.status) {
188
+ const listStatus = list.get(key.id)?.status;
189
+ if (listStatus && update.status <= listStatus) {
190
+ logger?.debug?.({
191
+ update,
192
+ storedStatus: listStatus
193
+ }, 'status stored newer then update');
194
+ delete update.status;
195
+ }
196
+ }
197
+ const result = list.updateAssign(key.id, update);
198
+ if (!result) {
199
+ logger?.debug?.({
200
+ update
201
+ }, 'got update for non-existent message');
202
+ }
203
+ }
204
+ });
205
+ ev.on('messages.delete', item => {
206
+ if ('all' in item) {
207
+ const list = messages[item.jid];
208
+ list?.clear();
209
+ } else {
210
+ const jid = item.keys[0].remoteJid;
211
+ const list = messages[jidNormalizedUser(jid)];
212
+ if (list) {
213
+ const idSet = new Set(item.keys.map(k => k.id));
214
+ list.filter(m => !idSet.has(m.key.id));
215
+ }
216
+ }
217
+ });
218
+ ev.on('messages.reaction', reactions => {
219
+ for (const {
220
+ key,
221
+ reaction
222
+ } of reactions) {
223
+ const obj = messages[jidNormalizedUser(key.remoteJid)];
224
+ const msg = obj?.get(key.id);
225
+ if (msg) {
226
+ updateMessageWithReaction(msg, reaction);
227
+ }
228
+ }
229
+ });
230
+ ev.on('message-receipt.update', updates => {
231
+ for (const {
232
+ key,
233
+ receipt
234
+ } of updates) {
235
+ const obj = messages[jidNormalizedUser(key.remoteJid)];
236
+ const msg = obj?.get(key.id);
237
+ if (msg) {
238
+ updateMessageWithReceipt(msg, receipt);
239
+ }
240
+ }
241
+ });
242
+ ev.on('groups.update', updates => {
243
+ for (const update of updates) {
244
+ const id = update.id;
245
+ if (groupMetadata[id]) {
246
+ Object.assign(groupMetadata[id], update);
247
+ } else {
248
+ logger?.debug?.({
249
+ update
250
+ }, 'got update for non-existant group metadata');
251
+ }
252
+ }
253
+ });
254
+ ev.on('group-participants.update', ({
255
+ id,
256
+ participants,
257
+ action
258
+ }) => {
259
+ const metadata = groupMetadata[id];
260
+ if (metadata) {
261
+ switch (action) {
262
+ case 'add':
263
+ metadata.participants.push(...participants.map(p => ({
264
+ id: p,
265
+ isAdmin: false,
266
+ isSuperAdmin: false
267
+ })));
268
+ break;
269
+ case 'demote':
270
+ case 'promote':
271
+ for (const participant of metadata.participants) {
272
+ if (participants.includes(participant.id)) {
273
+ participant.isAdmin = action === 'promote';
274
+ }
275
+ }
276
+ break;
277
+ case 'remove':
278
+ metadata.participants = metadata.participants.filter(p => !participants.includes(p.id));
279
+ break;
280
+ }
281
+ }
282
+ });
283
+ ev.on('groups.upsert', newGroups => {
284
+ for (const group of newGroups) {
285
+ groupMetadata[group.id] = group;
286
+ }
287
+ });
288
+ };
289
+ const toJSON = () => ({
290
+ chats,
291
+ contacts,
292
+ messages,
293
+ labels,
294
+ labelAssociations
295
+ });
296
+ const fromJSON = json => {
297
+ chats.upsert(...json.chats);
298
+ labelAssociations.upsert(...(json.labelAssociations || []));
299
+ contactsUpsert(Object.values(json.contacts));
300
+ labelsUpsert(Object.values(json.labels || {}));
301
+ for (const jid in json.messages) {
302
+ const list = assertMessageList(jid);
303
+ for (const msg of json.messages[jid]) {
304
+ list.upsert(msg, 'append');
305
+ }
306
+ }
307
+ };
308
+ const writeToFile = path => {
309
+ const data = JSON.stringify(toJSON(), BufferJSON_replacer);
310
+ writeFileSync(path, data);
311
+ };
312
+ const readFromFile = path => {
313
+ if (existsSync(path)) {
314
+ logger?.debug?.({
315
+ path
316
+ }, 'reading from file');
317
+ const jsonStr = readFileSync(path, {
318
+ encoding: 'utf-8'
319
+ });
320
+ const json = JSON.parse(jsonStr, BufferJSON_reviver);
321
+ fromJSON(json);
322
+ }
323
+ };
324
+ return {
325
+ chats,
326
+ contacts,
327
+ messages,
328
+ groupMetadata,
329
+ state,
330
+ presences,
331
+ labels,
332
+ labelAssociations,
333
+ bind,
334
+ loadMessages: async (jid, count, cursor) => {
335
+ const list = assertMessageList(jidNormalizedUser(jid));
336
+ const mode = !cursor || 'before' in cursor ? 'before' : 'after';
337
+ const cursorKey = cursor ? 'before' in cursor ? cursor.before : cursor.after : undefined;
338
+ const cursorValue = cursorKey ? list.get(cursorKey.id) : undefined;
339
+ let messagesList;
340
+ if (list && mode === 'before' && (!cursorKey || cursorValue)) {
341
+ if (cursorValue) {
342
+ const msgIdx = list.array.findIndex(m => m.key.id === cursorKey?.id);
343
+ messagesList = list.array.slice(0, msgIdx);
344
+ } else {
345
+ messagesList = list.array;
346
+ }
347
+ return messagesList.slice(-count);
348
+ }
349
+ return [];
350
+ },
351
+ loadMessage: async (jid, id) => messages[jidNormalizedUser(jid)]?.get(id),
352
+ getMessage: (jid, id) => messages[jidNormalizedUser(jid)]?.get(id),
353
+ mostRecentMessage: async jid => {
354
+ const message = messages[jidNormalizedUser(jid)]?.array.slice(-1)[0];
355
+ return message;
356
+ },
357
+ fetchImageUrl: async (jid, sock) => {
358
+ const s = sock || socket;
359
+ const contact = contacts[jid];
360
+ if (!contact) {
361
+ return s?.profilePictureUrl(jid);
362
+ }
363
+ if (typeof contact.imgUrl === 'undefined') {
364
+ contact.imgUrl = await s?.profilePictureUrl(jid);
365
+ }
366
+ return contact.imgUrl;
367
+ },
368
+ fetchGroupMetadata: async (jid, sock) => {
369
+ const s = sock || socket;
370
+ if (!groupMetadata[jid]) {
371
+ const metadata = await s?.groupMetadata(jid);
372
+ if (metadata) {
373
+ groupMetadata[jid] = metadata;
374
+ }
375
+ }
376
+ return groupMetadata[jid];
377
+ },
378
+ fetchMessageReceipts: async ({
379
+ remoteJid,
380
+ id
381
+ }, sock) => {
382
+ const s = sock || socket;
383
+ const list = messages[jidNormalizedUser(remoteJid)];
384
+ const msg = list?.get(id);
385
+ return msg?.userReceipt;
386
+ },
387
+ toJSON,
388
+ fromJSON,
389
+ writeToFile,
390
+ readFromFile
391
+ };
392
+ };
393
+ function BufferJSON_replacer(_key, value) {
394
+ if (value?.type === 'Buffer' && Array.isArray(value?.data)) {
395
+ return value;
396
+ }
397
+ if (value instanceof Uint8Array || typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) {
398
+ return {
399
+ type: 'Buffer',
400
+ data: Buffer.from(value).toString('base64'),
401
+ __enc: 'base64'
402
+ };
403
+ }
404
+ return value;
405
+ }
406
+ function BufferJSON_reviver(_key, value) {
407
+ if (value?.type === 'Buffer') {
408
+ if (value.__enc === 'base64' && typeof value.data === 'string') {
409
+ return Buffer.from(value.data, 'base64');
410
+ }
411
+ if (Array.isArray(value.data)) {
412
+ return Buffer.from(value.data);
413
+ }
414
+ }
415
+ return value;
416
+ }
417
+ export default makeInMemoryStore;
@@ -0,0 +1,69 @@
1
+ export default function makeOrderedDictionary(idGetter) {
2
+ const array = [];
3
+ const dict = {};
4
+ const get = id => dict[id];
5
+ const update = item => {
6
+ const id = idGetter(item);
7
+ const idx = array.findIndex(i => idGetter(i) === id);
8
+ if (idx >= 0) {
9
+ array[idx] = item;
10
+ dict[id] = item;
11
+ }
12
+ return false;
13
+ };
14
+ const upsert = (item, mode) => {
15
+ const id = idGetter(item);
16
+ if (get(id)) {
17
+ update(item);
18
+ } else {
19
+ if (mode === 'append') array.push(item);else array.unshift(item);
20
+ dict[id] = item;
21
+ }
22
+ };
23
+ const remove = item => {
24
+ const id = idGetter(item);
25
+ const idx = array.findIndex(i => idGetter(i) === id);
26
+ if (idx >= 0) {
27
+ array.splice(idx, 1);
28
+ delete dict[id];
29
+ return true;
30
+ }
31
+ return false;
32
+ };
33
+ return {
34
+ array,
35
+ get,
36
+ upsert,
37
+ update,
38
+ remove,
39
+ updateAssign: (id, update) => {
40
+ const item = get(id);
41
+ if (item) {
42
+ Object.assign(item, update);
43
+ delete dict[id];
44
+ dict[idGetter(item)] = item;
45
+ return true;
46
+ }
47
+ return false;
48
+ },
49
+ clear: () => {
50
+ array.length = 0;
51
+ for (const key of Object.keys(dict)) delete dict[key];
52
+ },
53
+ filter: contain => {
54
+ let i = 0;
55
+ while (i < array.length) {
56
+ if (!contain(array[i])) {
57
+ delete dict[idGetter(array[i])];
58
+ array.splice(i, 1);
59
+ } else {
60
+ i++;
61
+ }
62
+ }
63
+ },
64
+ toJSON: () => array,
65
+ fromJSON: newItems => {
66
+ array.splice(0, array.length, ...newItems);
67
+ }
68
+ };
69
+ }
@@ -0,0 +1,27 @@
1
+ export class ObjectRepository {
2
+ constructor(entities = {}) {
3
+ this.entityMap = new Map(Object.entries(entities));
4
+ }
5
+ findById(id) {
6
+ return this.entityMap.get(id);
7
+ }
8
+ findAll() {
9
+ return Array.from(this.entityMap.values());
10
+ }
11
+ upsertById(id, entity) {
12
+ this.entityMap.set(id, {
13
+ ...entity
14
+ });
15
+ return this;
16
+ }
17
+ deleteById(id) {
18
+ return this.entityMap.delete(id);
19
+ }
20
+ count() {
21
+ return this.entityMap.size;
22
+ }
23
+ toJSON() {
24
+ return this.findAll();
25
+ }
26
+ }
27
+ export default ObjectRepository;
package/lib/Types/Auth.js CHANGED
@@ -1,2 +1 @@
1
1
  export {};
2
- //# sourceMappingURL=Auth.js.map
@@ -1,2 +1 @@
1
1
  export {};
2
- //# sourceMappingURL=Bussines.js.map