@queenanya/baileys 7.4.14 → 7.5.3-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/README.md +26 -26
  2. package/lib/Defaults/baileys-version.json +1 -1
  3. package/lib/Defaults/index.d.ts +1 -231
  4. package/lib/Defaults/index.js +11 -23
  5. package/lib/Socket/Client/index.d.ts +2 -3
  6. package/lib/Socket/Client/index.js +2 -3
  7. package/lib/Socket/Client/{web-socket-client.d.ts → websocket.d.ts} +1 -1
  8. package/lib/Socket/Client/{web-socket-client.js → websocket.js} +2 -2
  9. package/lib/Socket/business.d.ts +31 -28
  10. package/lib/Socket/chats.d.ts +17 -9
  11. package/lib/Socket/chats.js +115 -116
  12. package/lib/Socket/{registration.d.ts → communities.d.ts} +94 -145
  13. package/lib/Socket/communities.js +354 -0
  14. package/lib/Socket/groups.d.ts +23 -10
  15. package/lib/Socket/groups.js +12 -1
  16. package/lib/Socket/index.d.ts +69 -38
  17. package/lib/Socket/index.js +2 -2
  18. package/lib/Socket/messages-recv.d.ts +30 -28
  19. package/lib/Socket/messages-recv.js +291 -180
  20. package/lib/Socket/messages-send.d.ts +25 -19
  21. package/lib/Socket/messages-send.js +110 -76
  22. package/lib/Socket/newsletter.d.ts +19 -13
  23. package/lib/Socket/newsletter.js +67 -54
  24. package/lib/Socket/socket.d.ts +3 -1
  25. package/lib/Socket/socket.js +15 -17
  26. package/lib/Socket/usync.d.ts +38 -0
  27. package/lib/Socket/usync.js +70 -0
  28. package/lib/Store/make-cache-manager-store.d.ts +2 -1
  29. package/lib/Store/make-in-memory-store.js +13 -11
  30. package/lib/Store/make-ordered-dictionary.js +2 -2
  31. package/lib/Types/Auth.d.ts +1 -6
  32. package/lib/Types/Call.d.ts +1 -1
  33. package/lib/Types/Chat.d.ts +15 -7
  34. package/lib/Types/Contact.d.ts +6 -1
  35. package/lib/Types/Events.d.ts +44 -2
  36. package/lib/Types/GroupMetadata.d.ts +3 -1
  37. package/lib/Types/Label.d.ts +11 -0
  38. package/lib/Types/Message.d.ts +37 -30
  39. package/lib/Types/Newsletter.d.ts +0 -13
  40. package/lib/Types/Newsletter.js +1 -15
  41. package/lib/Types/Socket.d.ts +10 -3
  42. package/lib/Types/USync.d.ts +25 -0
  43. package/lib/Types/USync.js +2 -0
  44. package/lib/Types/index.d.ts +8 -0
  45. package/lib/Utils/auth-utils.js +1 -7
  46. package/lib/Utils/chat-utils.d.ts +5 -4
  47. package/lib/Utils/chat-utils.js +52 -20
  48. package/lib/Utils/crypto.d.ts +2 -1
  49. package/lib/Utils/crypto.js +4 -2
  50. package/lib/Utils/decode-wa-message.d.ts +1 -0
  51. package/lib/Utils/decode-wa-message.js +34 -14
  52. package/lib/Utils/event-buffer.js +14 -8
  53. package/lib/Utils/generics.d.ts +37 -13
  54. package/lib/Utils/generics.js +103 -18
  55. package/lib/Utils/history.d.ts +6 -2
  56. package/lib/Utils/history.js +3 -0
  57. package/lib/Utils/index.d.ts +1 -0
  58. package/lib/Utils/index.js +1 -0
  59. package/lib/Utils/link-preview.js +24 -1
  60. package/lib/Utils/logger.d.ts +1 -3
  61. package/lib/Utils/make-mutex.js +1 -0
  62. package/lib/Utils/messages-media.d.ts +3 -2
  63. package/lib/Utils/messages-media.js +17 -32
  64. package/lib/Utils/messages.d.ts +1 -0
  65. package/lib/Utils/messages.js +67 -72
  66. package/lib/Utils/noise-handler.d.ts +3 -3
  67. package/lib/Utils/noise-handler.js +7 -12
  68. package/lib/Utils/process-message.d.ts +3 -2
  69. package/lib/Utils/process-message.js +55 -21
  70. package/lib/Utils/signal.js +23 -16
  71. package/lib/Utils/use-multi-file-auth-state.js +17 -3
  72. package/lib/Utils/validate-connection.d.ts +0 -1
  73. package/lib/Utils/validate-connection.js +10 -44
  74. package/lib/WABinary/constants.js +5 -5
  75. package/lib/WABinary/decode.d.ts +3 -2
  76. package/lib/WABinary/decode.js +6 -4
  77. package/lib/WABinary/encode.d.ts +1 -2
  78. package/lib/WABinary/encode.js +8 -6
  79. package/lib/WABinary/generic-utils.d.ts +1 -0
  80. package/lib/WABinary/jid-utils.d.ts +3 -3
  81. package/lib/WABinary/jid-utils.js +5 -5
  82. package/lib/WAM/BinaryInfo.d.ts +3 -2
  83. package/lib/WAM/constants.d.ts +3 -2
  84. package/lib/WAM/encode.d.ts +1 -0
  85. package/lib/WAM/encode.js +2 -2
  86. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  87. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  88. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  89. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  90. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  91. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  92. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  93. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  94. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  95. package/lib/WAUSync/Protocols/index.js +20 -0
  96. package/lib/WAUSync/USyncQuery.d.ts +26 -0
  97. package/lib/WAUSync/USyncQuery.js +79 -0
  98. package/lib/WAUSync/USyncUser.d.ts +10 -0
  99. package/lib/WAUSync/USyncUser.js +22 -0
  100. package/lib/WAUSync/index.d.ts +3 -0
  101. package/lib/WAUSync/index.js +19 -0
  102. package/lib/index.d.ts +1 -0
  103. package/lib/index.js +1 -0
  104. package/package.json +36 -34
  105. package/lib/Defaults/phonenumber-mcc.json +0 -223
  106. package/lib/Socket/Client/mobile-socket-client.d.ts +0 -13
  107. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  108. package/lib/Socket/registration.js +0 -166
  109. /package/lib/Socket/Client/{abstract-socket-client.d.ts → types.d.ts} +0 -0
  110. /package/lib/Socket/Client/{abstract-socket-client.js → types.js} +0 -0
@@ -5,6 +5,20 @@ const Types_1 = require("../Types");
5
5
  const Utils_1 = require("../Utils");
6
6
  const WABinary_1 = require("../WABinary");
7
7
  const groups_1 = require("./groups");
8
+ var QueryIds;
9
+ (function (QueryIds) {
10
+ QueryIds["JOB_MUTATION"] = "7150902998257522";
11
+ QueryIds["METADATA"] = "6620195908089573";
12
+ QueryIds["UNFOLLOW"] = "7238632346214362";
13
+ QueryIds["FOLLOW"] = "7871414976211147";
14
+ QueryIds["UNMUTE"] = "7337137176362961";
15
+ QueryIds["MUTE"] = "25151904754424642";
16
+ QueryIds["CREATE"] = "6996806640408138";
17
+ QueryIds["ADMIN_COUNT"] = "7130823597031706";
18
+ QueryIds["CHANGE_OWNER"] = "7341777602580933";
19
+ QueryIds["DELETE"] = "8316537688363079";
20
+ QueryIds["DEMOTE"] = "6551828931592903";
21
+ })(QueryIds || (QueryIds = {}));
8
22
  const makeNewsletterSocket = (config) => {
9
23
  const sock = (0, groups_1.makeGroupsSocket)(config);
10
24
  const { authState, signalRepository, query, generateMessageTag } = sock;
@@ -19,7 +33,7 @@ const makeNewsletterSocket = (config) => {
19
33
  },
20
34
  content
21
35
  }));
22
- const newsletterWMexQuery = async (jid, queryId, content) => (query({
36
+ const newsletterWMexQuery = async (jid, query_id, content) => (query({
23
37
  tag: 'iq',
24
38
  attrs: {
25
39
  id: generateMessageTag(),
@@ -30,21 +44,15 @@ const makeNewsletterSocket = (config) => {
30
44
  content: [
31
45
  {
32
46
  tag: 'query',
33
- attrs: { 'query_id': queryId },
34
- content: encoder.encode(JSON.stringify({
35
- variables: {
36
- 'newsletter_id': jid,
37
- ...content
38
- }
39
- }))
47
+ attrs: { query_id },
48
+ content: encoder.encode(JSON.stringify({ variables: { newsletter_id: jid, ...content } }))
40
49
  }
41
50
  ]
42
51
  }));
43
52
  const parseFetchedUpdates = async (node, type) => {
44
53
  let child;
45
- if (type === 'messages') {
54
+ if (type === 'messages')
46
55
  child = (0, WABinary_1.getBinaryNodeChild)(node, 'messages');
47
- }
48
56
  else {
49
57
  const parent = (0, WABinary_1.getBinaryNodeChild)(node, 'message_updates');
50
58
  child = (0, WABinary_1.getBinaryNodeChild)(parent, 'messages');
@@ -52,21 +60,30 @@ const makeNewsletterSocket = (config) => {
52
60
  return await Promise.all((0, WABinary_1.getAllBinaryNodeChildren)(child).map(async (messageNode) => {
53
61
  var _a, _b;
54
62
  messageNode.attrs.from = child === null || child === void 0 ? void 0 : child.attrs.jid;
55
- const views = parseInt(((_b = (_a = (0, WABinary_1.getBinaryNodeChild)(messageNode, 'views_count')) === null || _a === void 0 ? void 0 : _a.attrs) === null || _b === void 0 ? void 0 : _b.count) || '0');
63
+ const views = (_b = (_a = (0, WABinary_1.getBinaryNodeChild)(messageNode, 'views_count')) === null || _a === void 0 ? void 0 : _a.attrs) === null || _b === void 0 ? void 0 : _b.count;
56
64
  const reactionNode = (0, WABinary_1.getBinaryNodeChild)(messageNode, 'reactions');
57
65
  const reactions = (0, WABinary_1.getBinaryNodeChildren)(reactionNode, 'reaction')
58
66
  .map(({ attrs }) => ({ count: +attrs.count, code: attrs.code }));
59
- const data = {
60
- 'server_id': messageNode.attrs.server_id,
61
- views,
62
- reactions
63
- };
67
+ let data;
64
68
  if (type === 'messages') {
65
69
  const { fullMessage: message, decrypt } = await (0, Utils_1.decryptMessageNode)(messageNode, authState.creds.me.id, authState.creds.me.lid || '', signalRepository, config.logger);
66
70
  await decrypt();
67
- data.message = message;
71
+ data = {
72
+ server_id: messageNode.attrs.server_id,
73
+ views: views ? +views : undefined,
74
+ reactions,
75
+ message
76
+ };
77
+ return data;
78
+ }
79
+ else {
80
+ data = {
81
+ server_id: messageNode.attrs.server_id,
82
+ views: views ? +views : undefined,
83
+ reactions
84
+ };
85
+ return data;
68
86
  }
69
- return data;
70
87
  }));
71
88
  };
72
89
  return {
@@ -77,48 +94,44 @@ const makeNewsletterSocket = (config) => {
77
94
  return (_a = (0, WABinary_1.getBinaryNodeChild)(result, 'live_updates')) === null || _a === void 0 ? void 0 : _a.attrs;
78
95
  },
79
96
  newsletterReactionMode: async (jid, mode) => {
80
- await newsletterWMexQuery(jid, Types_1.QueryIds.JOB_MUTATION, {
81
- updates: { settings: { 'reaction_codes': { value: mode } } }
97
+ await newsletterWMexQuery(jid, QueryIds.JOB_MUTATION, {
98
+ updates: { settings: { reaction_codes: { value: mode } } }
82
99
  });
83
100
  },
84
101
  newsletterUpdateDescription: async (jid, description) => {
85
- await newsletterWMexQuery(jid, Types_1.QueryIds.JOB_MUTATION, {
102
+ await newsletterWMexQuery(jid, QueryIds.JOB_MUTATION, {
86
103
  updates: { description: description || '', settings: null }
87
104
  });
88
105
  },
89
106
  newsletterUpdateName: async (jid, name) => {
90
- await newsletterWMexQuery(jid, Types_1.QueryIds.JOB_MUTATION, {
107
+ await newsletterWMexQuery(jid, QueryIds.JOB_MUTATION, {
91
108
  updates: { name, settings: null }
92
109
  });
93
110
  },
94
111
  newsletterUpdatePicture: async (jid, content) => {
95
112
  const { img } = await (0, Utils_1.generateProfilePicture)(content);
96
- await newsletterWMexQuery(jid, Types_1.QueryIds.JOB_MUTATION, {
113
+ await newsletterWMexQuery(jid, QueryIds.JOB_MUTATION, {
97
114
  updates: { picture: img.toString('base64'), settings: null }
98
115
  });
99
116
  },
100
117
  newsletterRemovePicture: async (jid) => {
101
- await newsletterWMexQuery(jid, Types_1.QueryIds.JOB_MUTATION, {
118
+ await newsletterWMexQuery(jid, QueryIds.JOB_MUTATION, {
102
119
  updates: { picture: '', settings: null }
103
120
  });
104
121
  },
105
122
  newsletterUnfollow: async (jid) => {
106
- await newsletterWMexQuery(jid, Types_1.QueryIds.UNFOLLOW);
123
+ await newsletterWMexQuery(jid, QueryIds.UNFOLLOW);
107
124
  },
108
125
  newsletterFollow: async (jid) => {
109
- await newsletterWMexQuery(jid, Types_1.QueryIds.FOLLOW);
126
+ await newsletterWMexQuery(jid, QueryIds.FOLLOW);
110
127
  },
111
128
  newsletterUnmute: async (jid) => {
112
- await newsletterWMexQuery(jid, Types_1.QueryIds.UNMUTE);
129
+ await newsletterWMexQuery(jid, QueryIds.UNMUTE);
113
130
  },
114
131
  newsletterMute: async (jid) => {
115
- await newsletterWMexQuery(jid, Types_1.QueryIds.MUTE);
116
- },
117
- newsletterAction: async (jid, type) => {
118
- await newsletterWMexQuery(jid, type.toUpperCase());
132
+ await newsletterWMexQuery(jid, QueryIds.MUTE);
119
133
  },
120
- newsletterCreate: async (name, description, reaction_codes) => {
121
- //TODO: Implement TOS system wide for Meta AI, communities, and here etc.
134
+ newsletterCreate: async (name, description) => {
122
135
  /**tos query */
123
136
  await query({
124
137
  tag: 'iq',
@@ -139,50 +152,50 @@ const makeNewsletterSocket = (config) => {
139
152
  }
140
153
  ]
141
154
  });
142
- const result = await newsletterWMexQuery(undefined, Types_1.QueryIds.CREATE, {
143
- input: { name, description, settings: { 'reaction_codes': { value: reaction_codes.toUpperCase() } } }
155
+ const result = await newsletterWMexQuery(undefined, QueryIds.CREATE, {
156
+ input: { name, description }
144
157
  });
145
158
  return (0, exports.extractNewsletterMetadata)(result, true);
146
159
  },
147
160
  newsletterMetadata: async (type, key, role) => {
148
- const result = await newsletterWMexQuery(undefined, Types_1.QueryIds.METADATA, {
161
+ const result = await newsletterWMexQuery(undefined, QueryIds.METADATA, {
149
162
  input: {
150
163
  key,
151
164
  type: type.toUpperCase(),
152
- 'view_role': role || 'GUEST'
165
+ view_role: role || 'GUEST'
153
166
  },
154
- 'fetch_viewer_metadata': true,
155
- 'fetch_full_image': true,
156
- 'fetch_creation_time': true
167
+ fetch_viewer_metadata: true,
168
+ fetch_full_image: true,
169
+ fetch_creation_time: true
157
170
  });
158
171
  return (0, exports.extractNewsletterMetadata)(result);
159
172
  },
160
173
  newsletterAdminCount: async (jid) => {
161
174
  var _a, _b;
162
- const result = await newsletterWMexQuery(jid, Types_1.QueryIds.ADMIN_COUNT);
175
+ const result = await newsletterWMexQuery(jid, QueryIds.ADMIN_COUNT);
163
176
  const buff = (_b = (_a = (0, WABinary_1.getBinaryNodeChild)(result, 'result')) === null || _a === void 0 ? void 0 : _a.content) === null || _b === void 0 ? void 0 : _b.toString();
164
177
  return JSON.parse(buff).data[Types_1.XWAPaths.ADMIN_COUNT].admin_count;
165
178
  },
166
179
  /**user is Lid, not Jid */
167
180
  newsletterChangeOwner: async (jid, user) => {
168
- await newsletterWMexQuery(jid, Types_1.QueryIds.CHANGE_OWNER, {
169
- 'user_id': user
181
+ await newsletterWMexQuery(jid, QueryIds.CHANGE_OWNER, {
182
+ user_id: user
170
183
  });
171
184
  },
172
185
  /**user is Lid, not Jid */
173
186
  newsletterDemote: async (jid, user) => {
174
- await newsletterWMexQuery(jid, Types_1.QueryIds.DEMOTE, {
175
- 'user_id': user
187
+ await newsletterWMexQuery(jid, QueryIds.DEMOTE, {
188
+ user_id: user
176
189
  });
177
190
  },
178
191
  newsletterDelete: async (jid) => {
179
- await newsletterWMexQuery(jid, Types_1.QueryIds.DELETE);
192
+ await newsletterWMexQuery(jid, QueryIds.DELETE);
180
193
  },
181
194
  /**if code wasn't passed, the reaction will be removed (if is reacted) */
182
- newsletterReactMessage: async (jid, serverId, code) => {
195
+ newsletterReactMessage: async (jid, server_id, code) => {
183
196
  await query({
184
197
  tag: 'message',
185
- attrs: { to: jid, ...(!code ? { edit: '7' } : {}), type: 'reaction', 'server_id': serverId, id: (0, Utils_1.generateMessageID)() },
198
+ attrs: { to: jid, ...(!code ? { edit: '7' } : {}), type: 'reaction', server_id, id: (0, Utils_1.generateMessageID)() },
186
199
  content: [{
187
200
  tag: 'reaction',
188
201
  attrs: code ? { code } : {}
@@ -211,25 +224,25 @@ const makeNewsletterSocket = (config) => {
211
224
  };
212
225
  exports.makeNewsletterSocket = makeNewsletterSocket;
213
226
  const extractNewsletterMetadata = (node, isCreate) => {
214
- var _a, _b, _c, _d, _e, _f, _g;
227
+ var _a, _b, _c, _d, _e;
215
228
  const result = (_b = (_a = (0, WABinary_1.getBinaryNodeChild)(node, 'result')) === null || _a === void 0 ? void 0 : _a.content) === null || _b === void 0 ? void 0 : _b.toString();
216
229
  const metadataPath = JSON.parse(result).data[isCreate ? Types_1.XWAPaths.CREATE : Types_1.XWAPaths.NEWSLETTER];
217
230
  const metadata = {
218
231
  id: metadataPath.id,
219
232
  state: metadataPath.state.type,
220
- 'creation_time': +metadataPath.thread_metadata.creation_time,
233
+ creation_time: +metadataPath.thread_metadata.creation_time,
221
234
  name: metadataPath.thread_metadata.name.text,
222
235
  nameTime: +metadataPath.thread_metadata.name.update_time,
223
236
  description: metadataPath.thread_metadata.description.text,
224
237
  descriptionTime: +metadataPath.thread_metadata.description.update_time,
225
238
  invite: metadataPath.thread_metadata.invite,
226
239
  handle: metadataPath.thread_metadata.handle,
227
- picture: ((_c = metadataPath.thread_metadata.picture) === null || _c === void 0 ? void 0 : _c.direct_path) || null,
228
- preview: ((_d = metadataPath.thread_metadata.preview) === null || _d === void 0 ? void 0 : _d.direct_path) || null,
229
- 'reaction_codes': (_g = (_f = (_e = metadataPath.thread_metadata) === null || _e === void 0 ? void 0 : _e.settings) === null || _f === void 0 ? void 0 : _f.reaction_codes) === null || _g === void 0 ? void 0 : _g.value,
240
+ picture: metadataPath.thread_metadata.picture.direct_path || null,
241
+ preview: metadataPath.thread_metadata.preview.direct_path || null,
242
+ reaction_codes: (_e = (_d = (_c = metadataPath.thread_metadata) === null || _c === void 0 ? void 0 : _c.settings) === null || _d === void 0 ? void 0 : _d.reaction_codes) === null || _e === void 0 ? void 0 : _e.value,
230
243
  subscribers: +metadataPath.thread_metadata.subscribers_count,
231
244
  verification: metadataPath.thread_metadata.verification,
232
- 'viewer_metadata': metadataPath.viewer_metadata
245
+ viewer_metadata: metadataPath.viewer_metadata
233
246
  };
234
247
  return metadata;
235
248
  };
@@ -1,7 +1,9 @@
1
1
  /// <reference types="node" />
2
+ /// <reference types="node" />
2
3
  import { Boom } from '@hapi/boom';
3
4
  import { SocketConfig } from '../Types';
4
5
  import { BinaryNode } from '../WABinary';
6
+ import { WebSocketClient } from './Client';
5
7
  /**
6
8
  * Connects to WA servers and performs:
7
9
  * - simple queries (no retry mechanism, wait for connection establishment)
@@ -10,7 +12,7 @@ import { BinaryNode } from '../WABinary';
10
12
  */
11
13
  export declare const makeSocket: (config: SocketConfig) => {
12
14
  type: "md";
13
- ws: any;
15
+ ws: WebSocketClient;
14
16
  ev: import("../Types").BaileysEventEmitter & {
15
17
  process(handler: (events: Partial<import("../Types").BaileysEventMap>) => void | Promise<void>): () => void;
16
18
  buffer(): void;
@@ -20,15 +20,14 @@ const Client_1 = require("./Client");
20
20
  const makeSocket = (config) => {
21
21
  var _a, _b;
22
22
  const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository, } = config;
23
- let url = typeof waWebSocketUrl === 'string' ? new url_1.URL(waWebSocketUrl) : waWebSocketUrl;
24
- config.mobile = config.mobile || url.protocol === 'tcp:';
25
- if (config.mobile && url.protocol !== 'tcp:') {
26
- url = new url_1.URL(`tcp://${Defaults_1.MOBILE_ENDPOINT}:${Defaults_1.MOBILE_PORT}`);
23
+ const url = typeof waWebSocketUrl === 'string' ? new url_1.URL(waWebSocketUrl) : waWebSocketUrl;
24
+ if (config.mobile || url.protocol === 'tcp:') {
25
+ throw new boom_1.Boom('Mobile API is not supported anymore', { statusCode: Types_1.DisconnectReason.loggedOut });
27
26
  }
28
- if (!config.mobile && url.protocol === 'wss' && ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.routingInfo)) {
27
+ if (url.protocol === 'wss' && ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.routingInfo)) {
29
28
  url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'));
30
29
  }
31
- const ws = config.socket ? config.socket : config.mobile ? new Client_1.MobileSocketClient(url, config) : new Client_1.WebSocketClient(url, config);
30
+ const ws = new Client_1.WebSocketClient(url, config);
32
31
  ws.connect();
33
32
  const ev = (0, Utils_1.makeEventBuffer)(logger);
34
33
  /** ephemeral key pair used to encrypt/decrypt communication. Unique for each connection */
@@ -36,8 +35,7 @@ const makeSocket = (config) => {
36
35
  /** WA noise protocol wrapper */
37
36
  const noise = (0, Utils_1.makeNoiseHandler)({
38
37
  keyPair: ephemeralKeyPair,
39
- NOISE_HEADER: config.mobile ? Defaults_1.MOBILE_NOISE_HEADER : Defaults_1.NOISE_WA_HEADER,
40
- mobile: config.mobile,
38
+ NOISE_HEADER: Defaults_1.NOISE_WA_HEADER,
41
39
  logger,
42
40
  routingInfo: (_b = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _b === void 0 ? void 0 : _b.routingInfo
43
41
  });
@@ -74,7 +72,8 @@ const makeSocket = (config) => {
74
72
  if (logger.level === 'trace') {
75
73
  logger.trace({ xml: (0, WABinary_1.binaryNodeToString)(frame), msg: 'xml send' });
76
74
  }
77
- const buff = (0, WABinary_1.encodeBinaryNode)(frame);
75
+ const node = (0, WABinary_1.encodeBinaryNode)(frame);
76
+ const buff = Buffer.from(node);
78
77
  return sendRawMessage(buff);
79
78
  };
80
79
  /** log & process any unexpected errors */
@@ -159,10 +158,7 @@ const makeSocket = (config) => {
159
158
  logger.trace({ handshake }, 'handshake recv from WA');
160
159
  const keyEnc = noise.processHandshake(handshake, creds.noiseKey);
161
160
  let node;
162
- if (config.mobile) {
163
- node = (0, Utils_1.generateMobileNode)(config);
164
- }
165
- else if (!creds.me) {
161
+ if (!creds.me) {
166
162
  node = (0, Utils_1.generateRegistrationNode)(creds, config);
167
163
  logger.info({ node }, 'not logged in, attempting registration...');
168
164
  }
@@ -232,11 +228,11 @@ const makeSocket = (config) => {
232
228
  const l0 = frame.tag;
233
229
  const l1 = frame.attrs || {};
234
230
  const l2 = Array.isArray(frame.content) ? (_a = frame.content[0]) === null || _a === void 0 ? void 0 : _a.tag : '';
235
- Object.keys(l1).forEach(key => {
231
+ for (const key of Object.keys(l1)) {
236
232
  anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered;
237
233
  anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered;
238
234
  anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered;
239
- });
235
+ }
240
236
  anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;
241
237
  anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;
242
238
  if (!anyTriggered && logger.level === 'debug') {
@@ -366,6 +362,7 @@ const makeSocket = (config) => {
366
362
  end(new boom_1.Boom(msg || 'Intentional Logout', { statusCode: Types_1.DisconnectReason.loggedOut }));
367
363
  };
368
364
  const requestPairingCode = async (phoneNumber) => {
365
+ await waitForSocketOpen();
369
366
  authState.creds.pairingCode = (0, Utils_1.bytesToCrockford)((0, crypto_1.randomBytes)(5));
370
367
  authState.creds.me = {
371
368
  id: (0, WABinary_1.jidEncode)(phoneNumber, 's.whatsapp.net'),
@@ -403,7 +400,7 @@ const makeSocket = (config) => {
403
400
  {
404
401
  tag: 'companion_platform_id',
405
402
  attrs: {},
406
- content: '49' // Chrome
403
+ content: (0, Utils_1.getPlatformId)(browser[1])
407
404
  },
408
405
  {
409
406
  tag: 'companion_platform_display',
@@ -424,7 +421,7 @@ const makeSocket = (config) => {
424
421
  async function generatePairingKey() {
425
422
  const salt = (0, crypto_1.randomBytes)(32);
426
423
  const randomIv = (0, crypto_1.randomBytes)(16);
427
- const key = (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
424
+ const key = await (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
428
425
  const ciphered = (0, Utils_1.aesEncryptCTR)(authState.creds.pairingEphemeralKeyPair.public, key, randomIv);
429
426
  return Buffer.concat([salt, randomIv, ciphered]);
430
427
  }
@@ -536,6 +533,7 @@ const makeSocket = (config) => {
536
533
  const routingInfo = (0, WABinary_1.getBinaryNodeChild)(edgeRoutingNode, 'routing_info');
537
534
  if (routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content) {
538
535
  authState.creds.routingInfo = Buffer.from(routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content);
536
+ ev.emit('creds.update', authState.creds);
539
537
  }
540
538
  });
541
539
  let didStartBuffer = false;
@@ -0,0 +1,38 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ import { Boom } from '@hapi/boom';
4
+ import { SocketConfig } from '../Types';
5
+ import { BinaryNode } from '../WABinary';
6
+ import { USyncQuery } from '../WAUSync';
7
+ export declare const makeUSyncSocket: (config: SocketConfig) => {
8
+ executeUSyncQuery: (usyncQuery: USyncQuery) => Promise<import("../WAUSync").USyncQueryResult | undefined>;
9
+ type: "md";
10
+ ws: import("./Client").WebSocketClient;
11
+ ev: import("../Types").BaileysEventEmitter & {
12
+ process(handler: (events: Partial<import("../Types").BaileysEventMap>) => void | Promise<void>): () => void;
13
+ buffer(): void;
14
+ createBufferedFunction<A extends any[], T>(work: (...args: A) => Promise<T>): (...args: A) => Promise<T>;
15
+ flush(force?: boolean | undefined): boolean;
16
+ isBuffering(): boolean;
17
+ };
18
+ authState: {
19
+ creds: import("../Types").AuthenticationCreds;
20
+ keys: import("../Types").SignalKeyStoreWithTransaction;
21
+ };
22
+ signalRepository: import("../Types").SignalRepository;
23
+ user: import("../Types").Contact | undefined;
24
+ generateMessageTag: () => string;
25
+ query: (node: BinaryNode, timeoutMs?: number | undefined) => Promise<BinaryNode>;
26
+ waitForMessage: <T_1>(msgId: string, timeoutMs?: number | undefined) => Promise<T_1>;
27
+ waitForSocketOpen: () => Promise<void>;
28
+ sendRawMessage: (data: Uint8Array | Buffer) => Promise<void>;
29
+ sendNode: (frame: BinaryNode) => Promise<void>;
30
+ logout: (msg?: string | undefined) => Promise<void>;
31
+ end: (error: Error | undefined) => void;
32
+ onUnexpectedError: (err: Error | Boom<any>, msg: string) => void;
33
+ uploadPreKeys: (count?: number) => Promise<void>;
34
+ uploadPreKeysToServerIfRequired: () => Promise<void>;
35
+ requestPairingCode: (phoneNumber: string) => Promise<string>;
36
+ waitForConnectionUpdate: (check: (u: Partial<import("../Types").ConnectionState>) => boolean | undefined, timeoutMs?: number | undefined) => Promise<void>;
37
+ sendWAMBuffer: (wamBuffer: Buffer) => Promise<BinaryNode>;
38
+ };
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.makeUSyncSocket = void 0;
4
+ const boom_1 = require("@hapi/boom");
5
+ const WABinary_1 = require("../WABinary");
6
+ const socket_1 = require("./socket");
7
+ const makeUSyncSocket = (config) => {
8
+ const sock = (0, socket_1.makeSocket)(config);
9
+ const { generateMessageTag, query, } = sock;
10
+ const executeUSyncQuery = async (usyncQuery) => {
11
+ if (usyncQuery.protocols.length === 0) {
12
+ throw new boom_1.Boom('USyncQuery must have at least one protocol');
13
+ }
14
+ // todo: validate users, throw WARNING on no valid users
15
+ // variable below has only validated users
16
+ const validUsers = usyncQuery.users;
17
+ const userNodes = validUsers.map((user) => {
18
+ return {
19
+ tag: 'user',
20
+ attrs: {
21
+ jid: !user.phone ? user.id : undefined,
22
+ },
23
+ content: usyncQuery.protocols
24
+ .map((a) => a.getUserElement(user))
25
+ .filter(a => a !== null)
26
+ };
27
+ });
28
+ const listNode = {
29
+ tag: 'list',
30
+ attrs: {},
31
+ content: userNodes
32
+ };
33
+ const queryNode = {
34
+ tag: 'query',
35
+ attrs: {},
36
+ content: usyncQuery.protocols.map((a) => a.getQueryElement())
37
+ };
38
+ const iq = {
39
+ tag: 'iq',
40
+ attrs: {
41
+ to: WABinary_1.S_WHATSAPP_NET,
42
+ type: 'get',
43
+ xmlns: 'usync',
44
+ },
45
+ content: [
46
+ {
47
+ tag: 'usync',
48
+ attrs: {
49
+ context: usyncQuery.context,
50
+ mode: usyncQuery.mode,
51
+ sid: generateMessageTag(),
52
+ last: 'true',
53
+ index: '0',
54
+ },
55
+ content: [
56
+ queryNode,
57
+ listNode
58
+ ]
59
+ }
60
+ ],
61
+ };
62
+ const result = await query(iq);
63
+ return usyncQuery.parseUSyncQueryResult(result);
64
+ };
65
+ return {
66
+ ...sock,
67
+ executeUSyncQuery,
68
+ };
69
+ };
70
+ exports.makeUSyncSocket = makeUSyncSocket;
@@ -1,5 +1,6 @@
1
+ import { Store } from 'cache-manager';
1
2
  import { AuthenticationCreds } from '../Types';
2
- declare const makeCacheManagerAuthState: (store: Storage, sessionKey: string) => Promise<{
3
+ declare const makeCacheManagerAuthState: (store: Store, sessionKey: string) => Promise<{
3
4
  clearState: () => Promise<void>;
4
5
  saveCreds: () => Promise<void>;
5
6
  state: {
@@ -66,7 +66,11 @@ exports.default = (config) => {
66
66
  ev.on('connection.update', update => {
67
67
  Object.assign(state, update);
68
68
  });
69
- ev.on('messaging-history.set', ({ chats: newChats, contacts: newContacts, messages: newMessages, isLatest }) => {
69
+ ev.on('messaging-history.set', ({ chats: newChats, contacts: newContacts, messages: newMessages, isLatest, syncType }) => {
70
+ if (syncType === WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND) {
71
+ return; // FOR NOW,
72
+ //TODO: HANDLE
73
+ }
70
74
  if (isLatest) {
71
75
  chats.clear();
72
76
  for (const id in messages) {
@@ -178,16 +182,14 @@ exports.default = (config) => {
178
182
  const jid = (0, WABinary_1.jidNormalizedUser)(msg.key.remoteJid);
179
183
  const list = assertMessageList(jid);
180
184
  list.upsert(msg, 'append');
181
- if (type === 'notify') {
182
- if (!chats.get(jid)) {
183
- ev.emit('chats.upsert', [
184
- {
185
- id: jid,
186
- conversationTimestamp: (0, Utils_1.toNumber)(msg.messageTimestamp),
187
- unreadCount: 1
188
- }
189
- ]);
190
- }
185
+ if (type === 'notify' && !chats.get(jid)) {
186
+ ev.emit('chats.upsert', [
187
+ {
188
+ id: jid,
189
+ conversationTimestamp: (0, Utils_1.toNumber)(msg.messageTimestamp),
190
+ unreadCount: 1
191
+ }
192
+ ]);
191
193
  }
192
194
  }
193
195
  break;
@@ -56,9 +56,9 @@ function makeOrderedDictionary(idGetter) {
56
56
  },
57
57
  clear: () => {
58
58
  array.splice(0, array.length);
59
- Object.keys(dict).forEach(key => {
59
+ for (const key of Object.keys(dict)) {
60
60
  delete dict[key];
61
- });
61
+ }
62
62
  },
63
63
  filter: (contain) => {
64
64
  let i = 0;
@@ -1,6 +1,6 @@
1
1
  /// <reference types="node" />
2
+ /// <reference types="node" />
2
3
  import type { proto } from '../../WAProto';
3
- import { RegistrationOptions } from '../Socket/registration';
4
4
  import type { Contact } from './Contact';
5
5
  import type { MinimalMessage } from './Message';
6
6
  export type KeyPair = {
@@ -57,12 +57,7 @@ export type AuthenticationCreds = SignalCreds & {
57
57
  /** number of times history & app state has been synced */
58
58
  accountSyncCounter: number;
59
59
  accountSettings: AccountSettings;
60
- deviceId: string;
61
- phoneId: string;
62
- identityId: Buffer;
63
60
  registered: boolean;
64
- backupToken: Buffer;
65
- registration: RegistrationOptions;
66
61
  pairingCode: string | undefined;
67
62
  lastPropHash: string | undefined;
68
63
  routingInfo: Buffer | undefined;
@@ -1,4 +1,4 @@
1
- export type WACallUpdateType = 'offer' | 'ringing' | 'timeout' | 'reject' | 'accept';
1
+ export type WACallUpdateType = 'offer' | 'ringing' | 'timeout' | 'reject' | 'accept' | 'terminate';
2
2
  export type WACallEvent = {
3
3
  chatId: string;
4
4
  from: string;
@@ -1,13 +1,17 @@
1
1
  import type { proto } from '../../WAProto';
2
2
  import type { AccountSettings } from './Auth';
3
+ import type { ContactAction } from './Contact';
3
4
  import type { BufferedEventData } from './Events';
5
+ import type { LabelActionBody } from './Label';
4
6
  import type { ChatLabelAssociationActionBody } from './LabelAssociation';
5
7
  import type { MessageLabelAssociationActionBody } from './LabelAssociation';
6
- import type { MinimalMessage } from './Message';
8
+ import type { MinimalMessage, WAMessageKey } from './Message';
7
9
  /** privacy settings in WhatsApp Web */
8
10
  export type WAPrivacyValue = 'all' | 'contacts' | 'contact_blacklist' | 'none';
9
11
  export type WAPrivacyOnlineValue = 'all' | 'match_last_seen';
12
+ export type WAPrivacyGroupAddValue = 'all' | 'contacts' | 'contact_blacklist';
10
13
  export type WAReadReceiptsValue = 'all' | 'none';
14
+ export type WAPrivacyCallValue = 'all' | 'known';
11
15
  /** set of statuses visible to other people; see updatePresence() in WhatsAppWeb.Send */
12
16
  export type WAPresence = 'unavailable' | 'available' | 'composing' | 'recording' | 'paused';
13
17
  export declare const ALL_WA_PATCH_NAMES: readonly ["critical_block", "critical_unblock_low", "regular_high", "regular_low", "regular"];
@@ -59,12 +63,12 @@ export type ChatModification = {
59
63
  /** mute for duration, or provide timestamp of mute to remove*/
60
64
  mute: number | null;
61
65
  } | {
62
- clear: 'all' | {
63
- messages: {
64
- id: string;
65
- fromMe?: boolean;
66
- timestamp: number;
67
- }[];
66
+ clear: boolean;
67
+ } | {
68
+ deleteForMe: {
69
+ deleteMedia: boolean;
70
+ key: WAMessageKey;
71
+ timestamp: number;
68
72
  };
69
73
  } | {
70
74
  star: {
@@ -80,6 +84,10 @@ export type ChatModification = {
80
84
  } | {
81
85
  delete: true;
82
86
  lastMessages: LastMessageList;
87
+ } | {
88
+ contact: ContactAction | null;
89
+ } | {
90
+ addLabel: LabelActionBody;
83
91
  } | {
84
92
  addChatLabel: ChatLabelAssociationActionBody;
85
93
  } | {
@@ -14,6 +14,11 @@ export interface Contact {
14
14
  * null => if the profile picture has not been set (default profile picture)
15
15
  * any other string => url of the profile picture
16
16
  */
17
- imgUrl?: string | null | 'changed';
17
+ imgUrl?: string | null;
18
18
  status?: string;
19
19
  }
20
+ export type ContactAction = {
21
+ fistName: string;
22
+ fullName: string;
23
+ saveOnPrimaryAddressbook: boolean;
24
+ };