@bellaxchuu/flowred 0.8.6

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 (142) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +214 -0
  3. package/WAProto/GenerateStatics.sh +3 -0
  4. package/WAProto/WAProto.proto +6902 -0
  5. package/WAProto/fix-imports.js +85 -0
  6. package/WAProto/index.js +242946 -0
  7. package/engine-requirements.js +10 -0
  8. package/lib/Defaults/index.js +190 -0
  9. package/lib/Defaults/phonenumber-mcc.json +223 -0
  10. package/lib/Signal/Group/ciphertext-message.js +15 -0
  11. package/lib/Signal/Group/group-session-builder.js +92 -0
  12. package/lib/Signal/Group/group_cipher.js +89 -0
  13. package/lib/Signal/Group/index.js +136 -0
  14. package/lib/Signal/Group/keyhelper.js +73 -0
  15. package/lib/Signal/Group/sender-chain-key.js +32 -0
  16. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  17. package/lib/Signal/Group/sender-key-message.js +69 -0
  18. package/lib/Signal/Group/sender-key-name.js +50 -0
  19. package/lib/Signal/Group/sender-key-record.js +44 -0
  20. package/lib/Signal/Group/sender-key-state.js +97 -0
  21. package/lib/Signal/Group/sender-message-key.js +30 -0
  22. package/lib/Signal/libsignal.js +490 -0
  23. package/lib/Signal/lid-mapping.js +262 -0
  24. package/lib/Socket/Client/index.js +30 -0
  25. package/lib/Socket/Client/types.js +13 -0
  26. package/lib/Socket/Client/websocket.js +62 -0
  27. package/lib/Socket/aigroups.js +240 -0
  28. package/lib/Socket/business.js +422 -0
  29. package/lib/Socket/chats.js +1816 -0
  30. package/lib/Socket/communities.js +549 -0
  31. package/lib/Socket/graphql.js +656 -0
  32. package/lib/Socket/groups.js +764 -0
  33. package/lib/Socket/index.js +39 -0
  34. package/lib/Socket/interactive-handler.js +522 -0
  35. package/lib/Socket/interop.js +549 -0
  36. package/lib/Socket/luxu.js +387 -0
  37. package/lib/Socket/managed-account.js +183 -0
  38. package/lib/Socket/messages-recv.js +2440 -0
  39. package/lib/Socket/messages-send.js +1853 -0
  40. package/lib/Socket/mex.js +60 -0
  41. package/lib/Socket/newsletter.js +820 -0
  42. package/lib/Socket/privacy.js +449 -0
  43. package/lib/Socket/registration.js +427 -0
  44. package/lib/Socket/socket.js +1092 -0
  45. package/lib/Socket/text-router.js +83 -0
  46. package/lib/Socket/username.js +243 -0
  47. package/lib/Store/index.js +36 -0
  48. package/lib/Store/keyed-db.js +108 -0
  49. package/lib/Store/make-cache-manager-store.js +90 -0
  50. package/lib/Store/make-in-memory-store.js +604 -0
  51. package/lib/Store/make-ordered-dictionary.js +81 -0
  52. package/lib/Store/object-repository.js +29 -0
  53. package/lib/Types/Auth.js +38 -0
  54. package/lib/Types/Bussines.js +2 -0
  55. package/lib/Types/Call.js +2 -0
  56. package/lib/Types/Chat.js +4 -0
  57. package/lib/Types/Contact.js +2 -0
  58. package/lib/Types/Events.js +2 -0
  59. package/lib/Types/GroupMetadata.js +2 -0
  60. package/lib/Types/Label.js +27 -0
  61. package/lib/Types/LabelAssociation.js +9 -0
  62. package/lib/Types/Message.js +95 -0
  63. package/lib/Types/Mex.js +112 -0
  64. package/lib/Types/Newsletter.js +121 -0
  65. package/lib/Types/Product.js +2 -0
  66. package/lib/Types/Signal.js +2 -0
  67. package/lib/Types/Socket.js +2 -0
  68. package/lib/Types/State.js +70 -0
  69. package/lib/Types/USync.js +2 -0
  70. package/lib/Types/index.js +55 -0
  71. package/lib/Utils/auth-utils.js +306 -0
  72. package/lib/Utils/browser-utils.js +114 -0
  73. package/lib/Utils/business.js +247 -0
  74. package/lib/Utils/chat-utils.js +1208 -0
  75. package/lib/Utils/command-loader.js +100 -0
  76. package/lib/Utils/companion-reg-client-utils.js +42 -0
  77. package/lib/Utils/consumer-application.js +107 -0
  78. package/lib/Utils/crypto.js +155 -0
  79. package/lib/Utils/curve25519-js.js +275 -0
  80. package/lib/Utils/decode-wa-message.js +560 -0
  81. package/lib/Utils/event-buffer.js +607 -0
  82. package/lib/Utils/generics.js +563 -0
  83. package/lib/Utils/group-history.js +60 -0
  84. package/lib/Utils/history.js +244 -0
  85. package/lib/Utils/identity-change-handler.js +52 -0
  86. package/lib/Utils/index.js +57 -0
  87. package/lib/Utils/jid-display-normalization.js +218 -0
  88. package/lib/Utils/link-preview.js +143 -0
  89. package/lib/Utils/logger.js +9 -0
  90. package/lib/Utils/lt-hash.js +39 -0
  91. package/lib/Utils/make-mutex.js +36 -0
  92. package/lib/Utils/message-composer.js +479 -0
  93. package/lib/Utils/message-retry-manager.js +270 -0
  94. package/lib/Utils/messages-media.js +896 -0
  95. package/lib/Utils/messages.js +2904 -0
  96. package/lib/Utils/meta-ai-msmsg.js +262 -0
  97. package/lib/Utils/native-bridge.js +82 -0
  98. package/lib/Utils/noise-handler.js +196 -0
  99. package/lib/Utils/offline-node-processor.js +42 -0
  100. package/lib/Utils/pre-key-manager.js +107 -0
  101. package/lib/Utils/process-message.js +1048 -0
  102. package/lib/Utils/reporting-utils.js +262 -0
  103. package/lib/Utils/session-pool.js +94 -0
  104. package/lib/Utils/signal.js +224 -0
  105. package/lib/Utils/stanza-ack.js +40 -0
  106. package/lib/Utils/sticker.js +145 -0
  107. package/lib/Utils/sync-action-utils.js +54 -0
  108. package/lib/Utils/tc-token-utils.js +161 -0
  109. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  110. package/lib/Utils/validate-connection.js +219 -0
  111. package/lib/Utils/view-once-cache.js +79 -0
  112. package/lib/Utils/voip-rekey.js +22 -0
  113. package/lib/WABinary/constants.js +1304 -0
  114. package/lib/WABinary/decode.js +343 -0
  115. package/lib/WABinary/encode.js +228 -0
  116. package/lib/WABinary/generic-utils.js +240 -0
  117. package/lib/WABinary/index.js +33 -0
  118. package/lib/WABinary/jid-utils.js +361 -0
  119. package/lib/WABinary/types.js +2 -0
  120. package/lib/WAM/BinaryInfo.js +13 -0
  121. package/lib/WAM/constants.js +39486 -0
  122. package/lib/WAM/encode.js +142 -0
  123. package/lib/WAM/index.js +31 -0
  124. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +55 -0
  125. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +43 -0
  126. package/lib/WAUSync/Protocols/USyncContactProtocol.js +54 -0
  127. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  128. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  129. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +59 -0
  130. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +31 -0
  131. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +32 -0
  132. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +29 -0
  133. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +39 -0
  134. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
  135. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +27 -0
  136. package/lib/WAUSync/Protocols/index.js +39 -0
  137. package/lib/WAUSync/USyncQuery.js +133 -0
  138. package/lib/WAUSync/USyncUser.js +50 -0
  139. package/lib/WAUSync/index.js +31 -0
  140. package/lib/antiban.js +4637 -0
  141. package/lib/index.js +45 -0
  142. package/package.json +107 -0
@@ -0,0 +1,306 @@
1
+ 'use strict'
2
+ var __importDefault =
3
+ (this && this.__importDefault) ||
4
+ function (mod) {
5
+ return mod && mod.__esModule ? mod : { default: mod }
6
+ }
7
+ Object.defineProperty(exports, '__esModule', { value: true })
8
+ exports.initAuthCreds = exports.addTransactionCapability = void 0
9
+ exports.makeCacheableSignalKeyStore = makeCacheableSignalKeyStore
10
+ const node_cache_1 = __importDefault(require('@cacheable/node-cache'))
11
+ const async_hooks_1 = require('async_hooks')
12
+ const async_mutex_1 = require('async-mutex')
13
+ const crypto_1 = require('crypto')
14
+ const p_queue_1 = __importDefault(require('p-queue'))
15
+ const Defaults_1 = require('../Defaults')
16
+ const crypto_2 = require('./crypto')
17
+ const generics_1 = require('./generics')
18
+ const pre_key_manager_1 = require('./pre-key-manager')
19
+ /**
20
+ * Adds caching capability to a SignalKeyStore
21
+ * @param store the store to add caching to
22
+ * @param logger to log trace events
23
+ * @param _cache cache store to use
24
+ */
25
+ function makeCacheableSignalKeyStore(store, logger, _cache) {
26
+ const cache =
27
+ _cache ||
28
+ new node_cache_1.default({
29
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.SIGNAL_STORE, // 5 minutes
30
+ useClones: false,
31
+ deleteOnExpire: true
32
+ })
33
+ // Mutex for protecting cache operations
34
+ const cacheMutex = new async_mutex_1.Mutex()
35
+ function getUniqueId(type, id) {
36
+ return `${type}.${id}`
37
+ }
38
+ return {
39
+ async get(type, ids) {
40
+ return cacheMutex.runExclusive(async () => {
41
+ const data = {}
42
+ const idsToFetch = []
43
+ for (const id of ids) {
44
+ const item = await cache.get(getUniqueId(type, id))
45
+ if (typeof item !== 'undefined') {
46
+ data[id] = item
47
+ } else {
48
+ idsToFetch.push(id)
49
+ }
50
+ }
51
+ if (idsToFetch.length) {
52
+ logger?.trace({ items: idsToFetch.length }, 'loading from store')
53
+ const fetched = await store.get(type, idsToFetch)
54
+ for (const id of idsToFetch) {
55
+ const item = fetched[id]
56
+ if (item) {
57
+ data[id] = item
58
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
59
+ await cache.set(getUniqueId(type, id), item)
60
+ }
61
+ }
62
+ }
63
+ return data
64
+ })
65
+ },
66
+ async set(data) {
67
+ return cacheMutex.runExclusive(async () => {
68
+ let keys = 0
69
+ for (const type in data) {
70
+ for (const id in data[type]) {
71
+ await cache.set(getUniqueId(type, id), data[type][id])
72
+ keys += 1
73
+ }
74
+ }
75
+ logger?.trace({ keys }, 'updated cache')
76
+ await store.set(data)
77
+ })
78
+ },
79
+ async clear() {
80
+ await cache.flushAll()
81
+ await store.clear?.()
82
+ }
83
+ }
84
+ }
85
+ /**
86
+ * Adds DB-like transaction capability to the SignalKeyStore
87
+ * Uses AsyncLocalStorage for automatic context management
88
+ * @param state the key store to apply this capability to
89
+ * @param logger logger to log events
90
+ * @returns SignalKeyStore with transaction capability
91
+ */
92
+ const addTransactionCapability = (state, logger, { maxCommitRetries, delayBetweenTriesMs }) => {
93
+ const txStorage = new async_hooks_1.AsyncLocalStorage()
94
+ // Queues for concurrency control (keyed by signal data type - bounded set)
95
+ const keyQueues = new Map()
96
+ // Transaction mutexes with reference counting for cleanup
97
+ const txMutexes = new Map()
98
+ const txMutexRefCounts = new Map()
99
+ // Pre-key manager for specialized operations
100
+ const preKeyManager = new pre_key_manager_1.PreKeyManager(state, logger)
101
+ /**
102
+ * Get or create a queue for a specific key type
103
+ */
104
+ function getQueue(key) {
105
+ if (!keyQueues.has(key)) {
106
+ keyQueues.set(key, new p_queue_1.default({ concurrency: 1 }))
107
+ }
108
+ return keyQueues.get(key)
109
+ }
110
+ /**
111
+ * Get or create a transaction mutex
112
+ */
113
+ function getTxMutex(key) {
114
+ if (!txMutexes.has(key)) {
115
+ txMutexes.set(key, new async_mutex_1.Mutex())
116
+ txMutexRefCounts.set(key, 0)
117
+ }
118
+ return txMutexes.get(key)
119
+ }
120
+ /**
121
+ * Acquire a reference to a transaction mutex
122
+ */
123
+ function acquireTxMutexRef(key) {
124
+ const count = txMutexRefCounts.get(key) ?? 0
125
+ txMutexRefCounts.set(key, count + 1)
126
+ }
127
+ /**
128
+ * Release a reference to a transaction mutex and cleanup if no longer needed
129
+ */
130
+ function releaseTxMutexRef(key) {
131
+ const count = (txMutexRefCounts.get(key) ?? 1) - 1
132
+ txMutexRefCounts.set(key, count)
133
+ // Cleanup if no more references and mutex is not locked
134
+ if (count <= 0) {
135
+ const mutex = txMutexes.get(key)
136
+ if (mutex && !mutex.isLocked()) {
137
+ txMutexes.delete(key)
138
+ txMutexRefCounts.delete(key)
139
+ }
140
+ }
141
+ }
142
+ /**
143
+ * Check if currently in a transaction
144
+ */
145
+ function isInTransaction() {
146
+ return !!txStorage.getStore()
147
+ }
148
+ /**
149
+ * Commit transaction with retries
150
+ */
151
+ async function commitWithRetry(mutations) {
152
+ if (Object.keys(mutations).length === 0) {
153
+ logger.trace('no mutations in transaction')
154
+ return
155
+ }
156
+ logger.trace('committing transaction')
157
+ for (let attempt = 0; attempt < maxCommitRetries; attempt++) {
158
+ try {
159
+ await state.set(mutations)
160
+ logger.trace({ mutationCount: Object.keys(mutations).length }, 'committed transaction')
161
+ return
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_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(
214
+ types.map(type =>
215
+ getQueue(type).add(async () => {
216
+ const typeData = { [type]: data[type] }
217
+ await state.set(typeData)
218
+ })
219
+ )
220
+ )
221
+ return
222
+ }
223
+ // In transaction - update cache and mutations
224
+ logger.trace({ types: Object.keys(data) }, 'caching in transaction')
225
+ for (const key_ in data) {
226
+ const key = key_
227
+ // Ensure structures exist
228
+ ctx.cache[key] = ctx.cache[key] || {}
229
+ ctx.mutations[key] = ctx.mutations[key] || {}
230
+ // Special handling for pre-keys
231
+ if (key === 'pre-key') {
232
+ await preKeyManager.processOperations(data, key, ctx.cache, ctx.mutations, true)
233
+ } else {
234
+ // Normal key types
235
+ Object.assign(ctx.cache[key], data[key])
236
+ Object.assign(ctx.mutations[key], data[key])
237
+ }
238
+ }
239
+ },
240
+ isInTransaction,
241
+ transaction: async (work, key) => {
242
+ const existing = txStorage.getStore()
243
+ // Nested transaction - reuse existing context
244
+ if (existing) {
245
+ logger.trace('reusing existing transaction context')
246
+ return work()
247
+ }
248
+ // New transaction - acquire mutex and create context
249
+ const mutex = getTxMutex(key)
250
+ acquireTxMutexRef(key)
251
+ try {
252
+ return await mutex.runExclusive(async () => {
253
+ const ctx = {
254
+ cache: {},
255
+ mutations: {},
256
+ dbQueries: 0
257
+ }
258
+ logger.trace('entering transaction')
259
+ try {
260
+ const result = await txStorage.run(ctx, work)
261
+ // Commit mutations
262
+ await commitWithRetry(ctx.mutations)
263
+ logger.trace({ dbQueries: ctx.dbQueries }, 'transaction completed')
264
+ return result
265
+ } catch (error) {
266
+ logger.error({ error }, 'transaction failed, rolling back')
267
+ throw error
268
+ }
269
+ })
270
+ } finally {
271
+ releaseTxMutexRef(key)
272
+ }
273
+ }
274
+ }
275
+ }
276
+ exports.addTransactionCapability = addTransactionCapability
277
+ const initAuthCreds = () => {
278
+ const identityKey = crypto_2.Curve.generateKeyPair()
279
+ return {
280
+ noiseKey: crypto_2.Curve.generateKeyPair(),
281
+ pairingEphemeralKeyPair: crypto_2.Curve.generateKeyPair(),
282
+ signedIdentityKey: identityKey,
283
+ signedPreKey: (0, crypto_2.signedKeyPair)(identityKey, 1),
284
+ registrationId: (0, generics_1.generateRegistrationId)(),
285
+ advSecretKey: (0, crypto_1.randomBytes)(32).toString('base64'),
286
+ processedHistoryMessages: [],
287
+ initialFullSyncDone: false,
288
+ nextPreKeyId: 1,
289
+ firstUnuploadedPreKeyId: 1,
290
+ accountSyncCounter: 0,
291
+ accountSettings: {
292
+ unarchiveChats: false
293
+ },
294
+ deviceId: Buffer.from((0, crypto_1.randomUUID)().replace(/-/g, ''), 'hex').toString('base64url'),
295
+ phoneId: (0, crypto_1.randomUUID)(),
296
+ identityId: (0, crypto_1.randomBytes)(20),
297
+ backupToken: (0, crypto_1.randomBytes)(20),
298
+ registration: {},
299
+ registered: false,
300
+ pairingCode: undefined,
301
+ lastPropHash: undefined,
302
+ routingInfo: undefined,
303
+ additionalData: undefined
304
+ }
305
+ }
306
+ exports.initAuthCreds = initAuthCreds
@@ -0,0 +1,114 @@
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 COMPANION_PLATFORM_MAP = {
7
+ Chrome: '49',
8
+ Edge: '50',
9
+ Firefox: '51',
10
+ Opera: '53',
11
+ Safari: '54',
12
+ Brave: '1.79.112',
13
+ Vivaldi: '6.2.3105.58',
14
+ Tor: '12.5.3',
15
+ Yandex: '23.7.1',
16
+ Falkon: '22.08.3',
17
+ Epiphany: '44.2'
18
+ }
19
+ const PLATFORM_MAP = {
20
+ aix: 'AIX',
21
+ darwin: 'Mac OS',
22
+ win32: 'Windows',
23
+ android: 'Android',
24
+ freebsd: 'FreeBSD',
25
+ openbsd: 'OpenBSD',
26
+ sunos: 'Solaris',
27
+ linux: 'Linux',
28
+ ubuntu: 'Ubuntu',
29
+ ios: 'iOS',
30
+ baileys: 'Baileys',
31
+ chromeos: 'Chrome OS',
32
+ tizen: 'Tizen',
33
+ watchos: 'watchOS',
34
+ wearos: 'Wear OS',
35
+ harmonyos: 'HarmonyOS',
36
+ kaios: 'KaiOS',
37
+ smarttv: 'Smart TV',
38
+ raspberrypi: 'Raspberry Pi OS',
39
+ symbian: 'Symbian',
40
+ blackberry: 'Blackberry OS',
41
+ windowsphone: 'Windows Phone',
42
+ safari: 'Safari'
43
+ }
44
+
45
+ const PLATFORM_VERSIONS = {
46
+ ubuntu: '22.04.4',
47
+ darwin: '18.5',
48
+ win32: '10.0.22631',
49
+ android: '14.0.0',
50
+ freebsd: '13.2',
51
+ openbsd: '7.3',
52
+ sunos: '11',
53
+ linux: '6.5',
54
+ ios: '18.2',
55
+ baileys: '6.5.0',
56
+ chromeos: '117.0.5938.132',
57
+ tizen: '6.5',
58
+ watchos: '10.1',
59
+ wearos: '4.1',
60
+ harmonyos: '4.0.0',
61
+ kaios: '3.1',
62
+ smarttv: '23.3.1',
63
+ raspberrypi: '11 (Bullseye)',
64
+ symbian: '3',
65
+ blackberry: '10.3.3',
66
+ windowsphone: '8.1'
67
+ }
68
+
69
+ exports.Browsers = {
70
+ ubuntu: browser => {
71
+ return [PLATFORM_MAP['ubuntu'], browser, PLATFORM_VERSIONS['ubuntu']]
72
+ },
73
+ macOS: browser => {
74
+ return [PLATFORM_MAP['darwin'], browser, PLATFORM_VERSIONS['darwin']]
75
+ },
76
+ windows: browser => {
77
+ return [PLATFORM_MAP['win32'], browser, PLATFORM_VERSIONS['win32']]
78
+ },
79
+ linux: browser => {
80
+ return [PLATFORM_MAP['linux'], browser, PLATFORM_VERSIONS['linux']]
81
+ },
82
+ solaris: browser => {
83
+ return [PLATFORM_MAP['sunos'], browser, PLATFORM_VERSIONS['sunos']]
84
+ },
85
+ baileys: browser => {
86
+ return [PLATFORM_MAP['baileys'], browser, PLATFORM_VERSIONS['baileys']]
87
+ },
88
+ android: browser => {
89
+ return [PLATFORM_MAP['android'], browser, PLATFORM_VERSIONS['android']]
90
+ },
91
+ iOS: browser => {
92
+ return [PLATFORM_MAP['ios'], browser, PLATFORM_VERSIONS['ios']]
93
+ },
94
+ kaiOS: browser => {
95
+ return [PLATFORM_MAP['kaios'], browser, PLATFORM_VERSIONS['kaios']]
96
+ },
97
+ chromeOS: browser => {
98
+ return [PLATFORM_MAP['chromeos'], browser, PLATFORM_VERSIONS['chromeos']]
99
+ },
100
+ appropriate: browser => {
101
+ const platform = os_1.platform()
102
+ const platformName = PLATFORM_MAP[platform] || 'Unknown OS'
103
+ return [platformName, browser, PLATFORM_VERSIONS[platform] || 'latest']
104
+ },
105
+ custom: (platform, browser, version) => {
106
+ const platformName = PLATFORM_MAP[platform.toLowerCase()] || platform
107
+ return [platformName, browser, version || PLATFORM_VERSIONS[platform] || 'latest']
108
+ }
109
+ }
110
+ const getPlatformId = browser => {
111
+ const platformType = index_js_1.proto.DeviceProps.PlatformType[browser.toUpperCase()]
112
+ return platformType ? platformType.toString() : '1' //chrome
113
+ }
114
+ exports.getPlatformId = getPlatformId
@@ -0,0 +1,247 @@
1
+ 'use strict'
2
+ Object.defineProperty(exports, '__esModule', { value: true })
3
+ exports.uploadingNecessaryImages =
4
+ exports.parseProductNode =
5
+ exports.toProductNode =
6
+ exports.parseOrderDetailsNode =
7
+ exports.parseCollectionsNode =
8
+ exports.parseCatalogNode =
9
+ void 0
10
+ exports.uploadingNecessaryImagesOfProduct = uploadingNecessaryImagesOfProduct
11
+ const boom_1 = require('@hapi/boom')
12
+ const crypto_1 = require('crypto')
13
+ const fs_1 = require('fs')
14
+ const os_1 = require('os')
15
+ const path_1 = require('path')
16
+ const WABinary_1 = require('../WABinary')
17
+ const generics_1 = require('./generics')
18
+ const messages_media_1 = require('./messages-media')
19
+ const parseCatalogNode = node => {
20
+ const catalogNode = (0, WABinary_1.getBinaryNodeChild)(node, 'product_catalog')
21
+ const products = (0, WABinary_1.getBinaryNodeChildren)(catalogNode, 'product').map(exports.parseProductNode)
22
+ const paging = (0, WABinary_1.getBinaryNodeChild)(catalogNode, 'paging')
23
+ return {
24
+ products,
25
+ nextPageCursor: paging ? (0, WABinary_1.getBinaryNodeChildString)(paging, 'after') : undefined
26
+ }
27
+ }
28
+ exports.parseCatalogNode = parseCatalogNode
29
+ const parseCollectionsNode = node => {
30
+ const collectionsNode = (0, WABinary_1.getBinaryNodeChild)(node, 'collections')
31
+ const collections = (0, WABinary_1.getBinaryNodeChildren)(collectionsNode, 'collection').map(collectionNode => {
32
+ const id = (0, WABinary_1.getBinaryNodeChildString)(collectionNode, 'id')
33
+ const name = (0, WABinary_1.getBinaryNodeChildString)(collectionNode, 'name')
34
+ const products = (0, WABinary_1.getBinaryNodeChildren)(collectionNode, 'product').map(exports.parseProductNode)
35
+ return {
36
+ id,
37
+ name,
38
+ products,
39
+ status: parseStatusInfo(collectionNode)
40
+ }
41
+ })
42
+ return {
43
+ collections
44
+ }
45
+ }
46
+ exports.parseCollectionsNode = parseCollectionsNode
47
+ const parseOrderDetailsNode = node => {
48
+ const orderNode = (0, WABinary_1.getBinaryNodeChild)(node, 'order')
49
+ const products = (0, WABinary_1.getBinaryNodeChildren)(orderNode, 'product').map(productNode => {
50
+ const imageNode = (0, WABinary_1.getBinaryNodeChild)(productNode, 'image')
51
+ return {
52
+ id: (0, WABinary_1.getBinaryNodeChildString)(productNode, 'id'),
53
+ name: (0, WABinary_1.getBinaryNodeChildString)(productNode, 'name'),
54
+ imageUrl: (0, WABinary_1.getBinaryNodeChildString)(imageNode, 'url'),
55
+ price: +(0, WABinary_1.getBinaryNodeChildString)(productNode, 'price'),
56
+ currency: (0, WABinary_1.getBinaryNodeChildString)(productNode, 'currency'),
57
+ quantity: +(0, WABinary_1.getBinaryNodeChildString)(productNode, 'quantity')
58
+ }
59
+ })
60
+ const priceNode = (0, WABinary_1.getBinaryNodeChild)(orderNode, 'price')
61
+ const orderDetails = {
62
+ price: {
63
+ total: +(0, WABinary_1.getBinaryNodeChildString)(priceNode, 'total'),
64
+ currency: (0, WABinary_1.getBinaryNodeChildString)(priceNode, 'currency')
65
+ },
66
+ products
67
+ }
68
+ return orderDetails
69
+ }
70
+ exports.parseOrderDetailsNode = parseOrderDetailsNode
71
+ const toProductNode = (productId, product) => {
72
+ const attrs = {}
73
+ const content = []
74
+ if (typeof productId !== 'undefined') {
75
+ content.push({
76
+ tag: 'id',
77
+ attrs: {},
78
+ content: Buffer.from(productId)
79
+ })
80
+ }
81
+ if (typeof product.name !== 'undefined') {
82
+ content.push({
83
+ tag: 'name',
84
+ attrs: {},
85
+ content: Buffer.from(product.name)
86
+ })
87
+ }
88
+ if (typeof product.description !== 'undefined') {
89
+ content.push({
90
+ tag: 'description',
91
+ attrs: {},
92
+ content: Buffer.from(product.description)
93
+ })
94
+ }
95
+ if (typeof product.retailerId !== 'undefined') {
96
+ content.push({
97
+ tag: 'retailer_id',
98
+ attrs: {},
99
+ content: Buffer.from(product.retailerId)
100
+ })
101
+ }
102
+ if (product.images.length) {
103
+ content.push({
104
+ tag: 'media',
105
+ attrs: {},
106
+ content: product.images.map(img => {
107
+ if (!('url' in img)) {
108
+ throw new boom_1.Boom('Expected img for product to already be uploaded', { statusCode: 400 })
109
+ }
110
+ return {
111
+ tag: 'image',
112
+ attrs: {},
113
+ content: [
114
+ {
115
+ tag: 'url',
116
+ attrs: {},
117
+ content: Buffer.from(img.url.toString())
118
+ }
119
+ ]
120
+ }
121
+ })
122
+ })
123
+ }
124
+ if (typeof product.price !== 'undefined') {
125
+ content.push({
126
+ tag: 'price',
127
+ attrs: {},
128
+ content: Buffer.from(product.price.toString())
129
+ })
130
+ }
131
+ if (typeof product.currency !== 'undefined') {
132
+ content.push({
133
+ tag: 'currency',
134
+ attrs: {},
135
+ content: Buffer.from(product.currency)
136
+ })
137
+ }
138
+ if ('originCountryCode' in product) {
139
+ if (typeof product.originCountryCode === 'undefined') {
140
+ attrs['compliance_category'] = 'COUNTRY_ORIGIN_EXEMPT'
141
+ } else {
142
+ content.push({
143
+ tag: 'compliance_info',
144
+ attrs: {},
145
+ content: [
146
+ {
147
+ tag: 'country_code_origin',
148
+ attrs: {},
149
+ content: Buffer.from(product.originCountryCode)
150
+ }
151
+ ]
152
+ })
153
+ }
154
+ }
155
+ if (typeof product.isHidden !== 'undefined') {
156
+ attrs['is_hidden'] = product.isHidden.toString()
157
+ }
158
+ const node = {
159
+ tag: 'product',
160
+ attrs,
161
+ content
162
+ }
163
+ return node
164
+ }
165
+ exports.toProductNode = toProductNode
166
+ const parseProductNode = productNode => {
167
+ const isHidden = productNode.attrs.is_hidden === 'true'
168
+ const id = (0, WABinary_1.getBinaryNodeChildString)(productNode, 'id')
169
+ const mediaNode = (0, WABinary_1.getBinaryNodeChild)(productNode, 'media')
170
+ const statusInfoNode = (0, WABinary_1.getBinaryNodeChild)(productNode, 'status_info')
171
+ const product = {
172
+ id,
173
+ imageUrls: parseImageUrls(mediaNode),
174
+ reviewStatus: {
175
+ whatsapp: (0, WABinary_1.getBinaryNodeChildString)(statusInfoNode, 'status')
176
+ },
177
+ availability: 'in stock',
178
+ name: (0, WABinary_1.getBinaryNodeChildString)(productNode, 'name'),
179
+ retailerId: (0, WABinary_1.getBinaryNodeChildString)(productNode, 'retailer_id'),
180
+ url: (0, WABinary_1.getBinaryNodeChildString)(productNode, 'url'),
181
+ description: (0, WABinary_1.getBinaryNodeChildString)(productNode, 'description'),
182
+ price: +(0, WABinary_1.getBinaryNodeChildString)(productNode, 'price'),
183
+ currency: (0, WABinary_1.getBinaryNodeChildString)(productNode, 'currency'),
184
+ isHidden
185
+ }
186
+ return product
187
+ }
188
+ exports.parseProductNode = parseProductNode
189
+ /**
190
+ * Uploads images not already uploaded to WA's servers
191
+ */
192
+ async function uploadingNecessaryImagesOfProduct(product, waUploadToServer, timeoutMs = 30000) {
193
+ product = {
194
+ ...product,
195
+ images: product.images
196
+ ? await (0, exports.uploadingNecessaryImages)(product.images, waUploadToServer, timeoutMs)
197
+ : product.images
198
+ }
199
+ return product
200
+ }
201
+ /**
202
+ * Uploads images not already uploaded to WA's servers
203
+ */
204
+ const uploadingNecessaryImages = async (images, waUploadToServer, timeoutMs = 30000) => {
205
+ const results = await Promise.all(
206
+ images.map(async img => {
207
+ if ('url' in img) {
208
+ const url = img.url.toString()
209
+ if (url.includes('.whatsapp.net')) {
210
+ return { url }
211
+ }
212
+ }
213
+ const { stream } = await (0, messages_media_1.getStream)(img)
214
+ const hasher = (0, crypto_1.createHash)('sha256')
215
+ const filePath = (0, path_1.join)((0, os_1.tmpdir)(), 'img' + (0, generics_1.generateMessageIDV2)())
216
+ const encFileWriteStream = (0, fs_1.createWriteStream)(filePath)
217
+ for await (const block of stream) {
218
+ hasher.update(block)
219
+ encFileWriteStream.write(block)
220
+ }
221
+ const sha = hasher.digest('base64')
222
+ const { directPath } = await waUploadToServer(filePath, {
223
+ mediaType: 'product-catalog-image',
224
+ fileEncSha256B64: sha,
225
+ timeoutMs
226
+ })
227
+ await fs_1.promises.unlink(filePath).catch(() => {})
228
+ return { url: (0, messages_media_1.getUrlFromDirectPath)(directPath) }
229
+ })
230
+ )
231
+ return results
232
+ }
233
+ exports.uploadingNecessaryImages = uploadingNecessaryImages
234
+ const parseImageUrls = mediaNode => {
235
+ const imgNode = (0, WABinary_1.getBinaryNodeChild)(mediaNode, 'image')
236
+ return {
237
+ requested: (0, WABinary_1.getBinaryNodeChildString)(imgNode, 'request_image_url'),
238
+ original: (0, WABinary_1.getBinaryNodeChildString)(imgNode, 'original_image_url')
239
+ }
240
+ }
241
+ const parseStatusInfo = mediaNode => {
242
+ const node = (0, WABinary_1.getBinaryNodeChild)(mediaNode, 'status_info')
243
+ return {
244
+ status: (0, WABinary_1.getBinaryNodeChildString)(node, 'status'),
245
+ canAppeal: (0, WABinary_1.getBinaryNodeChildString)(node, 'can_appeal') === 'true'
246
+ }
247
+ }