angularsockets 1.0.1 → 1.0.2

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 (131) hide show
  1. package/README.md +1880 -36
  2. package/WAProto/index.d.ts +50383 -0
  3. package/WAProto/index.js +37203 -11791
  4. package/WASignalGroup/GroupProtocol.js +1697 -0
  5. package/WASignalGroup/ciphertext_message.js +16 -0
  6. package/WASignalGroup/group_cipher.js +120 -0
  7. package/WASignalGroup/group_session_builder.js +46 -0
  8. package/WASignalGroup/index.js +5 -0
  9. package/WASignalGroup/keyhelper.js +21 -0
  10. package/WASignalGroup/protobufs.js +3 -0
  11. package/WASignalGroup/queue_job.js +69 -0
  12. package/WASignalGroup/sender_chain_key.js +50 -0
  13. package/WASignalGroup/sender_key_distribution_message.js +78 -0
  14. package/WASignalGroup/sender_key_message.js +92 -0
  15. package/WASignalGroup/sender_key_name.js +70 -0
  16. package/WASignalGroup/sender_key_record.js +56 -0
  17. package/WASignalGroup/sender_key_state.js +129 -0
  18. package/{lib/Signal/Group/sender-message-key.js → WASignalGroup/sender_message_key.js} +16 -6
  19. package/lib/Defaults/baileys-version.json +1 -1
  20. package/lib/Defaults/index.js +79 -101
  21. package/lib/Signal/libsignal.js +29 -51
  22. package/lib/Socket/Client/web-socket-client.js +0 -2
  23. package/lib/Socket/business.d.ts +42 -43
  24. package/lib/Socket/chats.d.ts +9 -8
  25. package/lib/Socket/chats.js +107 -21
  26. package/lib/Socket/groups.d.ts +7 -7
  27. package/lib/Socket/groups.js +24 -25
  28. package/lib/Socket/index.d.ts +51 -52
  29. package/lib/Socket/messages-recv.d.ts +34 -37
  30. package/lib/Socket/messages-recv.js +37 -175
  31. package/lib/Socket/messages-send.d.ts +16 -10
  32. package/lib/Socket/messages-send.js +540 -346
  33. package/lib/Socket/newsletter.d.ts +26 -28
  34. package/lib/Socket/newsletter.js +4 -4
  35. package/lib/Socket/registration.d.ts +49 -52
  36. package/lib/Socket/registration.js +7 -7
  37. package/lib/Socket/socket.d.ts +1 -0
  38. package/lib/Socket/socket.js +36 -23
  39. package/lib/Socket/usync.d.ts +11 -10
  40. package/lib/Store/make-cache-manager-store.d.ts +2 -1
  41. package/lib/Store/make-in-memory-store.d.ts +2 -2
  42. package/lib/Store/make-in-memory-store.js +5 -1
  43. package/lib/Store/make-ordered-dictionary.js +2 -2
  44. package/lib/Types/Auth.d.ts +0 -1
  45. package/lib/Types/Call.d.ts +1 -1
  46. package/lib/Types/Chat.d.ts +12 -7
  47. package/lib/Types/Events.d.ts +17 -2
  48. package/lib/Types/GroupMetadata.d.ts +3 -2
  49. package/lib/Types/Label.d.ts +11 -0
  50. package/lib/Types/Label.js +1 -1
  51. package/lib/Types/LabelAssociation.js +1 -1
  52. package/lib/Types/Message.d.ts +170 -10
  53. package/lib/Types/Newsletter.js +3 -3
  54. package/lib/Types/Socket.d.ts +7 -2
  55. package/lib/Types/index.d.ts +9 -0
  56. package/lib/Types/index.js +1 -1
  57. package/lib/Utils/auth-utils.js +35 -14
  58. package/lib/Utils/business.d.ts +1 -1
  59. package/lib/Utils/business.js +2 -2
  60. package/lib/Utils/chat-utils.d.ts +11 -12
  61. package/lib/Utils/chat-utils.js +52 -36
  62. package/lib/Utils/crypto.d.ts +15 -16
  63. package/lib/Utils/crypto.js +74 -26
  64. package/lib/Utils/decode-wa-message.d.ts +17 -0
  65. package/lib/Utils/decode-wa-message.js +53 -17
  66. package/lib/Utils/event-buffer.js +10 -7
  67. package/lib/Utils/generics.d.ts +13 -17
  68. package/lib/Utils/generics.js +26 -15
  69. package/lib/Utils/history.d.ts +6 -2
  70. package/lib/Utils/history.js +4 -6
  71. package/lib/Utils/logger.d.ts +1 -3
  72. package/lib/Utils/lt-hash.js +12 -12
  73. package/lib/Utils/make-mutex.d.ts +2 -2
  74. package/lib/Utils/messages-media.d.ts +25 -28
  75. package/lib/Utils/messages-media.js +47 -57
  76. package/lib/Utils/messages.js +461 -44
  77. package/lib/Utils/noise-handler.d.ts +4 -5
  78. package/lib/Utils/noise-handler.js +19 -14
  79. package/lib/Utils/process-message.d.ts +5 -5
  80. package/lib/Utils/process-message.js +75 -23
  81. package/lib/Utils/signal.d.ts +2 -1
  82. package/lib/Utils/signal.js +43 -35
  83. package/lib/Utils/use-multi-file-auth-state.d.ts +0 -1
  84. package/lib/Utils/use-multi-file-auth-state.js +251 -36
  85. package/lib/Utils/use-single-file-auth-state.d.ts +12 -0
  86. package/lib/Utils/use-single-file-auth-state.js +75 -0
  87. package/lib/Utils/validate-connection.d.ts +1 -1
  88. package/lib/Utils/validate-connection.js +1 -1
  89. package/lib/WABinary/decode.d.ts +1 -2
  90. package/lib/WABinary/decode.js +23 -11
  91. package/lib/WABinary/encode.d.ts +1 -2
  92. package/lib/WABinary/encode.js +46 -22
  93. package/lib/WABinary/generic-utils.d.ts +2 -4
  94. package/lib/WABinary/generic-utils.js +2 -10
  95. package/lib/WABinary/jid-utils.d.ts +1 -1
  96. package/lib/WAM/BinaryInfo.d.ts +2 -11
  97. package/lib/WAM/encode.d.ts +1 -2
  98. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +3 -3
  99. package/lib/WAUSync/USyncUser.d.ts +0 -2
  100. package/lib/index.js +0 -6
  101. package/package.json +96 -104
  102. package/engine-requirements.js +0 -10
  103. package/lib/Defaults/phonenumber-mcc.json +0 -223
  104. package/lib/Signal/Group/ciphertext-message.d.ts +0 -9
  105. package/lib/Signal/Group/ciphertext-message.js +0 -15
  106. package/lib/Signal/Group/group-session-builder.d.ts +0 -14
  107. package/lib/Signal/Group/group-session-builder.js +0 -64
  108. package/lib/Signal/Group/group_cipher.d.ts +0 -17
  109. package/lib/Signal/Group/group_cipher.js +0 -96
  110. package/lib/Signal/Group/index.d.ts +0 -11
  111. package/lib/Signal/Group/index.js +0 -57
  112. package/lib/Signal/Group/keyhelper.d.ts +0 -10
  113. package/lib/Signal/Group/keyhelper.js +0 -55
  114. package/lib/Signal/Group/queue-job.d.ts +0 -1
  115. package/lib/Signal/Group/queue-job.js +0 -57
  116. package/lib/Signal/Group/sender-chain-key.d.ts +0 -13
  117. package/lib/Signal/Group/sender-chain-key.js +0 -34
  118. package/lib/Signal/Group/sender-key-distribution-message.d.ts +0 -16
  119. package/lib/Signal/Group/sender-key-distribution-message.js +0 -66
  120. package/lib/Signal/Group/sender-key-message.d.ts +0 -18
  121. package/lib/Signal/Group/sender-key-message.js +0 -69
  122. package/lib/Signal/Group/sender-key-name.d.ts +0 -17
  123. package/lib/Signal/Group/sender-key-name.js +0 -51
  124. package/lib/Signal/Group/sender-key-record.d.ts +0 -30
  125. package/lib/Signal/Group/sender-key-record.js +0 -53
  126. package/lib/Signal/Group/sender-key-state.d.ts +0 -38
  127. package/lib/Signal/Group/sender-key-state.js +0 -99
  128. package/lib/Signal/Group/sender-message-key.d.ts +0 -11
  129. package/lib/Socket/dugong.d.ts +0 -175
  130. package/lib/Socket/dugong.js +0 -342
  131. package/lib/index.d.ts +0 -12
@@ -1,80 +1,295 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.useMultiFileAuthState = void 0;
7
+ const async_lock_1 = __importDefault(require("async-lock"));
4
8
  const promises_1 = require("fs/promises");
5
9
  const path_1 = require("path");
6
10
  const WAProto_1 = require("../../WAProto");
7
11
  const auth_utils_1 = require("./auth-utils");
8
12
  const generics_1 = require("./generics");
13
+ const node_cache_1 = __importDefault(require("node-cache"));
14
+ const Defaults_1 = require("../Defaults");
15
+
16
+ // Enhanced locking mechanism
17
+ const fileLock = new async_lock_1.default({
18
+ maxPending: Infinity,
19
+ timeout: 5000 // 5s timeout to prevent deadlocks
20
+ });
21
+ const globalAuthLock = new async_lock_1.default(); // Additional global lock
22
+
23
+ // Debugging utilities
24
+ let AUTH_DEBUG = false;
25
+ function authDebug(...args) {
26
+ if (AUTH_DEBUG) {
27
+ console.log('[AUTH DEBUG]', new Date().toISOString(), ...args);
28
+ }
29
+ }
30
+
9
31
  /**
10
- * stores the full authentication state in a single folder.
11
- * Far more efficient than singlefileauthstate
12
- *
13
- * Again, I wouldn't endorse this for any production level use other than perhaps a bot.
14
- * Would recommend writing an auth state for use with a proper SQL or No-SQL DB
15
- * */
16
- const useMultiFileAuthState = async (folder) => {
17
- const writeData = (data, file) => {
18
- return (0, promises_1.writeFile)((0, path_1.join)(folder, fixFileName(file)), JSON.stringify(data, generics_1.BufferJSON.replacer));
19
- };
20
- const readData = async (file) => {
32
+ * Enhanced multi-file auth state storage with:
33
+ * - Better error handling
34
+ * - Additional locking
35
+ * - Data validation
36
+ * - Auto-repair mechanisms
37
+ */
38
+ const useMultiFileAuthState = async (folder, options = {}) => {
39
+ AUTH_DEBUG = options.authDebug ?? false;
40
+ const cache = options.syncCache ? new node_cache_1.default({
41
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.SIGNAL_STORE,
42
+ useClones: false,
43
+ deleteOnExpire: true,
44
+ checkperiod: 120
45
+ }) : null;
46
+ // Validate and prepare folder
47
+ const prepareFolder = async () => {
21
48
  try {
22
- const data = await (0, promises_1.readFile)((0, path_1.join)(folder, fixFileName(file)), { encoding: 'utf-8' });
23
- return JSON.parse(data, generics_1.BufferJSON.reviver);
24
- }
25
- catch (error) {
26
- return null;
49
+ const folderInfo = await (0, promises_1.stat)(folder).catch(() => null);
50
+
51
+ if (folderInfo) {
52
+ if (!folderInfo.isDirectory()) {
53
+ throw new Error(`Path exists but is not a directory: ${folder}`);
54
+ }
55
+ } else {
56
+ authDebug('Creating auth folder:', folder);
57
+ await (0, promises_1.mkdir)(folder, { recursive: true });
58
+ }
59
+
60
+ // Verify folder is writable
61
+ await testFolderAccess();
62
+ } catch (error) {
63
+ authDebug('Folder preparation failed:', error);
64
+ throw new Error(`Auth folder initialization failed: ${error.message}`);
27
65
  }
28
66
  };
29
- const removeData = async (file) => {
67
+
68
+ const testFolderAccess = async () => {
69
+ const testFile = (0, path_1.join)(folder, '.temp_test');
30
70
  try {
31
- await (0, promises_1.unlink)((0, path_1.join)(folder, fixFileName(file)));
32
- }
33
- catch (_a) {
71
+ await (0, promises_1.writeFile)(testFile, 'test');
72
+ await (0, promises_1.unlink)(testFile);
73
+ } catch (error) {
74
+ throw new Error(`Folder not writable: ${error.message}`);
34
75
  }
35
76
  };
36
- const folderInfo = await (0, promises_1.stat)(folder).catch(() => { });
37
- if (folderInfo) {
38
- if (!folderInfo.isDirectory()) {
39
- throw new Error(`found something that is not a directory at ${folder}, either delete it or specify a different location`);
40
- }
77
+
78
+ const fixFileName = (file) => {
79
+ if (!file) return file;
80
+ return file.replace(/\//g, '__').replace(/:/g, '-');
81
+ };
82
+
83
+ function getUniqueId(type, id) {
84
+ return `${type}.${id}`;
85
+ }
86
+
87
+ // Enhanced write with retries
88
+ const writeData = async (data, file) => {
89
+ return globalAuthLock.acquire('write', async () => {
90
+ const filePath = (0, path_1.join)(folder, fixFileName(file));
91
+ let attempts = 0;
92
+ const maxAttempts = 3;
93
+
94
+ while (attempts < maxAttempts) {
95
+ attempts++;
96
+ try {
97
+ await fileLock.acquire(filePath, async () => {
98
+ const serialized = JSON.stringify(data, generics_1.BufferJSON.replacer);
99
+ await (0, promises_1.writeFile)(filePath, serialized);
100
+ authDebug('Write successful:', file);
101
+ });
102
+ return;
103
+ } catch (error) {
104
+ authDebug(`Write attempt ${attempts} failed for ${file}:`, error);
105
+ if (attempts >= maxAttempts) {
106
+ throw new Error(`Failed to write after ${maxAttempts} attempts: ${error.message}`);
107
+ }
108
+ await new Promise(resolve => setTimeout(resolve, 100 * attempts));
109
+ }
110
+ }
111
+ });
112
+ };
113
+
114
+ // Enhanced read with validation
115
+ const readData = async (file) => {
116
+ return globalAuthLock.acquire('read', async () => {
117
+ const filePath = (0, path_1.join)(folder, fixFileName(file));
118
+
119
+ try {
120
+ const data = await fileLock.acquire(filePath, async () => {
121
+ const content = await (0, promises_1.readFile)(filePath, { encoding: 'utf-8' });
122
+ authDebug('Read successful:', file);
123
+ return content;
124
+ });
125
+
126
+ const parsed = JSON.parse(data, generics_1.BufferJSON.reviver);
127
+
128
+ // Basic data validation
129
+ if (file === 'creds.json' && !parsed.me) {
130
+ authDebug('Invalid creds data detected');
131
+ return null;
132
+ }
133
+
134
+ return parsed;
135
+ } catch (error) {
136
+ if (error.code !== 'ENOENT') { // Ignore "file not found" errors
137
+ authDebug('Read error:', file, error);
138
+ }
139
+ return null;
140
+ }
141
+ });
142
+ };
143
+
144
+ // Safe removal
145
+ const removeData = async (file) => {
146
+ return globalAuthLock.acquire('remove', async () => {
147
+ const filePath = (0, path_1.join)(folder, fixFileName(file));
148
+
149
+ try {
150
+ await fileLock.acquire(filePath, async () => {
151
+ await (0, promises_1.unlink)(filePath);
152
+ authDebug('Removed:', file);
153
+ });
154
+ } catch (error) {
155
+ if (error.code !== 'ENOENT') { // Ignore "file not found" errors
156
+ authDebug('Remove error:', file, error);
157
+ }
158
+ }
159
+ });
160
+ };
161
+
162
+ // Initialize
163
+ await prepareFolder();
164
+
165
+ // Load or initialize credentials
166
+ let creds = await readData('creds.json');
167
+ if (!creds) {
168
+ authDebug('No existing creds found, initializing new ones');
169
+ creds = (0, auth_utils_1.initAuthCreds)();
170
+ await writeData(creds, 'creds.json');
41
171
  }
42
- else {
43
- await (0, promises_1.mkdir)(folder, { recursive: true });
172
+
173
+ async function warmUpCache() {
174
+ try {
175
+ const files = await promises_1.readdir(folder);
176
+ for (const file of files) {
177
+ if (file.endsWith('.json') && file !== 'creds.json') {
178
+ const parts = file.split('-');
179
+ if (parts.length === 2) {
180
+ const type = parts[0];
181
+ const id = parts[1].replace('.json', '');
182
+ const data = await readData(file);
183
+ if (data) {
184
+ cache.set(getUniqueId(type, id), data);
185
+ authDebug(`Cache warmed: ${type}-${id}`);
186
+ }
187
+ }
188
+ }
189
+ }
190
+ } catch (error) {
191
+ authDebug('Cache warm-up failed:', error);
192
+ }
44
193
  }
45
- const fixFileName = (file) => { var _a; return (_a = file === null || file === void 0 ? void 0 : file.replace(/\//g, '__')) === null || _a === void 0 ? void 0 : _a.replace(/:/g, '-'); };
46
- const creds = await readData('creds.json') || (0, auth_utils_1.initAuthCreds)();
194
+
195
+ if (cache) warmUpCache();
196
+
197
+ // Auto-save mechanism
198
+ let saveTimeout;
199
+ const scheduleSave = () => {
200
+ if (saveTimeout) clearTimeout(saveTimeout);
201
+ saveTimeout = setTimeout(() => {
202
+ saveCreds().catch(error => {
203
+ authDebug('Auto-save failed, retrying sooner:', error);
204
+ setTimeout(scheduleSave, 60000);
205
+ });
206
+ }, 180000);
207
+ };
208
+ // Enhanced save function
209
+ const saveCreds = async () => {
210
+ try {
211
+ await writeData(creds, 'creds.json');
212
+ scheduleSave();
213
+ } catch (error) {
214
+ authDebug('Critical: Creds save failed:', error);
215
+ throw error;
216
+ }
217
+ };
218
+
219
+ process.on('beforeExit', async () => {
220
+ if (saveTimeout) clearTimeout(saveTimeout);
221
+ await saveCreds().catch(error => {
222
+ authDebug('Emergency save failed:', error);
223
+ });
224
+ });
225
+
226
+ process.on('uncaughtException', async (error) => {
227
+ authDebug('Uncaught exception, attempting emergency save:', error);
228
+ if (saveTimeout) clearTimeout(saveTimeout);
229
+ await saveCreds().catch(e => {
230
+ authDebug('Emergency save failed:', e);
231
+ });
232
+ process.exit(1);
233
+ });
234
+ // Start auto-save loop
235
+ scheduleSave();
236
+
47
237
  return {
48
238
  state: {
49
239
  creds,
50
240
  keys: {
51
241
  get: async (type, ids) => {
52
242
  const data = {};
243
+
53
244
  await Promise.all(ids.map(async (id) => {
54
245
  let value = await readData(`${type}-${id}.json`);
246
+
55
247
  if (type === 'app-state-sync-key' && value) {
56
- value = WAProto_1.proto.Message.AppStateSyncKeyData.fromObject(value);
248
+ try {
249
+ value = WAProto_1.proto.Message.AppStateSyncKeyData.fromObject(value);
250
+ } catch (error) {
251
+ authDebug('Key conversion failed:', type, id, error);
252
+ value = null;
253
+ }
57
254
  }
255
+
58
256
  data[id] = value;
59
257
  }));
258
+
60
259
  return data;
61
260
  },
62
261
  set: async (data) => {
63
262
  const tasks = [];
263
+
64
264
  for (const category in data) {
65
265
  for (const id in data[category]) {
66
266
  const value = data[category][id];
67
267
  const file = `${category}-${id}.json`;
68
- tasks.push(value ? writeData(value, file) : removeData(file));
268
+
269
+ if (value) {
270
+ tasks.push(writeData(value, file));
271
+ } else {
272
+ tasks.push(removeData(file));
273
+ }
69
274
  }
70
275
  }
71
- await Promise.all(tasks);
276
+
277
+ try {
278
+ await Promise.all(tasks);
279
+ } catch (error) {
280
+ authDebug('Bulk key update failed:', error);
281
+ throw error;
282
+ }
72
283
  }
73
284
  }
74
285
  },
75
- saveCreds: () => {
76
- return writeData(creds, 'creds.json');
77
- }
286
+ saveCreds,
287
+ // Additional maintenance API
288
+ cleanup: async () => {
289
+ if (saveTimeout) clearTimeout(saveTimeout);
290
+ await saveCreds();
291
+ },
292
+ cache
78
293
  };
79
294
  };
80
- exports.useMultiFileAuthState = useMultiFileAuthState;
295
+ exports.useMultiFileAuthState = useMultiFileAuthState;
@@ -0,0 +1,12 @@
1
+ import type { Logger } from 'pino';
2
+ import type { AuthenticationState } from '../Types';
3
+ /**
4
+ * @deprecated use multi file auth state instead please
5
+ * stores the full authentication state in a single JSON file
6
+ *
7
+ * DO NOT USE IN A PROD ENVIRONMENT, only meant to serve as an example
8
+ * */
9
+ export declare const useSingleFileAuthState: (filename: string, logger?: Logger) => {
10
+ state: AuthenticationState;
11
+ saveState: () => void;
12
+ };
@@ -0,0 +1,75 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useSingleFileAuthState = void 0;
4
+ const WAProto_1 = require("../../WAProto");
5
+ const auth_utils_1 = require("./auth-utils");
6
+ const generics_1 = require("./generics");
7
+ // useless key map only there to maintain backwards compatibility
8
+ // do not use in your own systems please
9
+ const KEY_MAP = {
10
+ 'pre-key': 'preKeys',
11
+ 'session': 'sessions',
12
+ 'sender-key': 'senderKeys',
13
+ 'app-state-sync-key': 'appStateSyncKeys',
14
+ 'app-state-sync-version': 'appStateVersions',
15
+ 'sender-key-memory': 'senderKeyMemory'
16
+ };
17
+ /**
18
+ * @deprecated use multi file auth state instead please
19
+ * stores the full authentication state in a single JSON file
20
+ *
21
+ * DO NOT USE IN A PROD ENVIRONMENT, only meant to serve as an example
22
+ * */
23
+ const useSingleFileAuthState = (filename, logger) => {
24
+ // require fs here so that in case "fs" is not available -- the app does not crash
25
+ const { readFileSync, writeFileSync, existsSync } = require('fs');
26
+ let creds;
27
+ let keys = {};
28
+ // save the authentication state to a file
29
+ const saveState = () => {
30
+ logger && logger.trace('saving auth state');
31
+ writeFileSync(filename,
32
+ // BufferJSON replacer utility saves buffers nicely
33
+ JSON.stringify({ creds, keys }, generics_1.BufferJSON.replacer, 2));
34
+ };
35
+ if (existsSync(filename)) {
36
+ const result = JSON.parse(readFileSync(filename, { encoding: 'utf-8' }), generics_1.BufferJSON.reviver);
37
+ creds = result.creds;
38
+ keys = result.keys;
39
+ }
40
+ else {
41
+ creds = (0, auth_utils_1.initAuthCreds)();
42
+ keys = {};
43
+ }
44
+ return {
45
+ state: {
46
+ creds,
47
+ keys: {
48
+ get: (type, ids) => {
49
+ const key = KEY_MAP[type];
50
+ return ids.reduce((dict, id) => {
51
+ var _a;
52
+ let value = (_a = keys[key]) === null || _a === void 0 ? void 0 : _a[id];
53
+ if (value) {
54
+ if (type === 'app-state-sync-key') {
55
+ value = WAProto_1.proto.Message.AppStateSyncKeyData.fromObject(value);
56
+ }
57
+ dict[id] = value;
58
+ }
59
+ return dict;
60
+ }, {});
61
+ },
62
+ set: (data) => {
63
+ for (const _key in data) {
64
+ const key = KEY_MAP[_key];
65
+ keys[key] = keys[key] || {};
66
+ Object.assign(keys[key], data[_key]);
67
+ }
68
+ saveState();
69
+ }
70
+ }
71
+ },
72
+ saveState
73
+ };
74
+ };
75
+ exports.useSingleFileAuthState = useSingleFileAuthState;
@@ -7,5 +7,5 @@ export declare const generateRegistrationNode: ({ registrationId, signedPreKey,
7
7
  export declare const configureSuccessfulPairing: (stanza: BinaryNode, { advSecretKey, signedIdentityKey, signalIdentities }: Pick<AuthenticationCreds, 'advSecretKey' | 'signedIdentityKey' | 'signalIdentities'>) => {
8
8
  creds: Partial<AuthenticationCreds>;
9
9
  reply: BinaryNode;
10
- };
10
+ };
11
11
  export declare const encodeSignedDeviceIdentity: (account: proto.IADVSignedDeviceIdentity, includeSignatureKey: boolean) => Uint8Array;
@@ -8,7 +8,7 @@ const Defaults_1 = require("../Defaults");
8
8
  const WABinary_1 = require("../WABinary");
9
9
  const crypto_2 = require("./crypto");
10
10
  const generics_1 = require("./generics");
11
- const signal_1 = require("./signal");
11
+ const signal_1 = require("./signal");
12
12
  const getUserAgent = (config) => {
13
13
  var _a, _b;
14
14
  const osVersion = config.mobile ? '15.3.1' : '0.1';
@@ -1,7 +1,6 @@
1
- /// <reference types="node" />
2
1
  import type { BinaryNode, BinaryNodeCodingOptions } from './types';
3
2
  export declare const decompressingIfRequired: (buffer: Buffer) => Buffer;
4
- export declare const decodeDecompressedBinaryNode: (buffer: Buffer, opts: Pick<BinaryNodeCodingOptions, 'DOUBLE_BYTE_TOKENS' | 'SINGLE_BYTE_TOKENS' | 'TAGS'>, indexRef?: {
3
+ export declare const decodeDecompressedBinaryNode: (buffer: Buffer, opts: Pick<BinaryNodeCodingOptions, "DOUBLE_BYTE_TOKENS" | "SINGLE_BYTE_TOKENS" | "TAGS">, indexRef?: {
5
4
  index: number;
6
5
  }) => BinaryNode;
7
6
  export declare const decodeBinaryNode: (buff: Buffer) => BinaryNode;
@@ -15,21 +15,33 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (
15
15
  }) : function(o, v) {
16
16
  o["default"] = v;
17
17
  });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
25
35
  Object.defineProperty(exports, "__esModule", { value: true });
26
36
  exports.decodeBinaryNode = exports.decodeDecompressedBinaryNode = exports.decompressingIfRequired = void 0;
37
+ const util_1 = require("util");
27
38
  const zlib_1 = require("zlib");
28
39
  const constants = __importStar(require("./constants"));
29
40
  const jid_utils_1 = require("./jid-utils");
30
- const decompressingIfRequired = (buffer) => {
41
+ const inflatePromise = (0, util_1.promisify)(zlib_1.inflate);
42
+ const decompressingIfRequired = async (buffer) => {
31
43
  if (2 & buffer.readUInt8()) {
32
- buffer = (0, zlib_1.inflateSync)(buffer.slice(1));
44
+ buffer = await inflatePromise(buffer.slice(1));
33
45
  }
34
46
  else { // nodes with no compression have a 0x00 prefix, we remove that
35
47
  buffer = buffer.slice(1);
@@ -245,8 +257,8 @@ const decodeDecompressedBinaryNode = (buffer, opts, indexRef = { index: 0 }) =>
245
257
  };
246
258
  };
247
259
  exports.decodeDecompressedBinaryNode = decodeDecompressedBinaryNode;
248
- const decodeBinaryNode = (buff) => {
249
- const decompBuff = (0, exports.decompressingIfRequired)(buff);
260
+ const decodeBinaryNode = async (buff) => {
261
+ const decompBuff = await (0, exports.decompressingIfRequired)(buff);
250
262
  return (0, exports.decodeDecompressedBinaryNode)(decompBuff, constants);
251
263
  };
252
264
  exports.decodeBinaryNode = decodeBinaryNode;
@@ -1,3 +1,2 @@
1
- /// <reference types="node" />
2
1
  import type { BinaryNode, BinaryNodeCodingOptions } from './types';
3
- export declare const encodeBinaryNode: ({ tag, attrs, content }: BinaryNode, opts?: Pick<BinaryNodeCodingOptions, 'TAGS' | 'TOKEN_MAP'>, buffer?: number[]) => Buffer;
2
+ export declare const encodeBinaryNode: (node: BinaryNode, opts?: Pick<BinaryNodeCodingOptions, "TAGS" | "TOKEN_MAP">, buffer?: number[]) => Buffer;
@@ -15,18 +15,33 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (
15
15
  }) : function(o, v) {
16
16
  o["default"] = v;
17
17
  });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
25
35
  Object.defineProperty(exports, "__esModule", { value: true });
26
36
  exports.encodeBinaryNode = void 0;
27
37
  const constants = __importStar(require("./constants"));
28
38
  const jid_utils_1 = require("./jid-utils");
29
- const encodeBinaryNode = ({ tag, attrs, content }, opts = constants, buffer = [0]) => {
39
+ const encodeBinaryNode = (node, opts = constants, buffer = [0]) => {
40
+ const encoded = encodeBinaryNodeInner(node, opts, buffer);
41
+ return Buffer.from(encoded);
42
+ };
43
+ exports.encodeBinaryNode = encodeBinaryNode;
44
+ const encodeBinaryNodeInner = ({ tag, attrs, content }, opts, buffer) => {
30
45
  const { TAGS, TOKEN_MAP } = opts;
31
46
  const pushByte = (value) => buffer.push(value & 0xff);
32
47
  const pushInt = (value, n, littleEndian = false) => {
@@ -35,7 +50,11 @@ const encodeBinaryNode = ({ tag, attrs, content }, opts = constants, buffer = [0
35
50
  buffer.push((value >> (curShift * 8)) & 0xff);
36
51
  }
37
52
  };
38
- const pushBytes = (bytes) => (bytes.forEach(b => buffer.push(b)));
53
+ const pushBytes = (bytes) => {
54
+ for (const b of bytes) {
55
+ buffer.push(b);
56
+ }
57
+ };
39
58
  const pushInt16 = (value) => {
40
59
  pushBytes([(value >> 8) & 0xff, value & 0xff]);
41
60
  };
@@ -134,11 +153,10 @@ const encodeBinaryNode = ({ tag, attrs, content }, opts = constants, buffer = [0
134
153
  }
135
154
  };
136
155
  const isNibble = (str) => {
137
- if (str.length > TAGS.PACKED_MAX) {
156
+ if (!str || str.length > TAGS.PACKED_MAX) {
138
157
  return false;
139
158
  }
140
- for (let i = 0; i < str.length; i++) {
141
- const char = str[i];
159
+ for (const char of str) {
142
160
  const isInNibbleRange = char >= '0' && char <= '9';
143
161
  if (!isInNibbleRange && char !== '-' && char !== '.') {
144
162
  return false;
@@ -147,19 +165,22 @@ const encodeBinaryNode = ({ tag, attrs, content }, opts = constants, buffer = [0
147
165
  return true;
148
166
  };
149
167
  const isHex = (str) => {
150
- if (str.length > TAGS.PACKED_MAX) {
168
+ if (!str || str.length > TAGS.PACKED_MAX) {
151
169
  return false;
152
170
  }
153
- for (let i = 0; i < str.length; i++) {
154
- const char = str[i];
171
+ for (const char of str) {
155
172
  const isInNibbleRange = char >= '0' && char <= '9';
156
- if (!isInNibbleRange && !(char >= 'A' && char <= 'F') && !(char >= 'a' && char <= 'f')) {
173
+ if (!isInNibbleRange && !(char >= 'A' && char <= 'F')) {
157
174
  return false;
158
175
  }
159
176
  }
160
177
  return true;
161
178
  };
162
179
  const writeString = (str) => {
180
+ if (str === undefined || str === null) {
181
+ pushByte(TAGS.LIST_EMPTY);
182
+ return;
183
+ }
163
184
  const tokenIndex = TOKEN_MAP[str];
164
185
  if (tokenIndex) {
165
186
  if (typeof tokenIndex.dict === 'number') {
@@ -195,7 +216,10 @@ const encodeBinaryNode = ({ tag, attrs, content }, opts = constants, buffer = [0
195
216
  pushInt16(listSize);
196
217
  }
197
218
  };
198
- const validAttributes = Object.keys(attrs).filter(k => (typeof attrs[k] !== 'undefined' && attrs[k] !== null));
219
+ if (!tag) {
220
+ throw new Error('Invalid node: tag cannot be undefined');
221
+ }
222
+ const validAttributes = Object.keys(attrs || {}).filter(k => (typeof attrs[k] !== 'undefined' && attrs[k] !== null));
199
223
  writeListStart(2 * validAttributes.length + 1 + (typeof content !== 'undefined' ? 1 : 0));
200
224
  writeString(tag);
201
225
  for (const key of validAttributes) {
@@ -212,9 +236,10 @@ const encodeBinaryNode = ({ tag, attrs, content }, opts = constants, buffer = [0
212
236
  pushBytes(content);
213
237
  }
214
238
  else if (Array.isArray(content)) {
215
- writeListStart(content.length);
216
- for (const item of content) {
217
- (0, exports.encodeBinaryNode)(item, opts, buffer);
239
+ const validContent = content.filter(item => item && (item.tag || Buffer.isBuffer(item) || item instanceof Uint8Array || typeof item === 'string'));
240
+ writeListStart(validContent.length);
241
+ for (const item of validContent) {
242
+ encodeBinaryNodeInner(item, opts, buffer);
218
243
  }
219
244
  }
220
245
  else if (typeof content === 'undefined') {
@@ -223,6 +248,5 @@ const encodeBinaryNode = ({ tag, attrs, content }, opts = constants, buffer = [0
223
248
  else {
224
249
  throw new Error(`invalid children for header "${tag}": ${content} (${typeof content})`);
225
250
  }
226
- return Buffer.from(buffer);
251
+ return buffer;
227
252
  };
228
- exports.encodeBinaryNode = encodeBinaryNode;
@@ -1,11 +1,10 @@
1
- /// <reference types="node" />
2
1
  import { proto } from '../../WAProto';
3
2
  import { BinaryNode } from './types';
4
3
  export declare const getBinaryNodeChildren: (node: BinaryNode | undefined, childTag: string) => BinaryNode[];
5
4
  export declare const getAllBinaryNodeChildren: ({ content }: BinaryNode) => BinaryNode[];
6
5
  export declare const getBinaryNodeChild: (node: BinaryNode | undefined, childTag: string) => BinaryNode | undefined;
7
- export declare const getBinaryNodeChildBuffer: (node: BinaryNode | undefined, childTag: string) => Uint8Array | Buffer | undefined;
8
- export declare const getBinaryNodeChildString: (node: BinaryNode | undefined, childTag: string) => string | undefined;
6
+ export declare const getBinaryNodeChildBuffer: (node: BinaryNode | undefined, childTag: string) => string | Uint8Array<ArrayBufferLike> | BinaryNode[] | undefined;
7
+ export declare const getBinaryNodeChildString: (node: BinaryNode | undefined, childTag: string) => any;
9
8
  export declare const getBinaryNodeChildUInt: (node: BinaryNode, childTag: string, length: number) => number | undefined;
10
9
  export declare const assertNodeErrorFree: (node: BinaryNode) => void;
11
10
  export declare const reduceBinaryNodeToDictionary: (node: BinaryNode, tag: string) => {
@@ -13,4 +12,3 @@ export declare const reduceBinaryNodeToDictionary: (node: BinaryNode, tag: strin
13
12
  };
14
13
  export declare const getBinaryNodeMessages: ({ content }: BinaryNode) => proto.WebMessageInfo[];
15
14
  export declare function binaryNodeToString(node: BinaryNode | BinaryNode['content'], i?: number): any;
16
- export declare const getBinaryFilteredBizBot: (nodeContent: BinaryNode | BinaryNode['content']) => BinaryNode['content']