@vanzxy/baileys 1.4.0 → 1.4.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 (114) hide show
  1. package/cjs/WAProto/index.js +106053 -0
  2. package/cjs/lib/Defaults/index.js +168 -0
  3. package/cjs/lib/Signal/Group/ciphertext-message.js +16 -0
  4. package/cjs/lib/Signal/Group/group-session-builder.js +67 -0
  5. package/cjs/lib/Signal/Group/group_cipher.js +86 -0
  6. package/cjs/lib/Signal/Group/index.js +58 -0
  7. package/cjs/lib/Signal/Group/keyhelper.js +56 -0
  8. package/cjs/lib/Signal/Group/sender-chain-key.js +30 -0
  9. package/cjs/lib/Signal/Group/sender-key-distribution-message.js +67 -0
  10. package/cjs/lib/Signal/Group/sender-key-message.js +70 -0
  11. package/cjs/lib/Signal/Group/sender-key-name.js +52 -0
  12. package/cjs/lib/Signal/Group/sender-key-record.js +45 -0
  13. package/cjs/lib/Signal/Group/sender-key-state.js +88 -0
  14. package/cjs/lib/Signal/Group/sender-message-key.js +30 -0
  15. package/cjs/lib/Signal/libsignal.js +467 -0
  16. package/cjs/lib/Signal/lid-mapping.js +281 -0
  17. package/cjs/lib/Socket/Client/index.js +19 -0
  18. package/cjs/lib/Socket/Client/types.js +15 -0
  19. package/cjs/lib/Socket/Client/websocket.js +61 -0
  20. package/cjs/lib/Socket/business.js +384 -0
  21. package/cjs/lib/Socket/chats.js +1257 -0
  22. package/cjs/lib/Socket/communities.js +442 -0
  23. package/cjs/lib/Socket/dugong.js +753 -0
  24. package/cjs/lib/Socket/groups.js +360 -0
  25. package/cjs/lib/Socket/index.js +19 -0
  26. package/cjs/lib/Socket/messages-recv.js +1790 -0
  27. package/cjs/lib/Socket/messages-send.js +1390 -0
  28. package/cjs/lib/Socket/mex.js +46 -0
  29. package/cjs/lib/Socket/newsletter.js +340 -0
  30. package/cjs/lib/Socket/socket.js +1007 -0
  31. package/cjs/lib/Store/index.js +20 -0
  32. package/cjs/lib/Store/make-in-memory-store.js +438 -0
  33. package/cjs/lib/Store/make-ordered-dictionary.js +82 -0
  34. package/cjs/lib/Store/object-repository.js +28 -0
  35. package/cjs/lib/Types/Auth.js +3 -0
  36. package/cjs/lib/Types/Bussines.js +3 -0
  37. package/cjs/lib/Types/Call.js +3 -0
  38. package/cjs/lib/Types/Chat.js +11 -0
  39. package/cjs/lib/Types/Contact.js +3 -0
  40. package/cjs/lib/Types/Events.js +4 -0
  41. package/cjs/lib/Types/GroupMetadata.js +3 -0
  42. package/cjs/lib/Types/Label.js +26 -0
  43. package/cjs/lib/Types/LabelAssociation.js +8 -0
  44. package/cjs/lib/Types/Message.js +19 -0
  45. package/cjs/lib/Types/Mex.js +40 -0
  46. package/cjs/lib/Types/Product.js +3 -0
  47. package/cjs/lib/Types/RichType.js +24 -0
  48. package/cjs/lib/Types/Signal.js +4 -0
  49. package/cjs/lib/Types/Socket.js +4 -0
  50. package/cjs/lib/Types/State.js +54 -0
  51. package/cjs/lib/Types/USync.js +4 -0
  52. package/cjs/lib/Types/index.js +42 -0
  53. package/cjs/lib/Utils/MessageBuilder.js +2164 -0
  54. package/cjs/lib/Utils/auth-utils.js +312 -0
  55. package/cjs/lib/Utils/browser-utils.js +32 -0
  56. package/cjs/lib/Utils/business.js +245 -0
  57. package/cjs/lib/Utils/chat-utils.js +937 -0
  58. package/cjs/lib/Utils/companion-reg-client-utils.js +45 -0
  59. package/cjs/lib/Utils/crypto.js +196 -0
  60. package/cjs/lib/Utils/decode-wa-message.js +324 -0
  61. package/cjs/lib/Utils/event-buffer.js +643 -0
  62. package/cjs/lib/Utils/generics.js +429 -0
  63. package/cjs/lib/Utils/history.js +151 -0
  64. package/cjs/lib/Utils/identity-change-handler.js +56 -0
  65. package/cjs/lib/Utils/index.js +42 -0
  66. package/cjs/lib/Utils/link-preview.js +122 -0
  67. package/cjs/lib/Utils/logger.js +8 -0
  68. package/cjs/lib/Utils/lt-hash.js +62 -0
  69. package/cjs/lib/Utils/make-mutex.js +38 -0
  70. package/cjs/lib/Utils/message-retry-manager.js +267 -0
  71. package/cjs/lib/Utils/messages-media.js +933 -0
  72. package/cjs/lib/Utils/messages.js +2175 -0
  73. package/cjs/lib/Utils/noise-handler.js +205 -0
  74. package/cjs/lib/Utils/offline-node-processor.js +43 -0
  75. package/cjs/lib/Utils/pre-key-manager.js +113 -0
  76. package/cjs/lib/Utils/process-message.js +772 -0
  77. package/cjs/lib/Utils/reporting-utils.js +263 -0
  78. package/cjs/lib/Utils/rich-message-utils.js +439 -0
  79. package/cjs/lib/Utils/signal.js +214 -0
  80. package/cjs/lib/Utils/stanza-ack.js +41 -0
  81. package/cjs/lib/Utils/sync-action-utils.js +54 -0
  82. package/cjs/lib/Utils/tc-token-utils.js +174 -0
  83. package/cjs/lib/Utils/use-multi-file-auth-state.js +125 -0
  84. package/cjs/lib/Utils/use-single-file-auth-state.js +121 -0
  85. package/cjs/lib/Utils/use-sqlite-auth-state.js +182 -0
  86. package/cjs/lib/Utils/validate-connection.js +210 -0
  87. package/cjs/lib/WABinary/constants.js +1470 -0
  88. package/cjs/lib/WABinary/decode.js +301 -0
  89. package/cjs/lib/WABinary/encode.js +257 -0
  90. package/cjs/lib/WABinary/generic-utils.js +274 -0
  91. package/cjs/lib/WABinary/index.js +22 -0
  92. package/cjs/lib/WABinary/jid-utils.js +114 -0
  93. package/cjs/lib/WABinary/types.js +37 -0
  94. package/cjs/lib/WAM/BinaryInfo.js +14 -0
  95. package/cjs/lib/WAM/constants.js +22856 -0
  96. package/cjs/lib/WAM/encode.js +154 -0
  97. package/cjs/lib/WAM/index.js +20 -0
  98. package/cjs/lib/WAUSync/Protocols/USyncContactProtocol.js +56 -0
  99. package/cjs/lib/WAUSync/Protocols/USyncDeviceProtocol.js +67 -0
  100. package/cjs/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +31 -0
  101. package/cjs/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  102. package/cjs/lib/WAUSync/Protocols/USyncUsernameProtocol.js +29 -0
  103. package/cjs/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +55 -0
  104. package/cjs/lib/WAUSync/Protocols/UsyncLIDProtocol.js +33 -0
  105. package/cjs/lib/WAUSync/Protocols/index.js +24 -0
  106. package/cjs/lib/WAUSync/USyncQuery.js +126 -0
  107. package/cjs/lib/WAUSync/USyncUser.js +35 -0
  108. package/cjs/lib/WAUSync/index.js +20 -0
  109. package/cjs/lib/index.js +34 -0
  110. package/cjs/package.json +1 -0
  111. package/lib/Socket/messages-send.js +4 -3
  112. package/lib/Utils/messages.js +4 -1
  113. package/package.json +16 -5
  114. package/postinstall-banner.js +3 -2
@@ -0,0 +1,312 @@
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.assertMeId = exports.addTransactionCapability = void 0;
7
+ exports.makeCacheableSignalKeyStore = makeCacheableSignalKeyStore;
8
+ const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
9
+ const boom_1 = require("@hapi/boom");
10
+ const async_hooks_1 = require("async_hooks");
11
+ const async_mutex_1 = require("async-mutex");
12
+ const crypto_1 = require("crypto");
13
+ const p_queue_1 = __importDefault(require("p-queue"));
14
+ const index_js_1 = require("../Defaults/index.js");
15
+ const crypto_js_1 = require("./crypto.js");
16
+ const generics_js_1 = require("./generics.js");
17
+ const pre_key_manager_js_1 = require("./pre-key-manager.js");
18
+ /**
19
+ * Adds caching capability to a SignalKeyStore
20
+ * @param store the store to add caching to
21
+ * @param logger to log trace events
22
+ * @param _cache cache store to use
23
+ */
24
+ function makeCacheableSignalKeyStore(store, logger, _cache) {
25
+ const cache = _cache ||
26
+ new node_cache_1.default({
27
+ stdTTL: index_js_1.DEFAULT_CACHE_TTLS.SIGNAL_STORE, // 5 minutes
28
+ useClones: false,
29
+ deleteOnExpire: true
30
+ });
31
+ // Mutex for protecting cache operations
32
+ const cacheMutex = new async_mutex_1.Mutex();
33
+ function getUniqueId(type, id) {
34
+ return `${type}.${id}`;
35
+ }
36
+ return {
37
+ async get(type, ids) {
38
+ return cacheMutex.runExclusive(async () => {
39
+ const data = {};
40
+ const idsToFetch = [];
41
+ for (const id of ids) {
42
+ const item = (await cache.get(getUniqueId(type, id)));
43
+ if (typeof item !== 'undefined') {
44
+ data[id] = item;
45
+ }
46
+ else {
47
+ idsToFetch.push(id);
48
+ }
49
+ }
50
+ if (idsToFetch.length) {
51
+ logger?.trace({ items: idsToFetch.length }, 'loading from store');
52
+ const fetched = await store.get(type, idsToFetch);
53
+ for (const id of idsToFetch) {
54
+ const item = fetched[id];
55
+ if (item) {
56
+ data[id] = item;
57
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
58
+ await cache.set(getUniqueId(type, id), item);
59
+ }
60
+ }
61
+ }
62
+ return data;
63
+ });
64
+ },
65
+ async set(data) {
66
+ return cacheMutex.runExclusive(async () => {
67
+ let keys = 0;
68
+ for (const type in data) {
69
+ for (const id in data[type]) {
70
+ await cache.set(getUniqueId(type, id), data[type][id]);
71
+ keys += 1;
72
+ }
73
+ }
74
+ logger?.trace({ keys }, 'updated cache');
75
+ await store.set(data);
76
+ });
77
+ },
78
+ async clear() {
79
+ await cache.flushAll();
80
+ await store.clear?.();
81
+ }
82
+ };
83
+ }
84
+ /**
85
+ * Adds DB-like transaction capability to the SignalKeyStore
86
+ * Uses AsyncLocalStorage for automatic context management
87
+ * @param state the key store to apply this capability to
88
+ * @param logger logger to log events
89
+ * @returns SignalKeyStore with transaction capability
90
+ */
91
+ const addTransactionCapability = (state, logger, { maxCommitRetries, delayBetweenTriesMs }) => {
92
+ const txStorage = new async_hooks_1.AsyncLocalStorage();
93
+ // Queues for concurrency control (keyed by signal data type - bounded set)
94
+ const keyQueues = new Map();
95
+ // Transaction mutexes with reference counting for cleanup
96
+ const txMutexes = new Map();
97
+ const txMutexRefCounts = new Map();
98
+ // Pre-key manager for specialized operations
99
+ const preKeyManager = new pre_key_manager_js_1.PreKeyManager(state, logger);
100
+ /**
101
+ * Get or create a queue for a specific key type
102
+ */
103
+ function getQueue(key) {
104
+ if (!keyQueues.has(key)) {
105
+ keyQueues.set(key, new p_queue_1.default({ concurrency: 1 }));
106
+ }
107
+ return keyQueues.get(key);
108
+ }
109
+ /**
110
+ * Get or create a transaction mutex
111
+ */
112
+ function getTxMutex(key) {
113
+ if (!txMutexes.has(key)) {
114
+ txMutexes.set(key, new async_mutex_1.Mutex());
115
+ txMutexRefCounts.set(key, 0);
116
+ }
117
+ return txMutexes.get(key);
118
+ }
119
+ /**
120
+ * Acquire a reference to a transaction mutex
121
+ */
122
+ function acquireTxMutexRef(key) {
123
+ const count = txMutexRefCounts.get(key) ?? 0;
124
+ txMutexRefCounts.set(key, count + 1);
125
+ }
126
+ /**
127
+ * Release a reference to a transaction mutex and cleanup if no longer needed
128
+ */
129
+ function releaseTxMutexRef(key) {
130
+ const count = (txMutexRefCounts.get(key) ?? 1) - 1;
131
+ txMutexRefCounts.set(key, count);
132
+ // Cleanup if no more references and mutex is not locked
133
+ if (count <= 0) {
134
+ const mutex = txMutexes.get(key);
135
+ if (mutex && !mutex.isLocked()) {
136
+ txMutexes.delete(key);
137
+ txMutexRefCounts.delete(key);
138
+ }
139
+ }
140
+ }
141
+ /**
142
+ * Check if currently in a transaction
143
+ */
144
+ function isInTransaction() {
145
+ return !!txStorage.getStore();
146
+ }
147
+ /**
148
+ * Commit transaction with retries
149
+ */
150
+ async function commitWithRetry(mutations) {
151
+ if (Object.keys(mutations).length === 0) {
152
+ logger.trace('no mutations in transaction');
153
+ return;
154
+ }
155
+ logger.trace('committing transaction');
156
+ for (let attempt = 0; attempt < maxCommitRetries; attempt++) {
157
+ try {
158
+ await state.set(mutations);
159
+ logger.trace({ mutationCount: Object.keys(mutations).length }, 'committed transaction');
160
+ return;
161
+ }
162
+ catch (error) {
163
+ const retriesLeft = maxCommitRetries - attempt - 1;
164
+ logger.warn(`failed to commit mutations, retries left=${retriesLeft}`);
165
+ if (retriesLeft === 0) {
166
+ throw error;
167
+ }
168
+ await (0, generics_js_1.delay)(delayBetweenTriesMs);
169
+ }
170
+ }
171
+ }
172
+ return {
173
+ get: async (type, ids) => {
174
+ const ctx = txStorage.getStore();
175
+ if (!ctx) {
176
+ // No transaction - direct read without exclusive lock for concurrency
177
+ return state.get(type, ids);
178
+ }
179
+ // In transaction - check cache first
180
+ const cached = ctx.cache[type] || {};
181
+ const missing = ids.filter(id => !(id in cached));
182
+ if (missing.length > 0) {
183
+ ctx.dbQueries++;
184
+ logger.trace({ type, count: missing.length }, 'fetching missing keys in transaction');
185
+ const fetched = await getTxMutex(type).runExclusive(() => state.get(type, missing));
186
+ // Update cache
187
+ ctx.cache[type] = ctx.cache[type] || {};
188
+ Object.assign(ctx.cache[type], fetched);
189
+ }
190
+ // Return requested ids from cache
191
+ const result = {};
192
+ for (const id of ids) {
193
+ const value = ctx.cache[type]?.[id];
194
+ if (value !== undefined && value !== null) {
195
+ result[id] = value;
196
+ }
197
+ }
198
+ return result;
199
+ },
200
+ set: async (data) => {
201
+ const ctx = txStorage.getStore();
202
+ if (!ctx) {
203
+ // No transaction - direct write with queue protection
204
+ const types = Object.keys(data);
205
+ // Process pre-keys with validation
206
+ for (const type_ of types) {
207
+ const type = type_;
208
+ if (type === 'pre-key') {
209
+ await preKeyManager.validateDeletions(data, type);
210
+ }
211
+ }
212
+ // Write all data in parallel
213
+ await Promise.all(types.map(type => getQueue(type).add(async () => {
214
+ const typeData = { [type]: data[type] };
215
+ await state.set(typeData);
216
+ })));
217
+ return;
218
+ }
219
+ // In transaction - update cache and mutations
220
+ logger.trace({ types: Object.keys(data) }, 'caching in transaction');
221
+ for (const key_ in data) {
222
+ const key = key_;
223
+ // Ensure structures exist
224
+ ctx.cache[key] = ctx.cache[key] || {};
225
+ ctx.mutations[key] = ctx.mutations[key] || {};
226
+ // Special handling for pre-keys
227
+ if (key === 'pre-key') {
228
+ await preKeyManager.processOperations(data, key, ctx.cache, ctx.mutations, true);
229
+ }
230
+ else {
231
+ // Normal key types
232
+ Object.assign(ctx.cache[key], data[key]);
233
+ Object.assign(ctx.mutations[key], data[key]);
234
+ }
235
+ }
236
+ },
237
+ isInTransaction,
238
+ transaction: async (work, key) => {
239
+ const existing = txStorage.getStore();
240
+ // Nested transaction - reuse existing context
241
+ if (existing) {
242
+ logger.trace('reusing existing transaction context');
243
+ return work();
244
+ }
245
+ // New transaction - acquire mutex and create context
246
+ const mutex = getTxMutex(key);
247
+ acquireTxMutexRef(key);
248
+ try {
249
+ return await mutex.runExclusive(async () => {
250
+ const ctx = {
251
+ cache: {},
252
+ mutations: {},
253
+ dbQueries: 0
254
+ };
255
+ logger.trace('entering transaction');
256
+ try {
257
+ const result = await txStorage.run(ctx, work);
258
+ // Commit mutations
259
+ await commitWithRetry(ctx.mutations);
260
+ logger.trace({ dbQueries: ctx.dbQueries }, 'transaction completed');
261
+ return result;
262
+ }
263
+ catch (error) {
264
+ logger.error({ error }, 'transaction failed, rolling back');
265
+ throw error;
266
+ }
267
+ });
268
+ }
269
+ finally {
270
+ releaseTxMutexRef(key);
271
+ }
272
+ }
273
+ };
274
+ };
275
+ exports.addTransactionCapability = addTransactionCapability;
276
+ /**
277
+ * Returns the authenticated user's JID, or throws a Boom-401 if creds are not yet authenticated.
278
+ * Use this anywhere we'd otherwise reach for `creds.me!.id` to fail fast with a descriptive error.
279
+ */
280
+ const assertMeId = (creds) => {
281
+ const id = creds.me?.id;
282
+ if (!id) {
283
+ throw new boom_1.Boom('Cannot proceed: socket is not authenticated yet (creds.me.id is missing)', { statusCode: 401 });
284
+ }
285
+ return id;
286
+ };
287
+ exports.assertMeId = assertMeId;
288
+ const initAuthCreds = () => {
289
+ const identityKey = crypto_js_1.Curve.generateKeyPair();
290
+ return {
291
+ noiseKey: crypto_js_1.Curve.generateKeyPair(),
292
+ pairingEphemeralKeyPair: crypto_js_1.Curve.generateKeyPair(),
293
+ signedIdentityKey: identityKey,
294
+ signedPreKey: (0, crypto_js_1.signedKeyPair)(identityKey, 1),
295
+ registrationId: (0, generics_js_1.generateRegistrationId)(),
296
+ advSecretKey: (0, crypto_1.randomBytes)(32).toString('base64'),
297
+ processedHistoryMessages: [],
298
+ nextPreKeyId: 1,
299
+ firstUnuploadedPreKeyId: 1,
300
+ accountSyncCounter: 0,
301
+ accountSettings: {
302
+ unarchiveChats: false
303
+ },
304
+ registered: false,
305
+ pairingCode: undefined,
306
+ lastPropHash: undefined,
307
+ routingInfo: undefined,
308
+ additionalData: undefined
309
+ };
310
+ };
311
+ exports.initAuthCreds = initAuthCreds;
312
+ //# sourceMappingURL=auth-utils.js.map
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getPlatformId = exports.Browsers = void 0;
4
+ const os_1 = require("os");
5
+ const index_js_1 = require("../../WAProto/index.js");
6
+ const PLATFORM_MAP = {
7
+ aix: 'AIX',
8
+ darwin: 'Mac OS',
9
+ win32: 'Windows',
10
+ android: 'Android',
11
+ freebsd: 'FreeBSD',
12
+ openbsd: 'OpenBSD',
13
+ sunos: 'Solaris',
14
+ linux: undefined,
15
+ haiku: undefined,
16
+ cygwin: undefined,
17
+ netbsd: undefined
18
+ };
19
+ exports.Browsers = {
20
+ ubuntu: browser => ['Ubuntu', browser, '22.04.4'],
21
+ macOS: browser => ['Mac OS', browser, '14.4.1'],
22
+ baileys: browser => ['Baileys', browser, '6.5.0'],
23
+ windows: browser => ['Windows', browser, '10.0.22631'],
24
+ /** The appropriate browser based on your OS & release */
25
+ appropriate: browser => [PLATFORM_MAP[(0, os_1.platform)()] || 'Ubuntu', browser, (0, os_1.release)()]
26
+ };
27
+ const getPlatformId = (browser) => {
28
+ const platformType = index_js_1.proto.DeviceProps.PlatformType[browser.toUpperCase()];
29
+ return platformType ? platformType.toString() : '1'; //chrome
30
+ };
31
+ exports.getPlatformId = getPlatformId;
32
+ //# sourceMappingURL=browser-utils.js.map
@@ -0,0 +1,245 @@
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.uploadingNecessaryImages = exports.parseProductNode = exports.toProductNode = exports.parseOrderDetailsNode = exports.parseCollectionsNode = exports.parseCatalogNode = void 0;
7
+ exports.uploadingNecessaryImagesOfProduct = uploadingNecessaryImagesOfProduct;
8
+ const boom_1 = require("@hapi/boom");
9
+ const crypto_1 = require("crypto");
10
+ const fs_1 = require("fs");
11
+ const os_1 = require("os");
12
+ const path_1 = require("path");
13
+ const index_js_1 = require("../WABinary/index.js");
14
+ const generics_js_1 = require("./generics.js");
15
+ const logger_js_1 = __importDefault(require("./logger.js"));
16
+ const messages_media_js_1 = require("./messages-media.js");
17
+ const parseCatalogNode = (node) => {
18
+ const catalogNode = (0, index_js_1.getBinaryNodeChild)(node, 'product_catalog');
19
+ const products = (0, index_js_1.getBinaryNodeChildren)(catalogNode, 'product').map(exports.parseProductNode);
20
+ const paging = (0, index_js_1.getBinaryNodeChild)(catalogNode, 'paging');
21
+ return {
22
+ products,
23
+ nextPageCursor: paging ? (0, index_js_1.getBinaryNodeChildString)(paging, 'after') : undefined
24
+ };
25
+ };
26
+ exports.parseCatalogNode = parseCatalogNode;
27
+ const parseCollectionsNode = (node) => {
28
+ const collectionsNode = (0, index_js_1.getBinaryNodeChild)(node, 'collections');
29
+ const collections = (0, index_js_1.getBinaryNodeChildren)(collectionsNode, 'collection').map(collectionNode => {
30
+ const id = (0, index_js_1.getBinaryNodeChildString)(collectionNode, 'id');
31
+ const name = (0, index_js_1.getBinaryNodeChildString)(collectionNode, 'name');
32
+ const products = (0, index_js_1.getBinaryNodeChildren)(collectionNode, 'product').map(exports.parseProductNode);
33
+ return {
34
+ id,
35
+ name,
36
+ products,
37
+ status: parseStatusInfo(collectionNode)
38
+ };
39
+ });
40
+ return {
41
+ collections
42
+ };
43
+ };
44
+ exports.parseCollectionsNode = parseCollectionsNode;
45
+ const parseOrderDetailsNode = (node) => {
46
+ const orderNode = (0, index_js_1.getBinaryNodeChild)(node, 'order');
47
+ const products = (0, index_js_1.getBinaryNodeChildren)(orderNode, 'product').map(productNode => {
48
+ const imageNode = (0, index_js_1.getBinaryNodeChild)(productNode, 'image');
49
+ return {
50
+ id: (0, index_js_1.getBinaryNodeChildString)(productNode, 'id'),
51
+ name: (0, index_js_1.getBinaryNodeChildString)(productNode, 'name'),
52
+ imageUrl: (0, index_js_1.getBinaryNodeChildString)(imageNode, 'url'),
53
+ price: +(0, index_js_1.getBinaryNodeChildString)(productNode, 'price'),
54
+ currency: (0, index_js_1.getBinaryNodeChildString)(productNode, 'currency'),
55
+ quantity: +(0, index_js_1.getBinaryNodeChildString)(productNode, 'quantity')
56
+ };
57
+ });
58
+ const priceNode = (0, index_js_1.getBinaryNodeChild)(orderNode, 'price');
59
+ const orderDetails = {
60
+ price: {
61
+ total: +(0, index_js_1.getBinaryNodeChildString)(priceNode, 'total'),
62
+ currency: (0, index_js_1.getBinaryNodeChildString)(priceNode, 'currency')
63
+ },
64
+ products
65
+ };
66
+ return orderDetails;
67
+ };
68
+ exports.parseOrderDetailsNode = parseOrderDetailsNode;
69
+ const toProductNode = (productId, product) => {
70
+ const attrs = {};
71
+ const content = [];
72
+ if (typeof productId !== 'undefined') {
73
+ content.push({
74
+ tag: 'id',
75
+ attrs: {},
76
+ content: Buffer.from(productId)
77
+ });
78
+ }
79
+ if (typeof product.name !== 'undefined') {
80
+ content.push({
81
+ tag: 'name',
82
+ attrs: {},
83
+ content: Buffer.from(product.name)
84
+ });
85
+ }
86
+ if (typeof product.description !== 'undefined') {
87
+ content.push({
88
+ tag: 'description',
89
+ attrs: {},
90
+ content: Buffer.from(product.description)
91
+ });
92
+ }
93
+ if (typeof product.retailerId !== 'undefined') {
94
+ content.push({
95
+ tag: 'retailer_id',
96
+ attrs: {},
97
+ content: Buffer.from(product.retailerId)
98
+ });
99
+ }
100
+ if (product.images.length) {
101
+ content.push({
102
+ tag: 'media',
103
+ attrs: {},
104
+ content: product.images.map(img => {
105
+ if (!('url' in img)) {
106
+ throw new boom_1.Boom('Expected img for product to already be uploaded', { statusCode: 400 });
107
+ }
108
+ return {
109
+ tag: 'image',
110
+ attrs: {},
111
+ content: [
112
+ {
113
+ tag: 'url',
114
+ attrs: {},
115
+ content: Buffer.from(img.url.toString())
116
+ }
117
+ ]
118
+ };
119
+ })
120
+ });
121
+ }
122
+ if (typeof product.price !== 'undefined') {
123
+ content.push({
124
+ tag: 'price',
125
+ attrs: {},
126
+ content: Buffer.from(product.price.toString())
127
+ });
128
+ }
129
+ if (typeof product.currency !== 'undefined') {
130
+ content.push({
131
+ tag: 'currency',
132
+ attrs: {},
133
+ content: Buffer.from(product.currency)
134
+ });
135
+ }
136
+ if ('originCountryCode' in product) {
137
+ if (typeof product.originCountryCode === 'undefined') {
138
+ attrs['compliance_category'] = 'COUNTRY_ORIGIN_EXEMPT';
139
+ }
140
+ else {
141
+ content.push({
142
+ tag: 'compliance_info',
143
+ attrs: {},
144
+ content: [
145
+ {
146
+ tag: 'country_code_origin',
147
+ attrs: {},
148
+ content: Buffer.from(product.originCountryCode)
149
+ }
150
+ ]
151
+ });
152
+ }
153
+ }
154
+ if (typeof product.isHidden !== 'undefined') {
155
+ attrs['is_hidden'] = product.isHidden.toString();
156
+ }
157
+ const node = {
158
+ tag: 'product',
159
+ attrs,
160
+ content
161
+ };
162
+ return node;
163
+ };
164
+ exports.toProductNode = toProductNode;
165
+ const parseProductNode = (productNode) => {
166
+ const isHidden = productNode.attrs.is_hidden === 'true';
167
+ const id = (0, index_js_1.getBinaryNodeChildString)(productNode, 'id');
168
+ const mediaNode = (0, index_js_1.getBinaryNodeChild)(productNode, 'media');
169
+ const statusInfoNode = (0, index_js_1.getBinaryNodeChild)(productNode, 'status_info');
170
+ const product = {
171
+ id,
172
+ imageUrls: parseImageUrls(mediaNode),
173
+ reviewStatus: {
174
+ whatsapp: (0, index_js_1.getBinaryNodeChildString)(statusInfoNode, 'status')
175
+ },
176
+ availability: 'in stock',
177
+ name: (0, index_js_1.getBinaryNodeChildString)(productNode, 'name'),
178
+ retailerId: (0, index_js_1.getBinaryNodeChildString)(productNode, 'retailer_id'),
179
+ url: (0, index_js_1.getBinaryNodeChildString)(productNode, 'url'),
180
+ description: (0, index_js_1.getBinaryNodeChildString)(productNode, 'description'),
181
+ price: +(0, index_js_1.getBinaryNodeChildString)(productNode, 'price'),
182
+ currency: (0, index_js_1.getBinaryNodeChildString)(productNode, 'currency'),
183
+ isHidden
184
+ };
185
+ return product;
186
+ };
187
+ exports.parseProductNode = parseProductNode;
188
+ /**
189
+ * Uploads images not already uploaded to WA's servers
190
+ */
191
+ async function uploadingNecessaryImagesOfProduct(product, waUploadToServer, timeoutMs = 30000) {
192
+ product = {
193
+ ...product,
194
+ images: product.images
195
+ ? await (0, exports.uploadingNecessaryImages)(product.images, waUploadToServer, timeoutMs)
196
+ : product.images
197
+ };
198
+ return product;
199
+ }
200
+ /**
201
+ * Uploads images not already uploaded to WA's servers
202
+ */
203
+ const uploadingNecessaryImages = async (images, waUploadToServer, timeoutMs = 30000) => {
204
+ const results = await Promise.all(images.map(async (img) => {
205
+ if ('url' in img) {
206
+ const url = img.url.toString();
207
+ if (url.includes('.whatsapp.net')) {
208
+ return { url };
209
+ }
210
+ }
211
+ const { stream } = await (0, messages_media_js_1.getStream)(img);
212
+ const hasher = (0, crypto_1.createHash)('sha256');
213
+ const filePath = (0, path_1.join)((0, os_1.tmpdir)(), 'img' + (0, generics_js_1.generateMessageIDV2)());
214
+ const encFileWriteStream = (0, fs_1.createWriteStream)(filePath);
215
+ for await (const block of stream) {
216
+ hasher.update(block);
217
+ encFileWriteStream.write(block);
218
+ }
219
+ const sha = hasher.digest('base64');
220
+ const { directPath } = await waUploadToServer(filePath, {
221
+ mediaType: 'product-catalog-image',
222
+ fileEncSha256B64: sha,
223
+ timeoutMs
224
+ });
225
+ await fs_1.promises.unlink(filePath).catch(err => logger_js_1.default.warn({ err, filePath }, 'Vanz@Fix (bug 57): error deleting temp file')); // was console.log
226
+ return { url: (0, messages_media_js_1.getUrlFromDirectPath)(directPath) };
227
+ }));
228
+ return results;
229
+ };
230
+ exports.uploadingNecessaryImages = uploadingNecessaryImages;
231
+ const parseImageUrls = (mediaNode) => {
232
+ const imgNode = (0, index_js_1.getBinaryNodeChild)(mediaNode, 'image');
233
+ return {
234
+ requested: (0, index_js_1.getBinaryNodeChildString)(imgNode, 'request_image_url'),
235
+ original: (0, index_js_1.getBinaryNodeChildString)(imgNode, 'original_image_url')
236
+ };
237
+ };
238
+ const parseStatusInfo = (mediaNode) => {
239
+ const node = (0, index_js_1.getBinaryNodeChild)(mediaNode, 'status_info');
240
+ return {
241
+ status: (0, index_js_1.getBinaryNodeChildString)(node, 'status'),
242
+ canAppeal: (0, index_js_1.getBinaryNodeChildString)(node, 'can_appeal') === 'true'
243
+ };
244
+ };
245
+ //# sourceMappingURL=business.js.map