@zervonexx/baileys 0.0.0-stage → 5.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 (125) hide show
  1. package/LICENSE +23 -0
  2. package/README.md +4113 -3
  3. package/WAProto/WAProtoCompile.js +323 -0
  4. package/WAProto/fetcher.js +68 -0
  5. package/WAProto/index.js +96 -0
  6. package/WAProto/parser.js +334 -0
  7. package/lib/Builders/AIRich.js +674 -0
  8. package/lib/Builders/auto.js +50 -0
  9. package/lib/Builders/base.js +145 -0
  10. package/lib/Builders/builders.js +589 -0
  11. package/lib/Builders/index.js +4 -0
  12. package/lib/Defaults/index.js +248 -0
  13. package/lib/Signal/index.js +2 -0
  14. package/lib/Signal/libsignal.js +527 -0
  15. package/lib/Signal/lid-mapping.js +283 -0
  16. package/lib/Socket/Client/index.js +2 -0
  17. package/lib/Socket/Client/types.js +10 -0
  18. package/lib/Socket/Client/websocket.js +84 -0
  19. package/lib/Socket/business.js +152 -0
  20. package/lib/Socket/chats.js +855 -0
  21. package/lib/Socket/communities.js +147 -0
  22. package/lib/Socket/groups.js +294 -0
  23. package/lib/Socket/index.js +15 -0
  24. package/lib/Socket/messages-recv.js +994 -0
  25. package/lib/Socket/messages-send.js +723 -0
  26. package/lib/Socket/mex.js +34 -0
  27. package/lib/Socket/newsletter.js +784 -0
  28. package/lib/Socket/registration.js +155 -0
  29. package/lib/Socket/socket.js +798 -0
  30. package/lib/Socket/spam-report.js +144 -0
  31. package/lib/Socket/username.js +82 -0
  32. package/lib/Socket/zervonex-handler.js +58 -0
  33. package/lib/Store/index.js +6 -0
  34. package/lib/Store/make-cache-manager-store.js +80 -0
  35. package/lib/Store/make-in-memory-store.js +426 -0
  36. package/lib/Store/make-ordered-dictionary.js +82 -0
  37. package/lib/Store/object-repository.js +31 -0
  38. package/lib/Store/reporting-info-store.js +38 -0
  39. package/lib/Types/Auth.js +2 -0
  40. package/lib/Types/Bussines.js +2 -0
  41. package/lib/Types/Call.js +2 -0
  42. package/lib/Types/Chat.js +8 -0
  43. package/lib/Types/Contact.js +2 -0
  44. package/lib/Types/Events.js +2 -0
  45. package/lib/Types/GroupMetadata.js +2 -0
  46. package/lib/Types/Label.js +25 -0
  47. package/lib/Types/LabelAssociation.js +7 -0
  48. package/lib/Types/Message.js +15 -0
  49. package/lib/Types/Newsletter.js +100 -0
  50. package/lib/Types/Product.js +2 -0
  51. package/lib/Types/Signal.js +2 -0
  52. package/lib/Types/Socket.js +14 -0
  53. package/lib/Types/State.js +26 -0
  54. package/lib/Types/USync.js +2 -0
  55. package/lib/Types/index.js +30 -0
  56. package/lib/Utils/auth-utils.js +159 -0
  57. package/lib/Utils/baileys-event-stream.js +33 -0
  58. package/lib/Utils/bot-capabilities.js +41 -0
  59. package/lib/Utils/bot-planning-replay.js +44 -0
  60. package/lib/Utils/browser-utils.js +30 -0
  61. package/lib/Utils/business.js +75 -0
  62. package/lib/Utils/chat-utils.js +317 -0
  63. package/lib/Utils/companion-reg-client-utils.js +20 -0
  64. package/lib/Utils/consumer-application.js +38 -0
  65. package/lib/Utils/crypto.js +53 -0
  66. package/lib/Utils/cstoken.js +15 -0
  67. package/lib/Utils/decode-wa-message.js +200 -0
  68. package/lib/Utils/event-buffer.js +273 -0
  69. package/lib/Utils/extras.js +186 -0
  70. package/lib/Utils/generics.js +195 -0
  71. package/lib/Utils/history.js +51 -0
  72. package/lib/Utils/identity-change-handler.js +19 -0
  73. package/lib/Utils/index.js +40 -0
  74. package/lib/Utils/link-preview.js +51 -0
  75. package/lib/Utils/logger.js +3 -0
  76. package/lib/Utils/lt-hash.js +3 -0
  77. package/lib/Utils/make-mutex.js +16 -0
  78. package/lib/Utils/message-composer.js +62 -0
  79. package/lib/Utils/message-retry-manager.js +48 -0
  80. package/lib/Utils/messages-media.js +502 -0
  81. package/lib/Utils/messages.js +943 -0
  82. package/lib/Utils/meta-ai-msmsg.js +122 -0
  83. package/lib/Utils/meta-compositing.js +75 -0
  84. package/lib/Utils/modern-messages.js +235 -0
  85. package/lib/Utils/native-flow.js +81 -0
  86. package/lib/Utils/noise-handler.js +161 -0
  87. package/lib/Utils/pre-key-manager.js +76 -0
  88. package/lib/Utils/process-message.js +401 -0
  89. package/lib/Utils/reporting-utils.js +171 -0
  90. package/lib/Utils/signal.js +167 -0
  91. package/lib/Utils/spam-report-utils.js +166 -0
  92. package/lib/Utils/sync-action-utils.js +33 -0
  93. package/lib/Utils/tc-token-utils.js +154 -0
  94. package/lib/Utils/use-keyv-auth-state.js +200 -0
  95. package/lib/Utils/use-multi-file-auth-state.js +84 -0
  96. package/lib/Utils/validate-connection.js +172 -0
  97. package/lib/WABinary/constants.js +1321 -0
  98. package/lib/WABinary/decode.js +152 -0
  99. package/lib/WABinary/encode.js +140 -0
  100. package/lib/WABinary/generic-utils.js +203 -0
  101. package/lib/WABinary/index.js +6 -0
  102. package/lib/WABinary/jid-utils.js +235 -0
  103. package/lib/WABinary/types.js +4 -0
  104. package/lib/WAM/BinaryInfo.js +10 -0
  105. package/lib/WAM/constants.js +22853 -0
  106. package/lib/WAM/encode.js +150 -0
  107. package/lib/WAM/index.js +3 -0
  108. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +30 -0
  109. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +48 -0
  110. package/lib/WAUSync/Protocols/USyncContactProtocol.js +23 -0
  111. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +28 -0
  112. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +15 -0
  113. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +24 -0
  114. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +9 -0
  115. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +21 -0
  116. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +19 -0
  117. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +19 -0
  118. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +22 -0
  119. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +16 -0
  120. package/lib/WAUSync/Protocols/index.js +12 -0
  121. package/lib/WAUSync/USyncQuery.js +88 -0
  122. package/lib/WAUSync/USyncUser.js +20 -0
  123. package/lib/WAUSync/index.js +3 -0
  124. package/lib/index.js +67 -0
  125. package/package.json +191 -5
@@ -0,0 +1,100 @@
1
+ export var XWAPaths;
2
+ (function (XWAPaths) {
3
+ XWAPaths["xwa2_newsletter_create"] = "xwa2_newsletter_create";
4
+ XWAPaths["xwa2_newsletter_subscribed"] = "xwa2_newsletter_subscribed";
5
+ XWAPaths["xwa2_newsletter_metadata"] = "xwa2_newsletter";
6
+ XWAPaths["xwa2_newsletter_admin_count"] = "xwa2_newsletter_admin";
7
+ XWAPaths["xwa2_newsletter_admin_info"] = "xwa2_newsletter_admin";
8
+ XWAPaths["xwa2_newsletter_admin_capabilities"] = "xwa2_newsletter_admin";
9
+ XWAPaths["admin_profile"] = "xwa2_newsletter_admin";
10
+ XWAPaths["pending_admin_invites"] = "xwa2_newsletter_admin";
11
+ XWAPaths["xwa2_channel_enforcements"] = "xwa2_channel_enforcements";
12
+ XWAPaths["xwa2_channels_reports"] = "xwa2_channels_reports";
13
+ XWAPaths["xwa2_create_channel_report_appeal_v2"] = "xwa2_create_channel_report_appeal_v2";
14
+ XWAPaths["xwa2_newsletter_update_user_setting"] = "xwa2_newsletter_update_user_setting";
15
+ XWAPaths["xwa2_newsletter_join_v2"] = "xwa2_newsletter_join_v2";
16
+ XWAPaths["xwa2_newsletter_leave_v2"] = "xwa2_newsletter_leave_v2";
17
+ XWAPaths["xwa2_newsletter_change_owner"] = "xwa2_newsletter_change_owner";
18
+ XWAPaths["xwa2_newsletter_demote"] = "xwa2_newsletter_admin_demote";
19
+ XWAPaths["xwa2_newsletter_delete_v2"] = "xwa2_newsletter_delete_v2";
20
+ XWAPaths["xwa2_newsletter_followers"] = "xwa2_newsletter_followers";
21
+ XWAPaths["xwa2_newsletter_mute_v2"] = "xwa2_newsletter_mute_v2";
22
+ XWAPaths["xwa2_newsletter_unmute_v2"] = "xwa2_newsletter_unmute_v2";
23
+ XWAPaths["xwa2_newsletter_admin_insights"] = "xwa2_newsletter_admin_insights";
24
+ XWAPaths["xwa2_newsletter_pin_messages"] = "xwa2_newsletter_pin_messages";
25
+ XWAPaths["xwa2_newsletter_unpin_messages"] = "xwa2_newsletter_unpin_messages";
26
+ XWAPaths["xwa2_newsletter_label_ai_content"] = "xwa2_newsletter_label_ai_content";
27
+ XWAPaths["xwa2_newsletter_label_paid_partnership"] = "xwa2_newsletter_label_paid_partnership";
28
+ XWAPaths["xwa2_newsletter_admin_invite_create"] = "xwa2_newsletter_admin_invite_create";
29
+ XWAPaths["xwa2_newsletter_admin_invite_revoke"] = "xwa2_newsletter_admin_invite_revoke";
30
+ XWAPaths["xwa2_newsletter_admin_invite_accept"] = "xwa2_newsletter_admin_invite_accept";
31
+ XWAPaths["xwa2_newsletter_link_preview"] = "xwa2_newsletter_link_preview";
32
+ XWAPaths["xwa2_newsletter_question_response_state_update"] = "xwa2_newsletter_question_response_state_update";
33
+ XWAPaths["voter_list"] = "voter_list";
34
+ XWAPaths["xwa2_newsletters_reaction_sender_list"] = "xwa2_newsletters_reaction_sender_list";
35
+ XWAPaths["xwa2_newsletters_recommended"] = "xwa2_newsletters_recommended";
36
+ XWAPaths["xwa2_newsletters_similar"] = "xwa2_newsletters_similar";
37
+ XWAPaths["xwa2_newsletters_directory_list"] = "xwa2_newsletters_directory_list";
38
+ XWAPaths["xwa2_newsletters_directory_search"] = "xwa2_newsletters_directory_search";
39
+ XWAPaths["xwa2_newsletters_directory_category_preview"] = "xwa2_newsletters_directory_category_preview";
40
+ XWAPaths["xwa2_fetch_account_reachout_timelock"] = "xwa2_fetch_account_reachout_timelock";
41
+ XWAPaths["xwa2_message_capping_info"] = "xwa2_message_capping_info";
42
+ XWAPaths["xwa2_username_get"] = "xwa2_username_get";
43
+ XWAPaths["xwa2_username_set"] = "xwa2_username_set";
44
+ XWAPaths["xwa2_username_pin_set"] = "xwa2_username_pin_set";
45
+ XWAPaths["xwa2_username_check"] = "xwa2_username_check";
46
+ XWAPaths["xwa2_update_text_status"] = "xwa2_update_text_status";
47
+ XWAPaths["xwa2_text_status_list"] = "xwa2_text_status_list";
48
+ XWAPaths["xwa2_users_updates_since"] = "xwa2_users_updates_since";
49
+ })(XWAPaths || (XWAPaths = {}));
50
+
51
+ export var QueryIds;
52
+ (function (QueryIds) {
53
+ QueryIds["CREATE"] = "25149874324715067";
54
+ QueryIds["UPDATE_METADATA"] = "24250201037901610";
55
+ QueryIds["METADATA"] = "27456920720571478";
56
+ QueryIds["SUBSCRIBERS"] = "9783111038412085";
57
+ QueryIds["SUBSCRIBED"] = "25399611239711790";
58
+ QueryIds["FOLLOW"] = "24404358912487870";
59
+ QueryIds["UNFOLLOW"] = "9767147403369991";
60
+ QueryIds["ENFORCEMENTS"] = "27835373536068060";
61
+ QueryIds["CHANNEL_REPORTS"] = "35936238352686172";
62
+ QueryIds["CREATE_REPORT_APPEAL"] = "27103316329328467";
63
+ QueryIds["UPDATE_USER_SETTING"] = "31938993655691868";
64
+ QueryIds["ADMIN_COUNT"] = "26278439461859188";
65
+ QueryIds["ADMIN_INFO"] = "26278439461859188";
66
+ QueryIds["ADMIN_CAPABILITIES"] = "9801384413216421";
67
+ QueryIds["CHANGE_OWNER"] = "9546742745432473";
68
+ QueryIds["DEMOTE"] = "9880997548630971";
69
+ QueryIds["DELETE"] = "30062808666639665";
70
+ QueryIds["FOLLOWERS"] = "27472091235714801";
71
+ QueryIds["MUTE"] = "29766401636284406";
72
+ QueryIds["UNMUTE"] = "9864994326891137";
73
+ QueryIds["INSIGHTS"] = "9853618868050977";
74
+ QueryIds["PIN_MESSAGES"] = "27165709459706559";
75
+ QueryIds["UNPIN_MESSAGES"] = "28007176042216937";
76
+ QueryIds["LABEL_AI_CONTENT"] = "27909718265289596";
77
+ QueryIds["PAID_PARTNERSHIP_LABEL"] = "26102375079404865";
78
+ QueryIds["CREATE_ADMIN_INVITE"] = "9387141988078609";
79
+ QueryIds["REVOKE_ADMIN_INVITE"] = "9656078347839416";
80
+ QueryIds["ACCEPT_ADMIN_INVITE"] = "9580828702035549";
81
+ QueryIds["POLL_VOTERS"] = "9407762219322536";
82
+ QueryIds["REACTION_SENDER_LIST"] = "29575462448733991";
83
+ QueryIds["RECOMMENDED"] = "25806748772361516";
84
+ QueryIds["SIMILAR"] = "26217043484590756";
85
+ QueryIds["DIRECTORY_LIST"] = "26125047313831973";
86
+ QueryIds["DIRECTORY_SEARCH"] = "26301059626252132";
87
+ QueryIds["DIRECTORY_CATEGORIES"] = "35266481849605779";
88
+ QueryIds["PENDING_ADMIN_INVITES"] = "9783111038412085";
89
+ QueryIds["QUESTION_RESPONSE_STATE"] = "24636260219323456";
90
+ QueryIds["REACHOUT_TIMELOCK"] = "23983697327930364";
91
+ QueryIds["MESSAGE_CAPPING_INFO"] = "27910975521856601";
92
+ QueryIds["PLAINTEXT_LINK_PREVIEW"] = "9101130456653613";
93
+ QueryIds["USERNAME_GET"] = "25347099718279209";
94
+ QueryIds["USERNAME_SET"] = "25757341163897635";
95
+ QueryIds["USERNAME_PIN_SET"] = "9749436995157074";
96
+ QueryIds["USERNAME_CHECK"] = "26122779627399568";
97
+ QueryIds["UPDATE_TEXT_STATUS"] = "9152604461510864";
98
+ QueryIds["TEXT_STATUS_LIST"] = "24072923595647473";
99
+ QueryIds["ABOUT_STATUS"] = "24535500086059408";
100
+ })(QueryIds || (QueryIds = {}));
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=Product.js.map
@@ -0,0 +1,2 @@
1
+ import { proto } from '../../WAProto/index.js';
2
+ //# sourceMappingURL=Signal.js.map
@@ -0,0 +1,14 @@
1
+ import { proto } from '../../WAProto/index.js';
2
+ import {} from './Message.js';
3
+ //# sourceMappingURL=Socket.js.map
4
+ export const AIProvenanceType = Object.freeze({
5
+ NONE: 0,
6
+ CREATED_WITH_GEN_AI: 1,
7
+ EDITED_WITH_GEN_AI: 2,
8
+ })
9
+
10
+ export const DeviceCapabilityLevel = Object.freeze({
11
+ NONE: 0,
12
+ INFRA: 1,
13
+ FULL: 2,
14
+ })
@@ -0,0 +1,26 @@
1
+ export const SyncState = Object.freeze({ Connecting: 0, AwaitingInitialSync: 1, Syncing: 2, Online: 3 })
2
+
3
+ export const ReachoutTimelockEnforcementType = Object.freeze({
4
+ BIZ_COMMERCE_VIOLATION_ALCOHOL: 'BIZ_COMMERCE_VIOLATION_ALCOHOL',
5
+ BIZ_COMMERCE_VIOLATION_ADULT: 'BIZ_COMMERCE_VIOLATION_ADULT',
6
+ BIZ_COMMERCE_VIOLATION_ANIMALS: 'BIZ_COMMERCE_VIOLATION_ANIMALS',
7
+ BIZ_COMMERCE_VIOLATION_BODY_PARTS_FLUIDS: 'BIZ_COMMERCE_VIOLATION_BODY_PARTS_FLUIDS',
8
+ BIZ_COMMERCE_VIOLATION_DATING: 'BIZ_COMMERCE_VIOLATION_DATING',
9
+ BIZ_COMMERCE_VIOLATION_DIGITAL_SERVICES_PRODUCTS: 'BIZ_COMMERCE_VIOLATION_DIGITAL_SERVICES_PRODUCTS',
10
+ BIZ_COMMERCE_VIOLATION_DRUGS: 'BIZ_COMMERCE_VIOLATION_DRUGS',
11
+ BIZ_COMMERCE_VIOLATION_DRUGS_ONLY_OTC: 'BIZ_COMMERCE_VIOLATION_DRUGS_ONLY_OTC',
12
+ BIZ_COMMERCE_VIOLATION_GAMBLING: 'BIZ_COMMERCE_VIOLATION_GAMBLING',
13
+ BIZ_COMMERCE_VIOLATION_HEALTHCARE: 'BIZ_COMMERCE_VIOLATION_HEALTHCARE',
14
+ BIZ_COMMERCE_VIOLATION_REAL_FAKE_CURRENCY: 'BIZ_COMMERCE_VIOLATION_REAL_FAKE_CURRENCY',
15
+ BIZ_COMMERCE_VIOLATION_SUPPLEMENTS: 'BIZ_COMMERCE_VIOLATION_SUPPLEMENTS',
16
+ BIZ_COMMERCE_VIOLATION_TOBACCO: 'BIZ_COMMERCE_VIOLATION_TOBACCO',
17
+ BIZ_COMMERCE_VIOLATION_VIOLENT_CONTENT: 'BIZ_COMMERCE_VIOLATION_VIOLENT_CONTENT',
18
+ BIZ_COMMERCE_VIOLATION_WEAPONS: 'BIZ_COMMERCE_VIOLATION_WEAPONS',
19
+ BIZ_QUALITY: 'BIZ_QUALITY',
20
+ DEFAULT: 'DEFAULT',
21
+ WEB_COMPANION_ONLY: 'WEB_COMPANION_ONLY',
22
+ })
23
+
24
+ export const NewChatMessageCappingStatusType = Object.freeze({ NONE:'NONE', FIRST_WARNING:'FIRST_WARNING', SECOND_WARNING:'SECOND_WARNING', CAPPED:'CAPPED' })
25
+ export const NewChatMessageCappingMVStatusType = Object.freeze({ NOT_ELIGIBLE:'NOT_ELIGIBLE', NOT_ACTIVE:'NOT_ACTIVE', ACTIVE:'ACTIVE', ACTIVE_UPGRADE_AVAILABLE:'ACTIVE_UPGRADE_AVAILABLE' })
26
+ export const NewChatMessageCappingOTEStatusType = Object.freeze({ NOT_ELIGIBLE:'NOT_ELIGIBLE', ELIGIBLE:'ELIGIBLE', ACTIVE_IN_CURRENT_CYCLE:'ACTIVE_IN_CURRENT_CYCLE', EXHAUSTED:'EXHAUSTED' })
@@ -0,0 +1,2 @@
1
+ import { USyncUser } from '../WAUSync/index.js';
2
+ //# sourceMappingURL=USync.js.map
@@ -0,0 +1,30 @@
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 * from './Label.js'
14
+ export * from './LabelAssociation.js'
15
+ export * from './USync.js'
16
+
17
+ export const DisconnectReason = Object.freeze({
18
+ connectionClosed: 428,
19
+ connectionLost: 408,
20
+ connectionReplaced: 440,
21
+ timedOut: 408,
22
+ loggedOut: 401,
23
+ badSession: 500,
24
+ restartRequired: 515,
25
+ multideviceMismatch: 411,
26
+ forbidden: 403,
27
+ unavailableService: 503,
28
+ })
29
+
30
+
@@ -0,0 +1,159 @@
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 { v4 } from 'uuid'
7
+ import { DEFAULT_CACHE_TTLS } from '../Defaults/index.js'
8
+ import { Curve, signedKeyPair } from './crypto.js'
9
+ import { delay, generateRegistrationId, BufferJSON } from './generics.js'
10
+ import { PreKeyManager } from './pre-key-manager.js'
11
+ import { proto } from '../../WAProto/index.js'
12
+
13
+ export function makeCacheableSignalKeyStore(store, logger, _cache) {
14
+ const cache = _cache || new NodeCache({ stdTTL: DEFAULT_CACHE_TTLS.SIGNAL_STORE, useClones: false, deleteOnExpire: true })
15
+ const cacheMutex = new Mutex()
16
+ const uid = (type, id) => `${type}.${id}`
17
+ return {
18
+ async get(type, ids) {
19
+ return cacheMutex.runExclusive(async () => {
20
+ const data = {}, missing = []
21
+ for (const id of ids) { const item = await cache.get(uid(type, id)); if (typeof item !== 'undefined') data[id] = item; else missing.push(id) }
22
+ if (missing.length) { logger?.trace({ items: missing.length }, 'loading from store'); const fetched = await store.get(type, missing); for (const id of missing) { if (fetched[id]) { data[id] = fetched[id]; cache.set(uid(type, id), fetched[id]) } } }
23
+ return data
24
+ })
25
+ },
26
+ async set(data) {
27
+ return cacheMutex.runExclusive(async () => {
28
+ let keys = 0
29
+ for (const type in data) { for (const id in data[type]) { await cache.set(uid(type, id), data[type][id]); keys++ } }
30
+ logger?.trace({ keys }, 'updated cache')
31
+ await store.set(data)
32
+ })
33
+ },
34
+ async clear() { await cache.flushAll(); await store.clear?.() }
35
+ }
36
+ }
37
+
38
+ export const addTransactionCapability = (state, logger, { maxCommitRetries, delayBetweenTriesMs }) => {
39
+ const txStorage = new AsyncLocalStorage()
40
+ const keyQueues = new Map()
41
+ const txMutexes = new Map()
42
+ const preKeyManager = new PreKeyManager(state, logger)
43
+
44
+ const getQueue = key => { if (!keyQueues.has(key)) keyQueues.set(key, new PQueue({ concurrency: 1 })); return keyQueues.get(key) }
45
+ const getTxMutex = key => { if (!txMutexes.has(key)) txMutexes.set(key, new Mutex()); return txMutexes.get(key) }
46
+ const isInTransaction = () => !!txStorage.getStore()
47
+
48
+ const EXPECTED_ERRORS = ['InvalidPreKeyId', 'SessionNotFound', 'InvalidMessage', 'no sender key state', 'memory access out of bounds', 'old counter', 'DuplicatedMessage', 'BadMac', 'Connection Closed']
49
+ const isExpectedError = msg => EXPECTED_ERRORS.some(e => msg.includes(e))
50
+
51
+ async function commitWithRetry(mutations) {
52
+ if (Object.keys(mutations).length === 0) { logger.trace('no mutations in transaction'); return }
53
+ logger.trace('committing transaction')
54
+ for (let attempt = 0; attempt < maxCommitRetries; attempt++) {
55
+ try {
56
+ await state.set(mutations)
57
+ logger.trace({ mutationCount: Object.keys(mutations).length }, 'committed transaction')
58
+ return
59
+ } catch (error) {
60
+ const msg = error?.message || (typeof error === 'string' ? error : '') || ''
61
+ if (isExpectedError(msg)) { logger?.debug?.({ error: msg }, 'transaction skipped — expected decrypt error'); return }
62
+ if (attempt < maxCommitRetries - 1) { await delay(delayBetweenTriesMs); continue }
63
+ logger?.error?.({ error: msg || error }, 'transaction failed after retries')
64
+ throw error
65
+ }
66
+ }
67
+ }
68
+
69
+ return {
70
+ get: async (type, ids) => {
71
+ const ctx = txStorage.getStore()
72
+ if (!ctx) return state.get(type, ids)
73
+ const cached = ctx.cache[type] || {}
74
+ const missing = ids.filter(id => !(id in cached))
75
+ if (missing.length) { ctx.dbQueries++; logger.trace({ type, count: missing.length }, 'fetching missing keys in transaction'); const fetched = await getTxMutex(type).runExclusive(() => state.get(type, missing)); ctx.cache[type] = ctx.cache[type] || {}; Object.assign(ctx.cache[type], fetched) }
76
+ const result = {}
77
+ for (const id of ids) { const value = ctx.cache[type]?.[id]; if (value !== undefined && value !== null) result[id] = value }
78
+ return result
79
+ },
80
+ set: async (data) => {
81
+ const ctx = txStorage.getStore()
82
+ if (!ctx) {
83
+ const types = Object.keys(data)
84
+ for (const type of types) { if (type === 'pre-key') await preKeyManager.validateDeletions(data, type) }
85
+ await Promise.all(types.map(type => getQueue(type).add(async () => state.set({ [type]: data[type] }))))
86
+ return
87
+ }
88
+ logger.trace({ types: Object.keys(data) }, 'caching in transaction')
89
+ for (const key in data) {
90
+ ctx.cache[key] = ctx.cache[key] || {}
91
+ ctx.mutations[key] = ctx.mutations[key] || {}
92
+ if (key === 'pre-key') await preKeyManager.processOperations(data, key, ctx.cache, ctx.mutations, true)
93
+ else { Object.assign(ctx.cache[key], data[key]); Object.assign(ctx.mutations[key], data[key]) }
94
+ }
95
+ },
96
+ isInTransaction,
97
+ transaction: async (work, key) => {
98
+ const existing = txStorage.getStore()
99
+ if (existing) { logger.trace('reusing existing transaction context'); return work() }
100
+ return getTxMutex(key).runExclusive(async () => {
101
+ const ctx = { cache: {}, mutations: {}, dbQueries: 0 }
102
+ logger.trace('entering transaction')
103
+ try {
104
+ const result = await txStorage.run(ctx, work)
105
+ await commitWithRetry(ctx.mutations)
106
+ logger.trace({ dbQueries: ctx.dbQueries }, 'transaction completed')
107
+ return result
108
+ } catch (error) {
109
+ const msg = error?.message || (typeof error === 'string' ? error : '') || ''
110
+ ; (isExpectedError(msg) ? logger?.debug?.bind(logger) : logger?.error?.bind(logger))?.({ error: msg || error }, 'transaction failed, rolling back')
111
+ throw error
112
+ }
113
+ })
114
+ }
115
+ }
116
+ }
117
+
118
+ export const initAuthCreds = () => {
119
+ const identityKey = Curve.generateKeyPair()
120
+ return {
121
+ noiseKey: Curve.generateKeyPair(),
122
+ pairingEphemeralKeyPair: Curve.generateKeyPair(),
123
+ signedIdentityKey: identityKey,
124
+ signedPreKey: signedKeyPair(identityKey, 1),
125
+ registrationId: generateRegistrationId(),
126
+ advSecretKey: randomBytes(32).toString('base64'),
127
+ processedHistoryMessages: [],
128
+ nextPreKeyId: 1,
129
+ firstUnuploadedPreKeyId: 1,
130
+ accountSyncCounter: 0,
131
+ accountSettings: { unarchiveChats: false },
132
+ deviceId: Buffer.from(v4().replace(/-/g, ''), 'hex').toString('base64url'),
133
+ phoneId: v4(),
134
+ identityId: randomBytes(20),
135
+ registered: false,
136
+ backupToken: randomBytes(20),
137
+ registration: {},
138
+ pairingCode: undefined,
139
+ lastPropHash: undefined,
140
+ routingInfo: undefined,
141
+ additionalData: undefined
142
+ }
143
+ }
144
+
145
+
146
+ export const bootstrapCreds = raw => raw ?? initAuthCreds()
147
+ export const patchAppStateKey = (type, v) => type === 'app-state-sync-key' && v ? proto.Message.AppStateSyncKeyData.fromObject(v) : v
148
+ export const ser = v => v == null ? null : JSON.parse(JSON.stringify(v, BufferJSON.replacer))
149
+ export const deser = raw => {
150
+ if (raw == null) return null
151
+ let p = typeof raw === 'string'
152
+ ? (() => { try { return JSON.parse(raw) } catch { return raw } })()
153
+ : raw
154
+ let depth = 0
155
+ while (depth++ < 3 && p && typeof p === 'object' && !Array.isArray(p) && Object.keys(p).length === 1 && 'value' in p) p = p.value
156
+ if (p == null) return null
157
+ if (typeof p === 'object' && '__checksum' in p && 'data' in p) p = p.data
158
+ return JSON.parse(JSON.stringify(p), BufferJSON.reviver)
159
+ }
@@ -0,0 +1,33 @@
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'
7
+
8
+ export const captureEventStream = (ev, filename) => {
9
+ const oldEmit = ev.emit.bind(ev)
10
+ const writeMutex = makeMutex()
11
+ ev.emit = (...args) => {
12
+ const content = JSON.stringify({ timestamp: Date.now(), event: args[0], data: args[1] }) + '\n'
13
+ const result = oldEmit(...args)
14
+ writeMutex.mutex(() => writeFile(filename, content, { flag: 'a' }))
15
+ return result
16
+ }
17
+ }
18
+
19
+ export const readAndEmitEventStream = (filename, delayIntervalMs = 0) => {
20
+ const ev = new EventEmitter()
21
+ const fireEvents = async () => {
22
+ const fileStream = createReadStream(filename)
23
+ const rl = createInterface({ input: fileStream, crlfDelay: Infinity })
24
+ for await (const line of rl) {
25
+ if (!line) continue
26
+ const { event, data } = JSON.parse(line)
27
+ ev.emit(event, data)
28
+ if (delayIntervalMs) await delay(delayIntervalMs)
29
+ }
30
+ fileStream.destroy()
31
+ }
32
+ return { ev, task: fireEvents() }
33
+ }
@@ -0,0 +1,41 @@
1
+ import { proto } from '../../WAProto/index.js'
2
+ import { BOT_RENDERING_CONFIG_METADATA } from '../Defaults/index.js'
3
+
4
+ export const BotCapabilityType = proto.BotCapabilityMetadata.BotCapabilityType
5
+ export const RichSubMessageType = proto.AIRichResponseSubMessageType
6
+
7
+ const capabilityNames = new Set(Object.keys(BotCapabilityType).filter(n => Number.isNaN(Number(n))))
8
+
9
+ export const normalizeBotCapabilities = (capabilities = []) => {
10
+ if (!Array.isArray(capabilities)) throw new TypeError('capabilities must be an array')
11
+ const values = capabilities.map(c => {
12
+ if (typeof c === 'string') { if (!capabilityNames.has(c)) throw new TypeError(`Unknown bot capability: ${c}`); return BotCapabilityType[c] }
13
+ if (Number.isInteger(c) && BotCapabilityType[c] !== undefined) return c
14
+ throw new TypeError(`Invalid bot capability: ${String(c)}`)
15
+ })
16
+ return [...new Set(values)]
17
+ }
18
+
19
+ export const buildBotCapabilityMetadata = (capabilities = []) => ({ capabilities: normalizeBotCapabilities(capabilities) })
20
+
21
+ // Use AIRich builder for complex multi-section responses
22
+ export const buildBotRichResponse = ({ text, submessages, capabilities = [], botMetadata = {}, botJid = '867051314767696@bot', richResponse = {} } = {}) => {
23
+ const resolved = submessages || (text == null ? [] : [{ messageType: proto.AIRichResponseSubMessageType.AI_RICH_RESPONSE_TEXT, messageText: String(text) }])
24
+ return {
25
+ messageContextInfo: {
26
+ botMetadata: { ...botMetadata, capabilityMetadata: buildBotCapabilityMetadata(capabilities), botRenderingConfigMetadata: BOT_RENDERING_CONFIG_METADATA }
27
+ },
28
+ botForwardedMessage: {
29
+ message: {
30
+ richResponseMessage: {
31
+ messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD,
32
+ submessages: resolved,
33
+ ...richResponse,
34
+ contextInfo: { isForwarded: true, forwardingScore: 1, forwardedAiBotMessageInfo: { botJid }, forwardOrigin: 4, ...(richResponse.contextInfo || {}) }
35
+ }
36
+ }
37
+ }
38
+ }
39
+ }
40
+
41
+ export const capability = name => { if (!capabilityNames.has(name)) throw new TypeError(`Unknown bot capability: ${name}`); return BotCapabilityType[name] }
@@ -0,0 +1,44 @@
1
+ import { buildPlainPlaceholder, PlanningStepStatus } from './meta-compositing.js'
2
+ import { delay } from './generics.js'
3
+
4
+ // Live planning animation: shows pending steps, edits each to DONE one-by-one,
5
+ // deletes placeholder, then sends the final message. Works on all WA clients.
6
+ export const replayPlanning = async (sock, jid, steps, finalContent, { description = 'Thinking…', placeholderText = '', stepDelayMs = 900, finalPauseMs = 600, abortOnDisconnect = true, sendOptions = {} } = {}) => {
7
+ if (!steps?.length) throw new Error('replayPlanning: steps must have at least one entry')
8
+
9
+ let aborted = false
10
+ if (abortOnDisconnect) sock.ev?.once?.('connection.update', ({ connection }) => { if (connection === 'close') aborted = true })
11
+
12
+ await sock.sendPresenceUpdate('composing', jid)
13
+
14
+ const initial = steps.map(s => ({ ...s, status: PlanningStepStatus.IN_PROGRESS }))
15
+ const placeholder = await sock.sendMessage(jid, buildPlainPlaceholder(description, initial, placeholderText))
16
+ const key = placeholder?.key
17
+
18
+ try {
19
+ const current = [...initial]
20
+ for (let i = 0; i < current.length; i++) {
21
+ if (aborted) break
22
+ await delay(stepDelayMs)
23
+ if (aborted) break
24
+ current[i] = { ...current[i], status: PlanningStepStatus.DONE }
25
+ if (key) await sock.sendMessage(jid, { edit: key, ...buildPlainPlaceholder(description, current, placeholderText) })
26
+ }
27
+ if (!aborted && finalPauseMs > 0) await delay(finalPauseMs)
28
+ if (key && !aborted) await sock.sendMessage(jid, { delete: key })
29
+ } catch (_) {
30
+ try { if (key) await sock.sendMessage(jid, { delete: key }) } catch (__) { }
31
+ }
32
+
33
+ await sock.sendPresenceUpdate('paused', jid)
34
+ if (sendOptions._skipFinalSend) return placeholder
35
+ return sock.sendMessage(jid, finalContent, sendOptions)
36
+ }
37
+
38
+ // Animation without a final message
39
+ export const replayPlanningOnly = (sock, jid, steps, options = {}) =>
40
+ replayPlanning(sock, jid, steps, null, { ...options, sendOptions: { ...options.sendOptions, _skipFinalSend: true } })
41
+
42
+ export const buildReasoningSteps = titles => titles.map(title => ({ title, isReasoning: true }))
43
+ export const buildSearchSteps = titles => titles.map(title => ({ title, isEnhancedSearch: true }))
44
+ export const mixedSteps = defs => defs.map(({ title, body, type }) => ({ title, ...(body ? { body } : {}), ...(type === 'reasoning' ? { isReasoning: true } : {}), ...(type === 'search' ? { isEnhancedSearch: true } : {}) }))
@@ -0,0 +1,30 @@
1
+ import { platform, release } from 'os'
2
+ import { proto } from '../../WAProto/index.js'
3
+
4
+ const PLATFORM_MAP = {
5
+ aix: 'AIX', darwin: 'Mac OS', win32: 'Windows', android: 'Android',
6
+ freebsd: 'FreeBSD', openbsd: 'OpenBSD', sunos: 'Solaris',
7
+ linux: undefined, haiku: undefined, cygwin: undefined, netbsd: undefined
8
+ }
9
+
10
+ export const Browsers = {
11
+ ubuntu: browser => ['Ubuntu', browser, '24.04.2'],
12
+ macOS: browser => ['Mac OS', browser, '15.4.1'],
13
+ baileys: browser => ['Baileys', browser, '6.5.0'],
14
+ windows: browser => ['Windows', browser, '10.0.26100'],
15
+ android: browser => [browser, 'Android', ''],
16
+ ios: browser => ['Mac OS', browser, '18.4'],
17
+ ipad: browser => ['iPadOS', browser, '18.4'],
18
+ appropriate: browser => [PLATFORM_MAP[platform()] || 'Ubuntu', browser, release()]
19
+ }
20
+
21
+ export const getPlatformType = (browser) => {
22
+ const upper = browser.toUpperCase()
23
+ if (upper === 'ANDROID') return proto.DeviceProps.PlatformType.ANDROID_PHONE
24
+ if (upper === 'IPAD') return proto.DeviceProps.PlatformType.IPAD
25
+ if (upper === 'IOS') return proto.DeviceProps.PlatformType.IOS_PHONE
26
+ if (upper === 'DESKTOP') return proto.DeviceProps.PlatformType.DESKTOP
27
+ return proto.DeviceProps.PlatformType[upper] ?? proto.DeviceProps.PlatformType.CHROME
28
+ }
29
+
30
+ export const isAndroidBrowser = browser => browser[1]?.toUpperCase() === 'ANDROID'
@@ -0,0 +1,75 @@
1
+ import { Boom } from '@hapi/boom'
2
+ import { createHash } from 'crypto'
3
+ import { getBinaryNodeChild, getBinaryNodeChildren, getBinaryNodeChildString } from '../WABinary/index.js'
4
+ import { getStream, getUrlFromDirectPath, toReadable } from './messages-media.js'
5
+
6
+ export const parseCatalogNode = node => {
7
+ const catalogNode = getBinaryNodeChild(node, 'product_catalog')
8
+ const paging = getBinaryNodeChild(catalogNode, 'paging')
9
+ return { products: getBinaryNodeChildren(catalogNode, 'product').map(parseProductNode), nextPageCursor: paging ? getBinaryNodeChildString(paging, 'after') : undefined }
10
+ }
11
+
12
+ export const parseCollectionsNode = node => {
13
+ const collectionsNode = getBinaryNodeChild(node, 'collections')
14
+ return { collections: getBinaryNodeChildren(collectionsNode, 'collection').map(collectionNode => ({ id: getBinaryNodeChildString(collectionNode, 'id'), name: getBinaryNodeChildString(collectionNode, 'name'), products: getBinaryNodeChildren(collectionNode, 'product').map(parseProductNode), status: parseStatusInfo(collectionNode) })) }
15
+ }
16
+
17
+ export const parseOrderDetailsNode = node => {
18
+ const orderNode = getBinaryNodeChild(node, 'order')
19
+ const priceNode = getBinaryNodeChild(orderNode, 'price')
20
+ const products = getBinaryNodeChildren(orderNode, 'product').map(productNode => {
21
+ const imageNode = getBinaryNodeChild(productNode, 'image')
22
+ return { id: getBinaryNodeChildString(productNode, 'id'), name: getBinaryNodeChildString(productNode, 'name'), imageUrl: getBinaryNodeChildString(imageNode, 'url'), price: +getBinaryNodeChildString(productNode, 'price'), currency: getBinaryNodeChildString(productNode, 'currency'), quantity: +getBinaryNodeChildString(productNode, 'quantity') }
23
+ })
24
+ return { price: { total: +getBinaryNodeChildString(priceNode, 'total'), currency: getBinaryNodeChildString(priceNode, 'currency') }, products }
25
+ }
26
+
27
+ export const toProductNode = (productId, product) => {
28
+ const attrs = {}
29
+ const content = []
30
+ const push = (tag, value) => content.push({ tag, attrs: {}, content: Buffer.from(value) })
31
+ if (productId !== undefined) push('id', productId)
32
+ if (product.name !== undefined) push('name', product.name)
33
+ if (product.description !== undefined) push('description', product.description)
34
+ if (product.retailerId !== undefined) push('retailer_id', product.retailerId)
35
+ if (product.images?.length) {
36
+ content.push({
37
+ tag: 'media', attrs: {}, content: product.images.map(img => {
38
+ if (!('url' in img)) throw new Boom('Expected img for product to already be uploaded', { statusCode: 400 })
39
+ return { tag: 'image', attrs: {}, content: [{ tag: 'url', attrs: {}, content: Buffer.from(img.url.toString()) }] }
40
+ })
41
+ })
42
+ }
43
+ if (product.price !== undefined) push('price', product.price.toString())
44
+ if (product.currency !== undefined) push('currency', product.currency)
45
+ if ('originCountryCode' in product) {
46
+ if (product.originCountryCode === undefined) attrs['compliance_category'] = 'COUNTRY_ORIGIN_EXEMPT'
47
+ else content.push({ tag: 'compliance_info', attrs: {}, content: [{ tag: 'country_code_origin', attrs: {}, content: Buffer.from(product.originCountryCode) }] })
48
+ }
49
+ if (product.isHidden !== undefined) attrs['is_hidden'] = product.isHidden.toString()
50
+ return { tag: 'product', attrs, content }
51
+ }
52
+
53
+ export const parseProductNode = productNode => {
54
+ const mediaNode = getBinaryNodeChild(productNode, 'media')
55
+ const statusInfoNode = getBinaryNodeChild(productNode, 'status_info')
56
+ return { id: getBinaryNodeChildString(productNode, 'id'), imageUrls: parseImageUrls(mediaNode), reviewStatus: { whatsapp: getBinaryNodeChildString(statusInfoNode, 'status') }, availability: 'in stock', name: getBinaryNodeChildString(productNode, 'name'), retailerId: getBinaryNodeChildString(productNode, 'retailer_id'), url: getBinaryNodeChildString(productNode, 'url'), description: getBinaryNodeChildString(productNode, 'description'), price: +getBinaryNodeChildString(productNode, 'price'), currency: getBinaryNodeChildString(productNode, 'currency'), isHidden: productNode.attrs.is_hidden === 'true' }
57
+ }
58
+
59
+ export const uploadingNecessaryImagesOfProduct = async (product, waUploadToServer, timeoutMs = 30000) =>
60
+ ({ ...product, images: product.images ? await uploadingNecessaryImages(product.images, waUploadToServer, timeoutMs) : product.images })
61
+
62
+ export const uploadingNecessaryImages = (images, waUploadToServer, timeoutMs = 30000) =>
63
+ Promise.all(images.map(async img => {
64
+ if ('url' in img && img.url.toString().includes('.whatsapp.net')) return { url: img.url.toString() }
65
+ const { stream } = await getStream(img)
66
+ const hasher = createHash('sha256')
67
+ const blocks = []
68
+ for await (const block of stream) { hasher.update(block); blocks.push(block) }
69
+ const sha = hasher.digest('base64')
70
+ const { directPath } = await waUploadToServer(toReadable(Buffer.concat(blocks)), { mediaType: 'product-catalog-image', fileEncSha256B64: sha, timeoutMs })
71
+ return { url: getUrlFromDirectPath(directPath) }
72
+ }))
73
+
74
+ const parseImageUrls = mediaNode => { const imgNode = getBinaryNodeChild(mediaNode, 'image'); return { requested: getBinaryNodeChildString(imgNode, 'request_image_url'), original: getBinaryNodeChildString(imgNode, 'original_image_url') } }
75
+ const parseStatusInfo = mediaNode => { const node = getBinaryNodeChild(mediaNode, 'status_info'); return { status: getBinaryNodeChildString(node, 'status'), canAppeal: getBinaryNodeChildString(node, 'can_appeal') === 'true' } }