supunmd-bail 2.1.1 → 2.1.3

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 (216) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +428 -0
  3. package/WAProto/index.js +130529 -45236
  4. package/engine-requirements.js +1 -1
  5. package/lib/Defaults/baileys-version.json +1 -1
  6. package/lib/Defaults/index.d.ts +9 -18
  7. package/lib/Defaults/index.js +136 -104
  8. package/lib/Defaults/phonenumber-mcc.json +223 -0
  9. package/lib/Signal/Group/ciphertext-message.d.ts +0 -1
  10. package/lib/Signal/Group/ciphertext-message.js +5 -2
  11. package/lib/Signal/Group/group-session-builder.d.ts +3 -4
  12. package/lib/Signal/Group/group-session-builder.js +41 -7
  13. package/lib/Signal/Group/group_cipher.d.ts +4 -4
  14. package/lib/Signal/Group/group_cipher.js +51 -37
  15. package/lib/Signal/Group/index.d.ts +11 -12
  16. package/lib/Signal/Group/index.js +57 -12
  17. package/lib/Signal/Group/keyhelper.d.ts +1 -2
  18. package/lib/Signal/Group/keyhelper.js +44 -7
  19. package/lib/Signal/Group/queue-job.d.ts +0 -1
  20. package/lib/Signal/Group/queue-job.js +5 -2
  21. package/lib/Signal/Group/sender-chain-key.d.ts +2 -3
  22. package/lib/Signal/Group/sender-chain-key.js +15 -7
  23. package/lib/Signal/Group/sender-key-distribution-message.d.ts +1 -2
  24. package/lib/Signal/Group/sender-key-distribution-message.js +11 -8
  25. package/lib/Signal/Group/sender-key-message.d.ts +1 -2
  26. package/lib/Signal/Group/sender-key-message.js +12 -9
  27. package/lib/Signal/Group/sender-key-name.d.ts +0 -1
  28. package/lib/Signal/Group/sender-key-name.js +5 -2
  29. package/lib/Signal/Group/sender-key-record.d.ts +2 -3
  30. package/lib/Signal/Group/sender-key-record.js +21 -9
  31. package/lib/Signal/Group/sender-key-state.d.ts +6 -7
  32. package/lib/Signal/Group/sender-key-state.js +42 -27
  33. package/lib/Signal/Group/sender-message-key.d.ts +0 -1
  34. package/lib/Signal/Group/sender-message-key.js +7 -4
  35. package/lib/Signal/libsignal.d.ts +3 -5
  36. package/lib/Signal/libsignal.js +90 -258
  37. package/lib/Socket/Client/{types.d.ts → abstract-socket-client.d.ts} +3 -2
  38. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  39. package/lib/Socket/Client/index.d.ts +3 -3
  40. package/lib/Socket/Client/index.js +19 -3
  41. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  42. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  43. package/lib/Socket/Client/{websocket.d.ts → web-socket-client.d.ts} +1 -2
  44. package/lib/Socket/Client/web-socket-client.js +62 -0
  45. package/lib/Socket/business.d.ts +108 -125
  46. package/lib/Socket/business.js +43 -159
  47. package/lib/Socket/chats.d.ts +239 -70
  48. package/lib/Socket/chats.js +384 -363
  49. package/lib/Socket/dugong.d.ts +254 -0
  50. package/lib/Socket/dugong.js +484 -0
  51. package/lib/Socket/groups.d.ts +56 -78
  52. package/lib/Socket/groups.js +96 -106
  53. package/lib/Socket/index.d.ts +115 -173
  54. package/lib/Socket/index.js +10 -17
  55. package/lib/Socket/messages-recv.d.ts +79 -91
  56. package/lib/Socket/messages-recv.js +521 -639
  57. package/lib/Socket/messages-send.d.ts +91 -111
  58. package/lib/Socket/messages-send.js +438 -599
  59. package/lib/Socket/newsletter.d.ts +84 -97
  60. package/lib/Socket/newsletter.js +1 -181
  61. package/lib/Socket/registration.d.ts +267 -0
  62. package/lib/Socket/registration.js +166 -0
  63. package/lib/Socket/socket.d.ts +18 -26
  64. package/lib/Socket/socket.js +230 -448
  65. package/lib/Socket/usync.d.ts +16 -17
  66. package/lib/Socket/usync.js +26 -19
  67. package/lib/Store/index.d.ts +3 -0
  68. package/lib/Store/index.js +10 -0
  69. package/lib/Store/make-cache-manager-store.d.ts +13 -0
  70. package/lib/Store/make-cache-manager-store.js +83 -0
  71. package/lib/Store/make-in-memory-store.d.ts +118 -0
  72. package/lib/Store/make-in-memory-store.js +427 -0
  73. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  74. package/lib/Store/make-ordered-dictionary.js +81 -0
  75. package/lib/Store/object-repository.d.ts +10 -0
  76. package/lib/Store/object-repository.js +27 -0
  77. package/lib/Types/Auth.d.ts +12 -13
  78. package/lib/Types/Auth.js +2 -2
  79. package/lib/Types/Call.d.ts +1 -2
  80. package/lib/Types/Call.js +2 -2
  81. package/lib/Types/Chat.d.ts +13 -34
  82. package/lib/Types/Chat.js +4 -8
  83. package/lib/Types/Contact.d.ts +1 -6
  84. package/lib/Types/Contact.js +2 -2
  85. package/lib/Types/Events.d.ts +15 -60
  86. package/lib/Types/Events.js +2 -2
  87. package/lib/Types/GroupMetadata.d.ts +5 -17
  88. package/lib/Types/GroupMetadata.js +2 -2
  89. package/lib/Types/Label.d.ts +0 -12
  90. package/lib/Types/Label.js +5 -3
  91. package/lib/Types/LabelAssociation.d.ts +0 -1
  92. package/lib/Types/LabelAssociation.js +5 -3
  93. package/lib/Types/Message.d.ts +54 -84
  94. package/lib/Types/Message.js +9 -11
  95. package/lib/Types/Newsletter.d.ts +98 -130
  96. package/lib/Types/Newsletter.js +38 -31
  97. package/lib/Types/Product.d.ts +1 -2
  98. package/lib/Types/Product.js +2 -2
  99. package/lib/Types/Signal.d.ts +1 -20
  100. package/lib/Types/Signal.js +2 -2
  101. package/lib/Types/Socket.d.ts +25 -47
  102. package/lib/Types/Socket.js +2 -3
  103. package/lib/Types/State.d.ts +2 -14
  104. package/lib/Types/State.js +2 -13
  105. package/lib/Types/USync.d.ts +2 -3
  106. package/lib/Types/USync.js +2 -2
  107. package/lib/Types/index.d.ts +14 -22
  108. package/lib/Types/index.js +31 -15
  109. package/lib/Utils/auth-utils.d.ts +6 -7
  110. package/lib/Utils/auth-utils.js +148 -199
  111. package/lib/Utils/baileys-event-stream.d.ts +1 -2
  112. package/lib/Utils/baileys-event-stream.js +22 -15
  113. package/lib/Utils/business.d.ts +2 -3
  114. package/lib/Utils/business.js +69 -66
  115. package/lib/Utils/chat-utils.d.ts +22 -21
  116. package/lib/Utils/chat-utils.js +226 -260
  117. package/lib/Utils/crypto.d.ts +19 -19
  118. package/lib/Utils/crypto.js +86 -77
  119. package/lib/Utils/decode-wa-message.d.ts +8 -37
  120. package/lib/Utils/decode-wa-message.js +83 -164
  121. package/lib/Utils/event-buffer.d.ts +8 -7
  122. package/lib/Utils/event-buffer.js +76 -110
  123. package/lib/Utils/generics.d.ts +29 -27
  124. package/lib/Utils/generics.js +210 -168
  125. package/lib/Utils/history.d.ts +8 -12
  126. package/lib/Utils/history.js +46 -34
  127. package/lib/Utils/index.d.ts +17 -20
  128. package/lib/Utils/index.js +33 -20
  129. package/lib/Utils/link-preview.d.ts +5 -5
  130. package/lib/Utils/link-preview.js +22 -14
  131. package/lib/Utils/logger.d.ts +3 -11
  132. package/lib/Utils/logger.js +7 -3
  133. package/lib/Utils/lt-hash.d.ts +8 -9
  134. package/lib/Utils/lt-hash.js +28 -25
  135. package/lib/Utils/make-mutex.d.ts +2 -3
  136. package/lib/Utils/make-mutex.js +10 -7
  137. package/lib/Utils/messages-media.d.ts +44 -42
  138. package/lib/Utils/messages-media.js +475 -319
  139. package/lib/Utils/messages.d.ts +18 -17
  140. package/lib/Utils/messages.js +259 -383
  141. package/lib/Utils/noise-handler.d.ts +15 -14
  142. package/lib/Utils/noise-handler.js +38 -30
  143. package/lib/Utils/process-message.d.ts +13 -14
  144. package/lib/Utils/process-message.js +147 -239
  145. package/lib/Utils/signal.d.ts +5 -7
  146. package/lib/Utils/signal.js +72 -78
  147. package/lib/Utils/use-multi-file-auth-state.d.ts +2 -2
  148. package/lib/Utils/use-multi-file-auth-state.js +27 -29
  149. package/lib/Utils/validate-connection.d.ts +7 -7
  150. package/lib/Utils/validate-connection.js +106 -72
  151. package/lib/WABinary/constants.d.ts +27 -25
  152. package/lib/WABinary/constants.js +20 -1281
  153. package/lib/WABinary/decode.d.ts +5 -5
  154. package/lib/WABinary/decode.js +42 -28
  155. package/lib/WABinary/encode.d.ts +3 -3
  156. package/lib/WABinary/encode.js +154 -105
  157. package/lib/WABinary/generic-utils.d.ts +7 -5
  158. package/lib/WABinary/generic-utils.js +63 -56
  159. package/lib/WABinary/index.d.ts +5 -6
  160. package/lib/WABinary/index.js +21 -6
  161. package/lib/WABinary/jid-utils.d.ts +8 -25
  162. package/lib/WABinary/jid-utils.js +40 -74
  163. package/lib/WABinary/types.d.ts +1 -2
  164. package/lib/WABinary/types.js +2 -2
  165. package/lib/WAM/BinaryInfo.d.ts +11 -3
  166. package/lib/WAM/BinaryInfo.js +5 -2
  167. package/lib/WAM/constants.d.ts +3 -5
  168. package/lib/WAM/constants.js +11958 -19461
  169. package/lib/WAM/encode.d.ts +3 -3
  170. package/lib/WAM/encode.js +22 -17
  171. package/lib/WAM/index.d.ts +3 -4
  172. package/lib/WAM/index.js +19 -4
  173. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +3 -4
  174. package/lib/WAUSync/Protocols/USyncContactProtocol.js +11 -8
  175. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +2 -3
  176. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +14 -11
  177. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +2 -3
  178. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +12 -9
  179. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +2 -3
  180. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +13 -9
  181. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +3 -4
  182. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +22 -20
  183. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +3 -5
  184. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +8 -13
  185. package/lib/WAUSync/Protocols/index.d.ts +4 -5
  186. package/lib/WAUSync/Protocols/index.js +20 -5
  187. package/lib/WAUSync/USyncQuery.d.ts +4 -5
  188. package/lib/WAUSync/USyncQuery.js +35 -40
  189. package/lib/WAUSync/USyncUser.d.ts +5 -6
  190. package/lib/WAUSync/USyncUser.js +5 -2
  191. package/lib/WAUSync/index.d.ts +3 -4
  192. package/lib/WAUSync/index.js +19 -4
  193. package/lib/index.d.ts +9 -19
  194. package/lib/index.js +1 -36
  195. package/package.json +109 -99
  196. package/WAProto/GenerateStatics.sh +0 -3
  197. package/WAProto/WAProto.proto +0 -5519
  198. package/WAProto/fix-imports.js +0 -29
  199. package/WAProto/index.d.ts +0 -11969
  200. package/lib/Signal/lid-mapping.d.ts +0 -23
  201. package/lib/Signal/lid-mapping.js +0 -171
  202. package/lib/Socket/Client/types.js +0 -11
  203. package/lib/Socket/Client/websocket.js +0 -50
  204. package/lib/Socket/communities.d.ts +0 -244
  205. package/lib/Socket/communities.js +0 -431
  206. package/lib/Socket/mex.d.ts +0 -3
  207. package/lib/Socket/mex.js +0 -42
  208. package/lib/Types/Bussines.d.ts +0 -25
  209. package/lib/Types/Bussines.js +0 -2
  210. package/lib/Utils/browser-utils.d.ts +0 -4
  211. package/lib/Utils/browser-utils.js +0 -28
  212. package/lib/Utils/message-retry-manager.d.ts +0 -82
  213. package/lib/Utils/message-retry-manager.js +0 -149
  214. package/lib/Utils/pre-key-manager.d.ts +0 -28
  215. package/lib/Utils/pre-key-manager.js +0 -106
  216. /package/lib/{supun → supunmd} +0 -0
@@ -1,16 +1,33 @@
1
- export * from './Auth.js';
2
- export * from './GroupMetadata.js';
3
- export * from './Chat.js';
4
- export * from './Contact.js';
5
- export * from './State.js';
6
- export * from './Message.js';
7
- export * from './Socket.js';
8
- export * from './Events.js';
9
- export * from './Product.js';
10
- export * from './Call.js';
11
- export * from './Signal.js';
12
- export * from './Newsletter.js';
13
- export var DisconnectReason;
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.DisconnectReason = void 0;
18
+ __exportStar(require("./Auth"), exports);
19
+ __exportStar(require("./GroupMetadata"), exports);
20
+ __exportStar(require("./Chat"), exports);
21
+ __exportStar(require("./Contact"), exports);
22
+ __exportStar(require("./State"), exports);
23
+ __exportStar(require("./Message"), exports);
24
+ __exportStar(require("./Newsletter"), exports);
25
+ __exportStar(require("./Socket"), exports);
26
+ __exportStar(require("./Events"), exports);
27
+ __exportStar(require("./Product"), exports);
28
+ __exportStar(require("./Call"), exports);
29
+ __exportStar(require("./Signal"), exports);
30
+ var DisconnectReason;
14
31
  (function (DisconnectReason) {
15
32
  DisconnectReason[DisconnectReason["connectionClosed"] = 428] = "connectionClosed";
16
33
  DisconnectReason[DisconnectReason["connectionLost"] = 408] = "connectionLost";
@@ -22,5 +39,4 @@ export var DisconnectReason;
22
39
  DisconnectReason[DisconnectReason["multideviceMismatch"] = 411] = "multideviceMismatch";
23
40
  DisconnectReason[DisconnectReason["forbidden"] = 403] = "forbidden";
24
41
  DisconnectReason[DisconnectReason["unavailableService"] = 503] = "unavailableService";
25
- })(DisconnectReason || (DisconnectReason = {}));
26
- //# sourceMappingURL=index.js.map
42
+ })(DisconnectReason = exports.DisconnectReason || (exports.DisconnectReason = {}));
@@ -1,19 +1,18 @@
1
- import type { AuthenticationCreds, CacheStore, SignalKeyStore, SignalKeyStoreWithTransaction, TransactionCapabilityOptions } from '../Types/index.js';
2
- import type { ILogger } from './logger.js';
1
+ import type { Logger } from 'pino';
2
+ import type { AuthenticationCreds, CacheStore, SignalKeyStore, SignalKeyStoreWithTransaction, TransactionCapabilityOptions } from '../Types';
3
3
  /**
4
4
  * Adds caching capability to a SignalKeyStore
5
5
  * @param store the store to add caching to
6
6
  * @param logger to log trace events
7
7
  * @param _cache cache store to use
8
8
  */
9
- export declare function makeCacheableSignalKeyStore(store: SignalKeyStore, logger?: ILogger, _cache?: CacheStore): SignalKeyStore;
9
+ export declare function makeCacheableSignalKeyStore(store: SignalKeyStore, logger: Logger, _cache?: CacheStore): SignalKeyStore;
10
10
  /**
11
- * Adds DB-like transaction capability to the SignalKeyStore
12
- * Uses AsyncLocalStorage for automatic context management
11
+ * Adds DB like transaction capability (https://en.wikipedia.org/wiki/Database_transaction) to the SignalKeyStore,
12
+ * this allows batch read & write operations & improves the performance of the lib
13
13
  * @param state the key store to apply this capability to
14
14
  * @param logger logger to log events
15
15
  * @returns SignalKeyStore with transaction capability
16
16
  */
17
- export declare const addTransactionCapability: (state: SignalKeyStore, logger: ILogger, { maxCommitRetries, delayBetweenTriesMs }: TransactionCapabilityOptions) => SignalKeyStoreWithTransaction;
17
+ export declare const addTransactionCapability: (state: SignalKeyStore, logger: Logger, { maxCommitRetries, delayBetweenTriesMs }: TransactionCapabilityOptions) => SignalKeyStoreWithTransaction;
18
18
  export declare const initAuthCreds: () => AuthenticationCreds;
19
- //# sourceMappingURL=auth-utils.d.ts.map
@@ -1,245 +1,189 @@
1
- import NodeCache from '@cacheable/node-cache';
2
- import { AsyncLocalStorage } from 'async_hooks';
3
- import { Mutex } from 'async-mutex';
4
- import { randomBytes } from 'crypto';
5
- import PQueue from 'p-queue';
6
- import { DEFAULT_CACHE_TTLS } from '../Defaults/index.js';
7
- import { Curve, signedKeyPair } from './crypto.js';
8
- import { delay, generateRegistrationId } from './generics.js';
9
- import { PreKeyManager } from './pre-key-manager.js';
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.initAuthCreds = exports.addTransactionCapability = exports.makeCacheableSignalKeyStore = void 0;
7
+ const crypto_1 = require("crypto");
8
+ const node_cache_1 = __importDefault(require("node-cache"));
9
+ const uuid_1 = require("uuid");
10
+ const Defaults_1 = require("../Defaults");
11
+ const crypto_2 = require("./crypto");
12
+ const generics_1 = require("./generics");
10
13
  /**
11
14
  * Adds caching capability to a SignalKeyStore
12
15
  * @param store the store to add caching to
13
16
  * @param logger to log trace events
14
17
  * @param _cache cache store to use
15
18
  */
16
- export function makeCacheableSignalKeyStore(store, logger, _cache) {
17
- const cache = _cache ||
18
- new NodeCache({
19
- stdTTL: DEFAULT_CACHE_TTLS.SIGNAL_STORE, // 5 minutes
20
- useClones: false,
21
- deleteOnExpire: true
22
- });
23
- // Mutex for protecting cache operations
24
- const cacheMutex = new Mutex();
19
+ function makeCacheableSignalKeyStore(store, logger, _cache) {
20
+ const cache = _cache || new node_cache_1.default({
21
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.SIGNAL_STORE,
22
+ useClones: false,
23
+ deleteOnExpire: true,
24
+ });
25
25
  function getUniqueId(type, id) {
26
26
  return `${type}.${id}`;
27
27
  }
28
28
  return {
29
29
  async get(type, ids) {
30
- return cacheMutex.runExclusive(async () => {
31
- const data = {};
32
- const idsToFetch = [];
33
- for (const id of ids) {
34
- const item = (await cache.get(getUniqueId(type, id)));
35
- if (typeof item !== 'undefined') {
36
- data[id] = item;
37
- }
38
- else {
39
- idsToFetch.push(id);
40
- }
30
+ const data = {};
31
+ const idsToFetch = [];
32
+ for (const id of ids) {
33
+ const item = cache.get(getUniqueId(type, id));
34
+ if (typeof item !== 'undefined') {
35
+ data[id] = item;
41
36
  }
42
- if (idsToFetch.length) {
43
- logger?.trace({ items: idsToFetch.length }, 'loading from store');
44
- const fetched = await store.get(type, idsToFetch);
45
- for (const id of idsToFetch) {
46
- const item = fetched[id];
47
- if (item) {
48
- data[id] = item;
49
- cache.set(getUniqueId(type, id), item);
50
- }
37
+ else {
38
+ idsToFetch.push(id);
39
+ }
40
+ }
41
+ if (idsToFetch.length) {
42
+ logger.trace({ items: idsToFetch.length }, 'loading from store');
43
+ const fetched = await store.get(type, idsToFetch);
44
+ for (const id of idsToFetch) {
45
+ const item = fetched[id];
46
+ if (item) {
47
+ data[id] = item;
48
+ cache.set(getUniqueId(type, id), item);
51
49
  }
52
50
  }
53
- return data;
54
- });
51
+ }
52
+ return data;
55
53
  },
56
54
  async set(data) {
57
- return cacheMutex.runExclusive(async () => {
58
- let keys = 0;
59
- for (const type in data) {
60
- for (const id in data[type]) {
61
- await cache.set(getUniqueId(type, id), data[type][id]);
62
- keys += 1;
63
- }
55
+ let keys = 0;
56
+ for (const type in data) {
57
+ for (const id in data[type]) {
58
+ cache.set(getUniqueId(type, id), data[type][id]);
59
+ keys += 1;
64
60
  }
65
- logger?.trace({ keys }, 'updated cache');
66
- await store.set(data);
67
- });
61
+ }
62
+ logger.trace({ keys }, 'updated cache');
63
+ await store.set(data);
68
64
  },
69
65
  async clear() {
70
- await cache.flushAll();
71
- await store.clear?.();
66
+ var _a;
67
+ cache.flushAll();
68
+ await ((_a = store.clear) === null || _a === void 0 ? void 0 : _a.call(store));
72
69
  }
73
70
  };
74
71
  }
72
+ exports.makeCacheableSignalKeyStore = makeCacheableSignalKeyStore;
75
73
  /**
76
- * Adds DB-like transaction capability to the SignalKeyStore
77
- * Uses AsyncLocalStorage for automatic context management
74
+ * Adds DB like transaction capability (https://en.wikipedia.org/wiki/Database_transaction) to the SignalKeyStore,
75
+ * this allows batch read & write operations & improves the performance of the lib
78
76
  * @param state the key store to apply this capability to
79
77
  * @param logger logger to log events
80
78
  * @returns SignalKeyStore with transaction capability
81
79
  */
82
- export const addTransactionCapability = (state, logger, { maxCommitRetries, delayBetweenTriesMs }) => {
83
- const txStorage = new AsyncLocalStorage();
84
- // Queues for concurrency control
85
- const keyQueues = new Map();
86
- const txMutexes = new Map();
87
- // Pre-key manager for specialized operations
88
- const preKeyManager = new PreKeyManager(state, logger);
89
- /**
90
- * Get or create a queue for a specific key type
91
- */
92
- function getQueue(key) {
93
- if (!keyQueues.has(key)) {
94
- keyQueues.set(key, new PQueue({ concurrency: 1 }));
95
- }
96
- return keyQueues.get(key);
97
- }
98
- /**
99
- * Get or create a transaction mutex
100
- */
101
- function getTxMutex(key) {
102
- if (!txMutexes.has(key)) {
103
- txMutexes.set(key, new Mutex());
104
- }
105
- return txMutexes.get(key);
106
- }
107
- /**
108
- * Check if currently in a transaction
109
- */
110
- function isInTransaction() {
111
- return !!txStorage.getStore();
112
- }
113
- /**
114
- * Commit transaction with retries
115
- */
116
- async function commitWithRetry(mutations) {
117
- if (Object.keys(mutations).length === 0) {
118
- logger.trace('no mutations in transaction');
119
- return;
120
- }
121
- logger.trace('committing transaction');
122
- for (let attempt = 0; attempt < maxCommitRetries; attempt++) {
123
- try {
124
- await state.set(mutations);
125
- logger.trace({ mutationCount: Object.keys(mutations).length }, 'committed transaction');
126
- return;
127
- }
128
- catch (error) {
129
- const retriesLeft = maxCommitRetries - attempt - 1;
130
- logger.warn(`failed to commit mutations, retries left=${retriesLeft}`);
131
- if (retriesLeft === 0) {
132
- throw error;
133
- }
134
- await delay(delayBetweenTriesMs);
135
- }
136
- }
137
- }
80
+ const addTransactionCapability = (state, logger, { maxCommitRetries, delayBetweenTriesMs }) => {
81
+ // number of queries made to the DB during the transaction
82
+ // only there for logging purposes
83
+ let dbQueriesInTransaction = 0;
84
+ let transactionCache = {};
85
+ let mutations = {};
86
+ let transactionsInProgress = 0;
138
87
  return {
139
88
  get: async (type, ids) => {
140
- const ctx = txStorage.getStore();
141
- if (!ctx) {
142
- // No transaction - direct read without exclusive lock for concurrency
143
- return state.get(type, ids);
144
- }
145
- // In transaction - check cache first
146
- const cached = ctx.cache[type] || {};
147
- const missing = ids.filter(id => !(id in cached));
148
- if (missing.length > 0) {
149
- ctx.dbQueries++;
150
- logger.trace({ type, count: missing.length }, 'fetching missing keys in transaction');
151
- const fetched = await getTxMutex(type).runExclusive(() => state.get(type, missing));
152
- // Update cache
153
- ctx.cache[type] = ctx.cache[type] || {};
154
- Object.assign(ctx.cache[type], fetched);
155
- }
156
- // Return requested ids from cache
157
- const result = {};
158
- for (const id of ids) {
159
- const value = ctx.cache[type]?.[id];
160
- if (value !== undefined && value !== null) {
161
- result[id] = value;
89
+ if (isInTransaction()) {
90
+ const dict = transactionCache[type];
91
+ const idsRequiringFetch = dict
92
+ ? ids.filter(item => typeof dict[item] === 'undefined')
93
+ : ids;
94
+ // only fetch if there are any items to fetch
95
+ if (idsRequiringFetch.length) {
96
+ dbQueriesInTransaction += 1;
97
+ const result = await state.get(type, idsRequiringFetch);
98
+ transactionCache[type] || (transactionCache[type] = {});
99
+ Object.assign(transactionCache[type], result);
162
100
  }
101
+ return ids.reduce((dict, id) => {
102
+ var _a;
103
+ const value = (_a = transactionCache[type]) === null || _a === void 0 ? void 0 : _a[id];
104
+ if (value) {
105
+ dict[id] = value;
106
+ }
107
+ return dict;
108
+ }, {});
109
+ }
110
+ else {
111
+ return state.get(type, ids);
163
112
  }
164
- return result;
165
113
  },
166
- set: async (data) => {
167
- const ctx = txStorage.getStore();
168
- if (!ctx) {
169
- // No transaction - direct write with queue protection
170
- const types = Object.keys(data);
171
- // Process pre-keys with validation
172
- for (const type_ of types) {
173
- const type = type_;
174
- if (type === 'pre-key') {
175
- await preKeyManager.validateDeletions(data, type);
176
- }
114
+ set: data => {
115
+ if (isInTransaction()) {
116
+ logger.trace({ types: Object.keys(data) }, 'caching in transaction');
117
+ for (const key in data) {
118
+ transactionCache[key] = transactionCache[key] || {};
119
+ Object.assign(transactionCache[key], data[key]);
120
+ mutations[key] = mutations[key] || {};
121
+ Object.assign(mutations[key], data[key]);
177
122
  }
178
- // Write all data in parallel
179
- await Promise.all(types.map(type => getQueue(type).add(async () => {
180
- const typeData = { [type]: data[type] };
181
- await state.set(typeData);
182
- })));
183
- return;
184
123
  }
185
- // In transaction - update cache and mutations
186
- logger.trace({ types: Object.keys(data) }, 'caching in transaction');
187
- for (const key_ in data) {
188
- const key = key_;
189
- // Ensure structures exist
190
- ctx.cache[key] = ctx.cache[key] || {};
191
- ctx.mutations[key] = ctx.mutations[key] || {};
192
- // Special handling for pre-keys
193
- if (key === 'pre-key') {
194
- await preKeyManager.processOperations(data, key, ctx.cache, ctx.mutations, true);
195
- }
196
- else {
197
- // Normal key types
198
- Object.assign(ctx.cache[key], data[key]);
199
- Object.assign(ctx.mutations[key], data[key]);
200
- }
124
+ else {
125
+ return state.set(data);
201
126
  }
202
127
  },
203
128
  isInTransaction,
204
- transaction: async (work, key) => {
205
- const existing = txStorage.getStore();
206
- // Nested transaction - reuse existing context
207
- if (existing) {
208
- logger.trace('reusing existing transaction context');
209
- return work();
210
- }
211
- // New transaction - acquire mutex and create context
212
- return getTxMutex(key).runExclusive(async () => {
213
- const ctx = {
214
- cache: {},
215
- mutations: {},
216
- dbQueries: 0
217
- };
129
+ async transaction(work) {
130
+ let result;
131
+ transactionsInProgress += 1;
132
+ if (transactionsInProgress === 1) {
218
133
  logger.trace('entering transaction');
219
- try {
220
- const result = await txStorage.run(ctx, work);
221
- // Commit mutations
222
- await commitWithRetry(ctx.mutations);
223
- logger.trace({ dbQueries: ctx.dbQueries }, 'transaction completed');
224
- return result;
134
+ }
135
+ try {
136
+ result = await work();
137
+ // commit if this is the outermost transaction
138
+ if (transactionsInProgress === 1) {
139
+ if (Object.keys(mutations).length) {
140
+ logger.trace('committing transaction');
141
+ // retry mechanism to ensure we've some recovery
142
+ // in case a transaction fails in the first attempt
143
+ let tries = maxCommitRetries;
144
+ while (tries) {
145
+ tries -= 1;
146
+ try {
147
+ await state.set(mutations);
148
+ logger.trace({ dbQueriesInTransaction }, 'committed transaction');
149
+ break;
150
+ }
151
+ catch (error) {
152
+ logger.warn(`failed to commit ${Object.keys(mutations).length} mutations, tries left=${tries}`);
153
+ await (0, generics_1.delay)(delayBetweenTriesMs);
154
+ }
155
+ }
156
+ }
157
+ else {
158
+ logger.trace('no mutations in transaction');
159
+ }
225
160
  }
226
- catch (error) {
227
- logger.error({ error }, 'transaction failed, rolling back');
228
- throw error;
161
+ }
162
+ finally {
163
+ transactionsInProgress -= 1;
164
+ if (transactionsInProgress === 0) {
165
+ transactionCache = {};
166
+ mutations = {};
167
+ dbQueriesInTransaction = 0;
229
168
  }
230
- });
169
+ }
170
+ return result;
231
171
  }
232
172
  };
173
+ function isInTransaction() {
174
+ return transactionsInProgress > 0;
175
+ }
233
176
  };
234
- export const initAuthCreds = () => {
235
- const identityKey = Curve.generateKeyPair();
177
+ exports.addTransactionCapability = addTransactionCapability;
178
+ const initAuthCreds = () => {
179
+ const identityKey = crypto_2.Curve.generateKeyPair();
236
180
  return {
237
- noiseKey: Curve.generateKeyPair(),
238
- pairingEphemeralKeyPair: Curve.generateKeyPair(),
181
+ noiseKey: crypto_2.Curve.generateKeyPair(),
182
+ pairingEphemeralKeyPair: crypto_2.Curve.generateKeyPair(),
239
183
  signedIdentityKey: identityKey,
240
- signedPreKey: signedKeyPair(identityKey, 1),
241
- registrationId: generateRegistrationId(),
242
- advSecretKey: randomBytes(32).toString('base64'),
184
+ signedPreKey: (0, crypto_2.signedKeyPair)(identityKey, 1),
185
+ registrationId: (0, generics_1.generateRegistrationId)(),
186
+ advSecretKey: (0, crypto_1.randomBytes)(32).toString('base64'),
243
187
  processedHistoryMessages: [],
244
188
  nextPreKeyId: 1,
245
189
  firstUnuploadedPreKeyId: 1,
@@ -247,11 +191,16 @@ export const initAuthCreds = () => {
247
191
  accountSettings: {
248
192
  unarchiveChats: false
249
193
  },
194
+ // mobile creds
195
+ deviceId: Buffer.from((0, uuid_1.v4)().replace(/-/g, ''), 'hex').toString('base64url'),
196
+ phoneId: (0, uuid_1.v4)(),
197
+ identityId: (0, crypto_1.randomBytes)(20),
250
198
  registered: false,
199
+ backupToken: (0, crypto_1.randomBytes)(20),
200
+ registration: {},
251
201
  pairingCode: undefined,
252
202
  lastPropHash: undefined,
253
203
  routingInfo: undefined,
254
- additionalData: undefined
255
204
  };
256
205
  };
257
- //# sourceMappingURL=auth-utils.js.map
206
+ exports.initAuthCreds = initAuthCreds;
@@ -1,4 +1,4 @@
1
- import type { BaileysEventEmitter } from '../Types/index.js';
1
+ import type { BaileysEventEmitter } from '../Types';
2
2
  /**
3
3
  * Captures events from a baileys event emitter & stores them in a file
4
4
  * @param ev The event emitter to read events from
@@ -14,4 +14,3 @@ export declare const readAndEmitEventStream: (filename: string, delayIntervalMs?
14
14
  ev: BaileysEventEmitter;
15
15
  task: Promise<void>;
16
16
  };
17
- //# sourceMappingURL=baileys-event-stream.d.ts.map
@@ -1,39 +1,46 @@
1
- import EventEmitter from 'events';
2
- import { createReadStream } from 'fs';
3
- import { writeFile } from 'fs/promises';
4
- import { createInterface } from 'readline';
5
- import { delay } from './generics.js';
6
- import { makeMutex } from './make-mutex.js';
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.readAndEmitEventStream = exports.captureEventStream = void 0;
7
+ const events_1 = __importDefault(require("events"));
8
+ const fs_1 = require("fs");
9
+ const promises_1 = require("fs/promises");
10
+ const readline_1 = require("readline");
11
+ const generics_1 = require("./generics");
12
+ const make_mutex_1 = require("./make-mutex");
7
13
  /**
8
14
  * Captures events from a baileys event emitter & stores them in a file
9
15
  * @param ev The event emitter to read events from
10
16
  * @param filename File to save to
11
17
  */
12
- export const captureEventStream = (ev, filename) => {
18
+ const captureEventStream = (ev, filename) => {
13
19
  const oldEmit = ev.emit;
14
20
  // write mutex so data is appended in order
15
- const writeMutex = makeMutex();
21
+ const writeMutex = (0, make_mutex_1.makeMutex)();
16
22
  // monkey patch eventemitter to capture all events
17
23
  ev.emit = function (...args) {
18
24
  const content = JSON.stringify({ timestamp: Date.now(), event: args[0], data: args[1] }) + '\n';
19
25
  const result = oldEmit.apply(ev, args);
20
26
  writeMutex.mutex(async () => {
21
- await writeFile(filename, content, { flag: 'a' });
27
+ await (0, promises_1.writeFile)(filename, content, { flag: 'a' });
22
28
  });
23
29
  return result;
24
30
  };
25
31
  };
32
+ exports.captureEventStream = captureEventStream;
26
33
  /**
27
34
  * Read event file and emit events from there
28
35
  * @param filename filename containing event data
29
36
  * @param delayIntervalMs delay between each event emit
30
37
  */
31
- export const readAndEmitEventStream = (filename, delayIntervalMs = 0) => {
32
- const ev = new EventEmitter();
38
+ const readAndEmitEventStream = (filename, delayIntervalMs = 0) => {
39
+ const ev = new events_1.default();
33
40
  const fireEvents = async () => {
34
41
  // from: https://stackoverflow.com/questions/6156501/read-a-file-one-line-at-a-time-in-node-js
35
- const fileStream = createReadStream(filename);
36
- const rl = createInterface({
42
+ const fileStream = (0, fs_1.createReadStream)(filename);
43
+ const rl = (0, readline_1.createInterface)({
37
44
  input: fileStream,
38
45
  crlfDelay: Infinity
39
46
  });
@@ -43,7 +50,7 @@ export const readAndEmitEventStream = (filename, delayIntervalMs = 0) => {
43
50
  if (line) {
44
51
  const { event, data } = JSON.parse(line);
45
52
  ev.emit(event, data);
46
- delayIntervalMs && (await delay(delayIntervalMs));
53
+ delayIntervalMs && await (0, generics_1.delay)(delayIntervalMs);
47
54
  }
48
55
  }
49
56
  fileStream.close();
@@ -53,4 +60,4 @@ export const readAndEmitEventStream = (filename, delayIntervalMs = 0) => {
53
60
  task: fireEvents()
54
61
  };
55
62
  };
56
- //# sourceMappingURL=baileys-event-stream.js.map
63
+ exports.readAndEmitEventStream = readAndEmitEventStream;
@@ -1,5 +1,5 @@
1
- import type { CatalogCollection, OrderDetails, Product, ProductCreate, ProductUpdate, WAMediaUpload, WAMediaUploadFunction } from '../Types/index.js';
2
- import { type BinaryNode } from '../WABinary/index.js';
1
+ import { CatalogCollection, OrderDetails, Product, ProductCreate, ProductUpdate, WAMediaUpload, WAMediaUploadFunction } from '../Types';
2
+ import { BinaryNode } from '../WABinary';
3
3
  export declare const parseCatalogNode: (node: BinaryNode) => {
4
4
  products: Product[];
5
5
  nextPageCursor: string | undefined;
@@ -20,4 +20,3 @@ export declare function uploadingNecessaryImagesOfProduct<T extends ProductUpdat
20
20
  export declare const uploadingNecessaryImages: (images: WAMediaUpload[], waUploadToServer: WAMediaUploadFunction, timeoutMs?: number) => Promise<{
21
21
  url: string;
22
22
  }[]>;
23
- //# sourceMappingURL=business.d.ts.map