@queenanya/baileys 7.5.11 → 8.0.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 (157) hide show
  1. package/package.json +13 -97
  2. package/LICENSE +0 -21
  3. package/README.md +0 -931
  4. package/WAProto/GenerateStatics.sh +0 -4
  5. package/WAProto/WAProto.proto +0 -3344
  6. package/WAProto/index.d.ts +0 -37016
  7. package/WAProto/index.js +0 -101044
  8. package/WASignalGroup/GroupProtocol.js +0 -1697
  9. package/WASignalGroup/ciphertext_message.js +0 -16
  10. package/WASignalGroup/group_cipher.js +0 -120
  11. package/WASignalGroup/group_session_builder.js +0 -46
  12. package/WASignalGroup/index.js +0 -5
  13. package/WASignalGroup/keyhelper.js +0 -21
  14. package/WASignalGroup/protobufs.js +0 -3
  15. package/WASignalGroup/queue_job.js +0 -69
  16. package/WASignalGroup/sender_chain_key.js +0 -50
  17. package/WASignalGroup/sender_key_distribution_message.js +0 -78
  18. package/WASignalGroup/sender_key_message.js +0 -92
  19. package/WASignalGroup/sender_key_name.js +0 -70
  20. package/WASignalGroup/sender_key_record.js +0 -56
  21. package/WASignalGroup/sender_key_state.js +0 -129
  22. package/WASignalGroup/sender_message_key.js +0 -39
  23. package/lib/Defaults/baileys-version.json +0 -3
  24. package/lib/Defaults/index.d.ts +0 -53
  25. package/lib/Defaults/index.js +0 -107
  26. package/lib/Signal/libsignal.d.ts +0 -3
  27. package/lib/Signal/libsignal.js +0 -152
  28. package/lib/Socket/Client/index.d.ts +0 -2
  29. package/lib/Socket/Client/index.js +0 -18
  30. package/lib/Socket/Client/types.d.ts +0 -17
  31. package/lib/Socket/Client/types.js +0 -13
  32. package/lib/Socket/Client/websocket.d.ts +0 -12
  33. package/lib/Socket/Client/websocket.js +0 -62
  34. package/lib/Socket/business.d.ts +0 -177
  35. package/lib/Socket/business.js +0 -260
  36. package/lib/Socket/chats.d.ts +0 -91
  37. package/lib/Socket/chats.js +0 -949
  38. package/lib/Socket/groups.d.ts +0 -131
  39. package/lib/Socket/groups.js +0 -314
  40. package/lib/Socket/index.d.ts +0 -177
  41. package/lib/Socket/index.js +0 -10
  42. package/lib/Socket/messages-recv.d.ts +0 -164
  43. package/lib/Socket/messages-recv.js +0 -918
  44. package/lib/Socket/messages-send.d.ts +0 -157
  45. package/lib/Socket/messages-send.js +0 -794
  46. package/lib/Socket/newsletter.d.ts +0 -143
  47. package/lib/Socket/newsletter.js +0 -249
  48. package/lib/Socket/socket.d.ts +0 -45
  49. package/lib/Socket/socket.js +0 -616
  50. package/lib/Store/index.d.ts +0 -3
  51. package/lib/Store/index.js +0 -10
  52. package/lib/Store/make-cache-manager-store.d.ts +0 -14
  53. package/lib/Store/make-cache-manager-store.js +0 -83
  54. package/lib/Store/make-in-memory-store.d.ts +0 -118
  55. package/lib/Store/make-in-memory-store.js +0 -420
  56. package/lib/Store/make-ordered-dictionary.d.ts +0 -13
  57. package/lib/Store/make-ordered-dictionary.js +0 -81
  58. package/lib/Store/object-repository.d.ts +0 -10
  59. package/lib/Store/object-repository.js +0 -27
  60. package/lib/Types/Auth.d.ts +0 -105
  61. package/lib/Types/Auth.js +0 -2
  62. package/lib/Types/Call.d.ts +0 -13
  63. package/lib/Types/Call.js +0 -2
  64. package/lib/Types/Chat.d.ts +0 -107
  65. package/lib/Types/Chat.js +0 -4
  66. package/lib/Types/Contact.d.ts +0 -19
  67. package/lib/Types/Contact.js +0 -2
  68. package/lib/Types/Events.d.ts +0 -199
  69. package/lib/Types/Events.js +0 -2
  70. package/lib/Types/GroupMetadata.d.ts +0 -56
  71. package/lib/Types/GroupMetadata.js +0 -2
  72. package/lib/Types/Label.d.ts +0 -46
  73. package/lib/Types/Label.js +0 -27
  74. package/lib/Types/LabelAssociation.d.ts +0 -29
  75. package/lib/Types/LabelAssociation.js +0 -9
  76. package/lib/Types/Message.d.ts +0 -280
  77. package/lib/Types/Message.js +0 -9
  78. package/lib/Types/Newsletter.d.ts +0 -79
  79. package/lib/Types/Newsletter.js +0 -18
  80. package/lib/Types/Product.d.ts +0 -78
  81. package/lib/Types/Product.js +0 -2
  82. package/lib/Types/Signal.d.ts +0 -57
  83. package/lib/Types/Signal.js +0 -2
  84. package/lib/Types/Socket.d.ts +0 -118
  85. package/lib/Types/Socket.js +0 -2
  86. package/lib/Types/State.d.ts +0 -27
  87. package/lib/Types/State.js +0 -2
  88. package/lib/Types/index.d.ts +0 -65
  89. package/lib/Types/index.js +0 -42
  90. package/lib/Utils/auth-utils.d.ts +0 -18
  91. package/lib/Utils/auth-utils.js +0 -200
  92. package/lib/Utils/baileys-event-stream.d.ts +0 -16
  93. package/lib/Utils/baileys-event-stream.js +0 -63
  94. package/lib/Utils/business.d.ts +0 -22
  95. package/lib/Utils/business.js +0 -234
  96. package/lib/Utils/chat-utils.d.ts +0 -72
  97. package/lib/Utils/chat-utils.js +0 -745
  98. package/lib/Utils/crypto.d.ts +0 -42
  99. package/lib/Utils/crypto.js +0 -153
  100. package/lib/Utils/decode-wa-message.d.ts +0 -20
  101. package/lib/Utils/decode-wa-message.js +0 -218
  102. package/lib/Utils/event-buffer.d.ts +0 -35
  103. package/lib/Utils/event-buffer.js +0 -520
  104. package/lib/Utils/generics.d.ts +0 -119
  105. package/lib/Utils/generics.js +0 -467
  106. package/lib/Utils/history.d.ts +0 -19
  107. package/lib/Utils/history.js +0 -94
  108. package/lib/Utils/index.d.ts +0 -18
  109. package/lib/Utils/index.js +0 -34
  110. package/lib/Utils/link-preview.d.ts +0 -21
  111. package/lib/Utils/link-preview.js +0 -116
  112. package/lib/Utils/logger.d.ts +0 -2
  113. package/lib/Utils/logger.js +0 -7
  114. package/lib/Utils/lt-hash.d.ts +0 -12
  115. package/lib/Utils/lt-hash.js +0 -51
  116. package/lib/Utils/make-mutex.d.ts +0 -7
  117. package/lib/Utils/make-mutex.js +0 -44
  118. package/lib/Utils/messages-media.d.ts +0 -131
  119. package/lib/Utils/messages-media.js +0 -786
  120. package/lib/Utils/messages.d.ts +0 -78
  121. package/lib/Utils/messages.js +0 -767
  122. package/lib/Utils/noise-handler.d.ts +0 -21
  123. package/lib/Utils/noise-handler.js +0 -150
  124. package/lib/Utils/process-message.d.ts +0 -42
  125. package/lib/Utils/process-message.js +0 -355
  126. package/lib/Utils/signal.d.ts +0 -32
  127. package/lib/Utils/signal.js +0 -158
  128. package/lib/Utils/use-multi-file-auth-state.d.ts +0 -12
  129. package/lib/Utils/use-multi-file-auth-state.js +0 -94
  130. package/lib/Utils/use-single-file-auth-state.d.ts +0 -5
  131. package/lib/Utils/use-single-file-auth-state.js +0 -66
  132. package/lib/Utils/validate-connection.d.ts +0 -10
  133. package/lib/Utils/validate-connection.js +0 -171
  134. package/lib/WABinary/constants.d.ts +0 -27
  135. package/lib/WABinary/constants.js +0 -40
  136. package/lib/WABinary/decode.d.ts +0 -8
  137. package/lib/WABinary/decode.js +0 -254
  138. package/lib/WABinary/encode.d.ts +0 -2
  139. package/lib/WABinary/encode.js +0 -230
  140. package/lib/WABinary/generic-utils.d.ts +0 -16
  141. package/lib/WABinary/generic-utils.js +0 -110
  142. package/lib/WABinary/index.d.ts +0 -5
  143. package/lib/WABinary/index.js +0 -21
  144. package/lib/WABinary/jid-utils.d.ts +0 -31
  145. package/lib/WABinary/jid-utils.js +0 -62
  146. package/lib/WABinary/types.d.ts +0 -18
  147. package/lib/WABinary/types.js +0 -2
  148. package/lib/WAM/BinaryInfo.d.ts +0 -18
  149. package/lib/WAM/BinaryInfo.js +0 -13
  150. package/lib/WAM/constants.d.ts +0 -39
  151. package/lib/WAM/constants.js +0 -15350
  152. package/lib/WAM/encode.d.ts +0 -4
  153. package/lib/WAM/encode.js +0 -155
  154. package/lib/WAM/index.d.ts +0 -3
  155. package/lib/WAM/index.js +0 -19
  156. package/lib/index.d.ts +0 -11
  157. package/lib/index.js +0 -30
@@ -1,118 +0,0 @@
1
- /// <reference types="node" />
2
- /// <reference types="node" />
3
- import { AxiosRequestConfig } from 'axios';
4
- import type { Agent } from 'https';
5
- import type { Logger } from 'pino';
6
- import type { URL } from 'url';
7
- import { proto } from '../../WAProto';
8
- import { AuthenticationState, SignalAuthState, TransactionCapabilityOptions } from './Auth';
9
- import { GroupMetadata } from './GroupMetadata';
10
- import { MediaConnInfo } from './Message';
11
- import { SignalRepository } from './Signal';
12
- export type WAVersion = [number, number, number];
13
- export type WABrowserDescription = [string, string, string];
14
- export type CacheStore = {
15
- /** get a cached key and change the stats */
16
- get<T>(key: string): T | undefined;
17
- /** set a key in the cache */
18
- set<T>(key: string, value: T): void;
19
- /** delete a key from the cache */
20
- del(key: string): void;
21
- /** flush all data */
22
- flushAll(): void;
23
- };
24
- export type SocketConfig = {
25
- /** the WS url to connect to WA */
26
- waWebSocketUrl: string | URL;
27
- /** Fails the connection if the socket times out in this interval */
28
- connectTimeoutMs: number;
29
- /** Default timeout for queries, undefined for no timeout */
30
- defaultQueryTimeoutMs: number | undefined;
31
- /** ping-pong interval for WS connection */
32
- keepAliveIntervalMs: number;
33
- /** should baileys use the mobile api instead of the multi device api
34
- * @deprecated This feature has been removed
35
- */
36
- mobile?: boolean;
37
- /** proxy agent */
38
- agent?: Agent;
39
- /** pino logger */
40
- logger: Logger;
41
- /** version to connect with */
42
- version: WAVersion;
43
- /** override browser config */
44
- browser: WABrowserDescription;
45
- /** agent used for fetch requests -- uploading/downloading media */
46
- fetchAgent?: Agent;
47
- /** should the QR be printed in the terminal */
48
- printQRInTerminal: boolean;
49
- /** should events be emitted for actions done by this socket connection */
50
- emitOwnEvents: boolean;
51
- /** custom upload hosts to upload media to */
52
- customUploadHosts: MediaConnInfo['hosts'];
53
- /** time to wait between sending new retry requests */
54
- retryRequestDelayMs: number;
55
- /** max retry count */
56
- maxMsgRetryCount: number;
57
- /** time to wait for the generation of the next QR in ms */
58
- qrTimeout?: number;
59
- /** provide an auth state object to maintain the auth state */
60
- auth: AuthenticationState;
61
- /** manage history processing with this control; by default will sync up everything */
62
- shouldSyncHistoryMessage: (msg: proto.Message.IHistorySyncNotification) => boolean;
63
- /** transaction capability options for SignalKeyStore */
64
- transactionOpts: TransactionCapabilityOptions;
65
- /** marks the client as online whenever the socket successfully connects */
66
- markOnlineOnConnect: boolean;
67
- /** provide a cache to store media, so does not have to be re-uploaded */
68
- mediaCache?: CacheStore;
69
- /**
70
- * map to store the retry counts for failed messages;
71
- * used to determine whether to retry a message or not */
72
- msgRetryCounterCache?: CacheStore;
73
- /** provide a cache to store a user's device list */
74
- userDevicesCache?: CacheStore;
75
- /** cache to store call offers */
76
- callOfferCache?: CacheStore;
77
- /** cache to track placeholder resends */
78
- placeholderResendCache?: CacheStore;
79
- /** width for link preview images */
80
- linkPreviewImageThumbnailWidth: number;
81
- /** Should Baileys ask the phone for full history, will be received async */
82
- syncFullHistory: boolean;
83
- /** Ignore Message when offline, default is false */
84
- ignoreMsgLoading: boolean;
85
- /** Should baileys fire init queries automatically, default true */
86
- fireInitQueries: boolean;
87
- /**
88
- * generate a high quality link preview,
89
- * entails uploading the jpegThumbnail to WA
90
- * */
91
- generateHighQualityLinkPreview: boolean;
92
- /**
93
- * Returns if a jid should be ignored,
94
- * no event for that jid will be triggered.
95
- * Messages from that jid will also not be decrypted
96
- * */
97
- shouldIgnoreJid: (jid: string) => boolean | undefined;
98
- /**
99
- * Optionally patch the message before sending out
100
- * */
101
- patchMessageBeforeSending: (msg: proto.IMessage, recipientJids: string[]) => Promise<proto.IMessage> | proto.IMessage;
102
- /** verify app state MACs */
103
- appStateMacVerification: {
104
- patch: boolean;
105
- snapshot: boolean;
106
- };
107
- /** options for axios */
108
- options: AxiosRequestConfig<{}>;
109
- /**
110
- * fetch a message from your store
111
- * implement this so that messages failed to send
112
- * (solves the "this message can take a while" issue) can be retried
113
- * */
114
- getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined>;
115
- /** cached group metadata, use to prevent redundant requests to WA & speed up msg sending */
116
- cachedGroupMetadata: (jid: string) => Promise<GroupMetadata | undefined>;
117
- makeSignalRepository: (auth: SignalAuthState) => SignalRepository;
118
- };
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,27 +0,0 @@
1
- import { Contact } from './Contact';
2
- export type WAConnectionState = 'open' | 'connecting' | 'close';
3
- export type ConnectionState = {
4
- /** connection is now open, connecting or closed */
5
- connection: WAConnectionState;
6
- /** the error that caused the connection to close */
7
- lastDisconnect?: {
8
- error: Error | undefined;
9
- date: Date;
10
- };
11
- /** is this a new login */
12
- isNewLogin?: boolean;
13
- /** the current QR code */
14
- qr?: string;
15
- /** has the device received all pending notifications while it was offline */
16
- receivedPendingNotifications?: boolean;
17
- /** legacy connection options */
18
- legacy?: {
19
- phoneConnected: boolean;
20
- user?: Contact;
21
- };
22
- /**
23
- * if the client is shown as an active, online client.
24
- * If this is false, the primary phone and other devices will receive notifs
25
- * */
26
- isOnline?: boolean;
27
- };
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,65 +0,0 @@
1
- export * from './Auth';
2
- export * from './GroupMetadata';
3
- export * from './Chat';
4
- export * from './Contact';
5
- export * from './State';
6
- export * from './Message';
7
- export * from './Newsletter';
8
- export * from './Socket';
9
- export * from './Events';
10
- export * from './Product';
11
- export * from './Call';
12
- export * from './Signal';
13
- import { AuthenticationState } from './Auth';
14
- import { SocketConfig } from './Socket';
15
- export type UserFacingSocketConfig = Partial<SocketConfig> & {
16
- auth: AuthenticationState;
17
- };
18
- /** Other Browser Support for Paircode */
19
- export type BrowsersMap = {
20
- ubuntu(browser: string): [string, string, string];
21
- macOS(browser: string): [string, string, string];
22
- baileys(browser: string): [string, string, string];
23
- windows(browser: string): [string, string, string];
24
- appropriate(browser: string): [string, string, string];
25
- };
26
- export declare enum DisconnectReason {
27
- connectionClosed = 428,
28
- connectionLost = 408,
29
- connectionReplaced = 440,
30
- timedOut = 408,
31
- loggedOut = 401,
32
- badSession = 500,
33
- restartRequired = 515,
34
- multideviceMismatch = 411,
35
- forbidden = 403,
36
- unavailableService = 503
37
- }
38
- export type WAInitResponse = {
39
- ref: string;
40
- ttl: number;
41
- status: 200;
42
- };
43
- export type WABusinessHoursConfig = {
44
- day_of_week: string;
45
- mode: string;
46
- open_time?: number;
47
- close_time?: number;
48
- };
49
- export type WABusinessProfile = {
50
- description: string;
51
- email: string | undefined;
52
- business_hours: {
53
- timezone?: string;
54
- config?: WABusinessHoursConfig[];
55
- business_config?: WABusinessHoursConfig[];
56
- };
57
- website: string[];
58
- category?: string;
59
- wid?: string;
60
- address?: string;
61
- };
62
- export type CurveKeyPair = {
63
- private: Uint8Array;
64
- public: Uint8Array;
65
- };
@@ -1,42 +0,0 @@
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;
31
- (function (DisconnectReason) {
32
- DisconnectReason[DisconnectReason["connectionClosed"] = 428] = "connectionClosed";
33
- DisconnectReason[DisconnectReason["connectionLost"] = 408] = "connectionLost";
34
- DisconnectReason[DisconnectReason["connectionReplaced"] = 440] = "connectionReplaced";
35
- DisconnectReason[DisconnectReason["timedOut"] = 408] = "timedOut";
36
- DisconnectReason[DisconnectReason["loggedOut"] = 401] = "loggedOut";
37
- DisconnectReason[DisconnectReason["badSession"] = 500] = "badSession";
38
- DisconnectReason[DisconnectReason["restartRequired"] = 515] = "restartRequired";
39
- DisconnectReason[DisconnectReason["multideviceMismatch"] = 411] = "multideviceMismatch";
40
- DisconnectReason[DisconnectReason["forbidden"] = 403] = "forbidden";
41
- DisconnectReason[DisconnectReason["unavailableService"] = 503] = "unavailableService";
42
- })(DisconnectReason = exports.DisconnectReason || (exports.DisconnectReason = {}));
@@ -1,18 +0,0 @@
1
- import type { Logger } from 'pino';
2
- import type { AuthenticationCreds, CacheStore, SignalKeyStore, SignalKeyStoreWithTransaction, TransactionCapabilityOptions } from '../Types';
3
- /**
4
- * Adds caching capability to a SignalKeyStore
5
- * @param store the store to add caching to
6
- * @param logger to log trace events
7
- * @param _cache cache store to use
8
- */
9
- export declare function makeCacheableSignalKeyStore(store: SignalKeyStore, logger: Logger, _cache?: CacheStore): SignalKeyStore;
10
- /**
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
- * @param state the key store to apply this capability to
14
- * @param logger logger to log events
15
- * @returns SignalKeyStore with transaction capability
16
- */
17
- export declare const addTransactionCapability: (state: SignalKeyStore, logger: Logger, { maxCommitRetries, delayBetweenTriesMs }: TransactionCapabilityOptions) => SignalKeyStoreWithTransaction;
18
- export declare const initAuthCreds: () => AuthenticationCreds;
@@ -1,200 +0,0 @@
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 Defaults_1 = require("../Defaults");
10
- const crypto_2 = require("./crypto");
11
- const generics_1 = require("./generics");
12
- /**
13
- * Adds caching capability to a SignalKeyStore
14
- * @param store the store to add caching to
15
- * @param logger to log trace events
16
- * @param _cache cache store to use
17
- */
18
- function makeCacheableSignalKeyStore(store, logger, _cache) {
19
- const cache = _cache || new node_cache_1.default({
20
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.SIGNAL_STORE,
21
- useClones: false,
22
- deleteOnExpire: true,
23
- });
24
- function getUniqueId(type, id) {
25
- return `${type}.${id}`;
26
- }
27
- return {
28
- async get(type, ids) {
29
- const data = {};
30
- const idsToFetch = [];
31
- for (const id of ids) {
32
- const item = cache.get(getUniqueId(type, id));
33
- if (typeof item !== 'undefined') {
34
- data[id] = item;
35
- }
36
- else {
37
- idsToFetch.push(id);
38
- }
39
- }
40
- if (idsToFetch.length) {
41
- logger.trace({ items: idsToFetch.length }, 'loading from store');
42
- const fetched = await store.get(type, idsToFetch);
43
- for (const id of idsToFetch) {
44
- const item = fetched[id];
45
- if (item) {
46
- data[id] = item;
47
- cache.set(getUniqueId(type, id), item);
48
- }
49
- }
50
- }
51
- return data;
52
- },
53
- async set(data) {
54
- let keys = 0;
55
- for (const type in data) {
56
- for (const id in data[type]) {
57
- cache.set(getUniqueId(type, id), data[type][id]);
58
- keys += 1;
59
- }
60
- }
61
- logger.trace({ keys }, 'updated cache');
62
- await store.set(data);
63
- },
64
- async clear() {
65
- var _a;
66
- cache.flushAll();
67
- await ((_a = store.clear) === null || _a === void 0 ? void 0 : _a.call(store));
68
- }
69
- };
70
- }
71
- exports.makeCacheableSignalKeyStore = makeCacheableSignalKeyStore;
72
- /**
73
- * Adds DB like transaction capability (https://en.wikipedia.org/wiki/Database_transaction) to the SignalKeyStore,
74
- * this allows batch read & write operations & improves the performance of the lib
75
- * @param state the key store to apply this capability to
76
- * @param logger logger to log events
77
- * @returns SignalKeyStore with transaction capability
78
- */
79
- const addTransactionCapability = (state, logger, { maxCommitRetries, delayBetweenTriesMs }) => {
80
- // number of queries made to the DB during the transaction
81
- // only there for logging purposes
82
- let dbQueriesInTransaction = 0;
83
- let transactionCache = {};
84
- let mutations = {};
85
- let transactionsInProgress = 0;
86
- return {
87
- get: async (type, ids) => {
88
- if (isInTransaction()) {
89
- const dict = transactionCache[type];
90
- const idsRequiringFetch = dict
91
- ? ids.filter(item => typeof dict[item] === 'undefined')
92
- : ids;
93
- // only fetch if there are any items to fetch
94
- if (idsRequiringFetch.length) {
95
- dbQueriesInTransaction += 1;
96
- const result = await state.get(type, idsRequiringFetch);
97
- transactionCache[type] || (transactionCache[type] = {});
98
- Object.assign(transactionCache[type], result);
99
- }
100
- return ids.reduce((dict, id) => {
101
- var _a;
102
- const value = (_a = transactionCache[type]) === null || _a === void 0 ? void 0 : _a[id];
103
- if (value) {
104
- dict[id] = value;
105
- }
106
- return dict;
107
- }, {});
108
- }
109
- else {
110
- return state.get(type, ids);
111
- }
112
- },
113
- set: data => {
114
- if (isInTransaction()) {
115
- logger.trace({ types: Object.keys(data) }, 'caching in transaction');
116
- for (const key in data) {
117
- transactionCache[key] = transactionCache[key] || {};
118
- Object.assign(transactionCache[key], data[key]);
119
- mutations[key] = mutations[key] || {};
120
- Object.assign(mutations[key], data[key]);
121
- }
122
- }
123
- else {
124
- return state.set(data);
125
- }
126
- },
127
- isInTransaction,
128
- async transaction(work) {
129
- let result;
130
- transactionsInProgress += 1;
131
- if (transactionsInProgress === 1) {
132
- logger.trace('entering transaction');
133
- }
134
- try {
135
- result = await work();
136
- // commit if this is the outermost transaction
137
- if (transactionsInProgress === 1) {
138
- if (Object.keys(mutations).length) {
139
- logger.trace('committing transaction');
140
- // retry mechanism to ensure we've some recovery
141
- // in case a transaction fails in the first attempt
142
- let tries = maxCommitRetries;
143
- while (tries) {
144
- tries -= 1;
145
- //eslint-disable-next-line max-depth
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
- }
160
- }
161
- }
162
- finally {
163
- transactionsInProgress -= 1;
164
- if (transactionsInProgress === 0) {
165
- transactionCache = {};
166
- mutations = {};
167
- dbQueriesInTransaction = 0;
168
- }
169
- }
170
- return result;
171
- }
172
- };
173
- function isInTransaction() {
174
- return transactionsInProgress > 0;
175
- }
176
- };
177
- exports.addTransactionCapability = addTransactionCapability;
178
- const initAuthCreds = () => {
179
- const identityKey = crypto_2.Curve.generateKeyPair();
180
- return {
181
- noiseKey: crypto_2.Curve.generateKeyPair(),
182
- pairingEphemeralKeyPair: crypto_2.Curve.generateKeyPair(),
183
- signedIdentityKey: identityKey,
184
- signedPreKey: (0, crypto_2.signedKeyPair)(identityKey, 1),
185
- registrationId: (0, generics_1.generateRegistrationId)(),
186
- advSecretKey: (0, crypto_1.randomBytes)(32).toString('base64'),
187
- processedHistoryMessages: [],
188
- nextPreKeyId: 1,
189
- firstUnuploadedPreKeyId: 1,
190
- accountSyncCounter: 0,
191
- accountSettings: {
192
- unarchiveChats: false
193
- },
194
- registered: false,
195
- pairingCode: undefined,
196
- lastPropHash: undefined,
197
- routingInfo: undefined,
198
- };
199
- };
200
- exports.initAuthCreds = initAuthCreds;
@@ -1,16 +0,0 @@
1
- import type { BaileysEventEmitter } from '../Types';
2
- /**
3
- * Captures events from a baileys event emitter & stores them in a file
4
- * @param ev The event emitter to read events from
5
- * @param filename File to save to
6
- */
7
- export declare const captureEventStream: (ev: BaileysEventEmitter, filename: string) => void;
8
- /**
9
- * Read event file and emit events from there
10
- * @param filename filename containing event data
11
- * @param delayIntervalMs delay between each event emit
12
- */
13
- export declare const readAndEmitEventStream: (filename: string, delayIntervalMs?: number) => {
14
- ev: BaileysEventEmitter;
15
- task: Promise<void>;
16
- };
@@ -1,63 +0,0 @@
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");
13
- /**
14
- * Captures events from a baileys event emitter & stores them in a file
15
- * @param ev The event emitter to read events from
16
- * @param filename File to save to
17
- */
18
- const captureEventStream = (ev, filename) => {
19
- const oldEmit = ev.emit;
20
- // write mutex so data is appended in order
21
- const writeMutex = (0, make_mutex_1.makeMutex)();
22
- // monkey patch eventemitter to capture all events
23
- ev.emit = function (...args) {
24
- const content = JSON.stringify({ timestamp: Date.now(), event: args[0], data: args[1] }) + '\n';
25
- const result = oldEmit.apply(ev, args);
26
- writeMutex.mutex(async () => {
27
- await (0, promises_1.writeFile)(filename, content, { flag: 'a' });
28
- });
29
- return result;
30
- };
31
- };
32
- exports.captureEventStream = captureEventStream;
33
- /**
34
- * Read event file and emit events from there
35
- * @param filename filename containing event data
36
- * @param delayIntervalMs delay between each event emit
37
- */
38
- const readAndEmitEventStream = (filename, delayIntervalMs = 0) => {
39
- const ev = new events_1.default();
40
- const fireEvents = async () => {
41
- // from: https://stackoverflow.com/questions/6156501/read-a-file-one-line-at-a-time-in-node-js
42
- const fileStream = (0, fs_1.createReadStream)(filename);
43
- const rl = (0, readline_1.createInterface)({
44
- input: fileStream,
45
- crlfDelay: Infinity
46
- });
47
- // Note: we use the crlfDelay option to recognize all instances of CR LF
48
- // ('\r\n') in input.txt as a single line break.
49
- for await (const line of rl) {
50
- if (line) {
51
- const { event, data } = JSON.parse(line);
52
- ev.emit(event, data);
53
- delayIntervalMs && await (0, generics_1.delay)(delayIntervalMs);
54
- }
55
- }
56
- fileStream.close();
57
- };
58
- return {
59
- ev,
60
- task: fireEvents()
61
- };
62
- };
63
- exports.readAndEmitEventStream = readAndEmitEventStream;
@@ -1,22 +0,0 @@
1
- import { CatalogCollection, OrderDetails, Product, ProductCreate, ProductUpdate, WAMediaUpload, WAMediaUploadFunction } from '../Types';
2
- import { BinaryNode } from '../WABinary';
3
- export declare const parseCatalogNode: (node: BinaryNode) => {
4
- products: Product[];
5
- nextPageCursor: string | undefined;
6
- };
7
- export declare const parseCollectionsNode: (node: BinaryNode) => {
8
- collections: CatalogCollection[];
9
- };
10
- export declare const parseOrderDetailsNode: (node: BinaryNode) => OrderDetails;
11
- export declare const toProductNode: (productId: string | undefined, product: ProductCreate | ProductUpdate) => BinaryNode;
12
- export declare const parseProductNode: (productNode: BinaryNode) => Product;
13
- /**
14
- * Uploads images not already uploaded to WA's servers
15
- */
16
- export declare function uploadingNecessaryImagesOfProduct<T extends ProductUpdate | ProductCreate>(product: T, waUploadToServer: WAMediaUploadFunction, timeoutMs?: number): Promise<T>;
17
- /**
18
- * Uploads images not already uploaded to WA's servers
19
- */
20
- export declare const uploadingNecessaryImages: (images: WAMediaUpload[], waUploadToServer: WAMediaUploadFunction, timeoutMs?: number) => Promise<{
21
- url: string;
22
- }[]>;