@zervonexx/baileys 5.0.0 → 5.0.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 (127) hide show
  1. package/LICENSE +22 -22
  2. package/README.md +4124 -4112
  3. package/WAProto/WAProto.json +1 -0
  4. package/WAProto/WAProto.proto +7160 -0
  5. package/WAProto/WAProtoCompile.js +264 -322
  6. package/WAProto/index.js +55 -95
  7. package/lib/Builders/AIRich.js +673 -673
  8. package/lib/Builders/auto.js +49 -49
  9. package/lib/Builders/base.js +144 -144
  10. package/lib/Builders/builders.js +588 -588
  11. package/lib/Builders/index.js +3 -3
  12. package/lib/Defaults/index.js +249 -248
  13. package/lib/Signal/index.js +2 -2
  14. package/lib/Signal/libsignal.js +526 -526
  15. package/lib/Signal/lid-mapping.js +282 -282
  16. package/lib/Socket/Client/index.js +1 -1
  17. package/lib/Socket/Client/types.js +9 -9
  18. package/lib/Socket/Client/websocket.js +83 -83
  19. package/lib/Socket/business.js +151 -151
  20. package/lib/Socket/chats.js +854 -854
  21. package/lib/Socket/communities.js +146 -146
  22. package/lib/Socket/groups.js +293 -293
  23. package/lib/Socket/index.js +17 -14
  24. package/lib/Socket/messages-recv.js +993 -993
  25. package/lib/Socket/messages-send.js +722 -722
  26. package/lib/Socket/mex.js +33 -33
  27. package/lib/Socket/newsletter.js +783 -783
  28. package/lib/Socket/registration.js +154 -154
  29. package/lib/Socket/socket.js +797 -797
  30. package/lib/Socket/spam-report.js +143 -143
  31. package/lib/Socket/username.js +81 -81
  32. package/lib/Socket/zervonex-handler.js +57 -57
  33. package/lib/Store/index.js +6 -6
  34. package/lib/Store/make-cache-manager-store.js +80 -80
  35. package/lib/Store/make-in-memory-store.js +426 -426
  36. package/lib/Store/make-ordered-dictionary.js +81 -81
  37. package/lib/Store/object-repository.js +30 -30
  38. package/lib/Store/reporting-info-store.js +37 -37
  39. package/lib/Types/Auth.js +1 -1
  40. package/lib/Types/Bussines.js +1 -1
  41. package/lib/Types/Call.js +1 -1
  42. package/lib/Types/Chat.js +7 -7
  43. package/lib/Types/Contact.js +1 -1
  44. package/lib/Types/Events.js +1 -1
  45. package/lib/Types/GroupMetadata.js +1 -1
  46. package/lib/Types/Label.js +24 -24
  47. package/lib/Types/LabelAssociation.js +6 -6
  48. package/lib/Types/Message.js +14 -14
  49. package/lib/Types/Newsletter.js +99 -99
  50. package/lib/Types/Product.js +1 -1
  51. package/lib/Types/Signal.js +1 -1
  52. package/lib/Types/Socket.js +14 -14
  53. package/lib/Types/State.js +26 -26
  54. package/lib/Types/USync.js +1 -1
  55. package/lib/Types/index.js +30 -30
  56. package/lib/Utils/auth-utils.js +159 -159
  57. package/lib/Utils/baileys-event-stream.js +32 -32
  58. package/lib/Utils/bot-capabilities.js +40 -40
  59. package/lib/Utils/bot-planning-replay.js +43 -43
  60. package/lib/Utils/browser-utils.js +29 -29
  61. package/lib/Utils/business.js +74 -74
  62. package/lib/Utils/chat-utils.js +316 -316
  63. package/lib/Utils/companion-reg-client-utils.js +19 -19
  64. package/lib/Utils/consumer-application.js +37 -37
  65. package/lib/Utils/crypto.js +52 -52
  66. package/lib/Utils/cstoken.js +14 -14
  67. package/lib/Utils/decode-wa-message.js +199 -199
  68. package/lib/Utils/event-buffer.js +272 -272
  69. package/lib/Utils/extras.js +186 -186
  70. package/lib/Utils/generics.js +195 -194
  71. package/lib/Utils/history.js +50 -50
  72. package/lib/Utils/identity-change-handler.js +18 -18
  73. package/lib/Utils/index.js +40 -40
  74. package/lib/Utils/link-preview.js +50 -50
  75. package/lib/Utils/logger.js +3 -2
  76. package/lib/Utils/lt-hash.js +3 -3
  77. package/lib/Utils/make-mutex.js +15 -15
  78. package/lib/Utils/message-composer.js +61 -61
  79. package/lib/Utils/message-retry-manager.js +47 -47
  80. package/lib/Utils/messages-media.js +501 -501
  81. package/lib/Utils/messages.js +944 -942
  82. package/lib/Utils/meta-ai-msmsg.js +121 -121
  83. package/lib/Utils/meta-compositing.js +74 -74
  84. package/lib/Utils/modern-messages.js +234 -234
  85. package/lib/Utils/native-flow.js +80 -80
  86. package/lib/Utils/noise-handler.js +160 -160
  87. package/lib/Utils/pre-key-manager.js +75 -75
  88. package/lib/Utils/process-message.js +400 -400
  89. package/lib/Utils/reporting-utils.js +170 -170
  90. package/lib/Utils/signal.js +166 -166
  91. package/lib/Utils/spam-report-utils.js +165 -165
  92. package/lib/Utils/sync-action-utils.js +33 -33
  93. package/lib/Utils/tc-token-utils.js +153 -153
  94. package/lib/Utils/use-keyv-auth-state.js +199 -199
  95. package/lib/Utils/use-multi-file-auth-state.js +83 -83
  96. package/lib/Utils/validate-connection.js +171 -171
  97. package/lib/WABinary/constants.js +1320 -1320
  98. package/lib/WABinary/decode.js +151 -151
  99. package/lib/WABinary/encode.js +139 -139
  100. package/lib/WABinary/generic-utils.js +202 -202
  101. package/lib/WABinary/index.js +6 -6
  102. package/lib/WABinary/jid-utils.js +235 -235
  103. package/lib/WABinary/types.js +4 -4
  104. package/lib/WAM/BinaryInfo.js +9 -9
  105. package/lib/WAM/constants.js +22852 -22852
  106. package/lib/WAM/encode.js +149 -149
  107. package/lib/WAM/index.js +3 -3
  108. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +30 -30
  109. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +48 -48
  110. package/lib/WAUSync/Protocols/USyncContactProtocol.js +23 -23
  111. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +28 -28
  112. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +15 -15
  113. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +24 -24
  114. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +9 -9
  115. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +21 -21
  116. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +19 -19
  117. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +19 -19
  118. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +22 -22
  119. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +16 -16
  120. package/lib/WAUSync/Protocols/index.js +12 -12
  121. package/lib/WAUSync/USyncQuery.js +88 -88
  122. package/lib/WAUSync/USyncUser.js +20 -20
  123. package/lib/WAUSync/index.js +3 -3
  124. package/lib/index.js +66 -66
  125. package/package.json +187 -192
  126. package/WAProto/fetcher.js +0 -68
  127. package/WAProto/parser.js +0 -334
@@ -1,144 +1,144 @@
1
- import { createReportingInfoStore } from '../Store/index.js'
2
- import { SPAM_FLOWS, REPORT_REASON_CODES, resolveReportContext, buildSpamReportIq, buildSimpleReportNode, parseSpamReportResponse } from '../Utils/index.js'
3
- import { isJidGroup, isPnUser, isLidUser, jidNormalizedUser, S_WHATSAPP_NET } from '../WABinary/index.js'
4
-
5
- export const makeSpamReportSocket = (sock, config) => {
6
- const { query, generateMessageTag, signalRepository, logger } = sock
7
- const store = config.reportingInfoStore ?? createReportingInfoStore()
8
-
9
- if (!signalRepository?.lidMapping) logger?.warn?.({}, 'makeSpamReportSocket: signalRepository.lidMapping unavailable — LID resolution disabled')
10
-
11
- const simpleReportQuery = (jid, messageKeys) => query({
12
- tag: 'iq',
13
- attrs: { type: 'set', xmlns: 'spam', to: S_WHATSAPP_NET },
14
- content: [buildSimpleReportNode(jid, messageKeys)],
15
- })
16
-
17
- const wReportQuery = async (node, label, meta, waitForAckMs = 5000) => {
18
- try {
19
- await query(node, waitForAckMs)
20
- logger?.info?.(meta, `${label} (ack received)`)
21
- return true
22
- } catch (err) {
23
- const code = err?.output?.statusCode || err?.statusCode
24
- if (code === 408 || err?.message?.toLowerCase?.().includes('timed out')) {
25
- logger?.warn?.(meta, `${label} (no ack; request likely sent)`)
26
- return false
27
- }
28
- throw err
29
- }
30
- }
31
-
32
- const resolveToPN = async jid => {
33
- if (!isLidUser(jid)) return jidNormalizedUser(jid)
34
- const pn = await signalRepository?.lidMapping?.getPNForLID?.(jid)
35
- if (!pn) {
36
- logger?.error?.({ jid }, 'resolveToPN: could not resolve LID to PN')
37
- throw new Error(`resolveToPN: no PN found for LID ${jid}`)
38
- }
39
- logger?.debug?.({ lid: jid, pn }, 'resolveToPN: resolved LID → PN')
40
- return jidNormalizedUser(pn)
41
- }
42
-
43
- const reportSpam = async (jid, options = {}) => {
44
- const { spamFlow: manualFlow, messages: manualMessages, maxMessages = 5 } = options
45
- const { reportJid, spamFlow: autoFlow, isGroup } = await resolveReportContext(jid, signalRepository?.lidMapping)
46
- const spamFlow = manualFlow ?? autoFlow
47
- let messages = manualMessages
48
- if (!messages?.length) {
49
- messages = store.getForJid(reportJid, maxMessages)
50
- if (!messages.length && !isGroup) {
51
- messages = store.getForJid(jid, maxMessages)
52
- if (messages.length) logger?.debug?.({ jid, reportJid }, 'reportSpam: fell back to raw JID for store lookup')
53
- }
54
- }
55
- if (!messages?.length) {
56
- logger?.error?.({ jid, reportJid }, 'reportSpam: no reporting_tag stored — receive at least one message first')
57
- throw new Error(`reportSpam: no reporting_tag stored for ${jid}`)
58
- }
59
- const normalized = messages.slice(0, maxMessages).map(m => ({
60
- stanzaId: m.stanzaId || m.id,
61
- timestamp: Number(m.timestamp || m.sendTimestamp || m.t) || Math.floor(Date.now() / 1000),
62
- reportingTag: m.reportingTag || m.tag,
63
- text: m.text != null ? String(m.text) : m.raw != null ? String(m.raw) : '',
64
- pushName: m.pushName || m.reportedPushName || '',
65
- messageType: m.messageType || m.type || 'text',
66
- fromJid: m.fromJid || m.from || reportJid,
67
- }))
68
- logger?.debug?.({ jid: reportJid, spamFlow, count: normalized.length }, 'reportSpam: raw sending IQ')
69
- const result = await query(buildSpamReportIq(reportJid, normalized, spamFlow, logger))
70
- return { ...parseSpamReportResponse(result), messageCount: normalized.length }
71
- }
72
-
73
- const reportContact = async (jid, messageKeys = []) => {
74
- if (!isPnUser(jid) && !isLidUser(jid)) {
75
- logger?.error?.({ jid }, 'reportContact: invalid contact JID')
76
- throw new Error('reportContact requires a valid contact JID')
77
- }
78
- const pnJid = await resolveToPN(jid)
79
- return parseSpamReportResponse(await simpleReportQuery(pnJid, messageKeys))
80
- }
81
-
82
- const reportGroup = async (jid, messageKeys = []) => {
83
- if (!isJidGroup(jid)) {
84
- logger?.error?.({ jid }, 'reportGroup: invalid group JID')
85
- throw new Error('reportGroup requires a valid group JID')
86
- }
87
- const parsed = parseSpamReportResponse(await simpleReportQuery(jid, messageKeys))
88
- if (parsed.success) {
89
- try {
90
- await query({ tag: 'iq', attrs: { type: 'set', xmlns: 'w:g2', to: '@g.us' }, content: [{ tag: 'leave', attrs: {}, content: [{ tag: 'group', attrs: { id: jid } }] }] })
91
- logger?.info?.({ jid }, 'reportGroup: left group after successful report')
92
- } catch (err) {
93
- logger?.warn?.({ jid, err: err?.message }, 'reportGroup: leave failed after successful report')
94
- }
95
- }
96
- return parsed
97
- }
98
-
99
- const reportUser = async (jid, reason = 'spam', waitForAckMs = 5000) => {
100
- const pnJid = await resolveToPN(jid)
101
- return wReportQuery(
102
- { tag: 'iq', attrs: { id: generateMessageTag(), xmlns: 'w:report', to: 's.whatsapp.net', type: 'set' }, content: [{ tag: 'user', attrs: { jid: pnJid, reason: String(REPORT_REASON_CODES[reason] ?? 1) } }] },
103
- 'reported user', { jid: pnJid, reason }, waitForAckMs,
104
- )
105
- }
106
-
107
- const reportMessage = async (jid, messageId, reason = 'spam', participantJid, waitForAckMs = 5000) => {
108
- const pnJid = await resolveToPN(jid)
109
- const participant = participantJid ? await resolveToPN(participantJid) : undefined
110
- const attrs = { id: String(messageId), reason: String(REPORT_REASON_CODES[reason] ?? 1), ...(participant ? { participant } : {}) }
111
- return wReportQuery(
112
- { tag: 'iq', attrs: { id: generateMessageTag(), xmlns: 'w:report', to: 's.whatsapp.net', type: 'set' }, content: [{ tag: 'message', attrs }] },
113
- 'reported message', { jid: pnJid, messageId, reason, participant }, waitForAckMs,
114
- )
115
- }
116
-
117
- const reportAndBlockUser = async (jid, reason = 'spam', options = {}) => {
118
- const { waitForAckMs = 5000, maxAttempts = 4, delayMs = 1500 } = options
119
- const pnJid = await resolveToPN(jid)
120
- let attempts = 0
121
- while (attempts < maxAttempts) {
122
- await reportUser(pnJid, reason, waitForAckMs)
123
- attempts++
124
- logger?.debug?.({ jid: pnJid, attempts }, 'reportAndBlockUser: attempt sent')
125
- await new Promise(r => setTimeout(r, delayMs))
126
- }
127
- return { attempts }
128
- }
129
-
130
- return {
131
- ...sock,
132
- reportSpam,
133
- reportContact,
134
- reportGroup,
135
- reportUser,
136
- reportMessage,
137
- reportAndBlockUser,
138
- getStoredReportingInfo: (jid, max = 5) => store.getForJid(jid, max),
139
- clearStoredReportingInfo: jid => store.clear(jid),
140
- reportingInfoStore: store,
141
- SPAM_FLOWS,
142
- REPORT_REASON_CODES,
143
- }
1
+ import { createReportingInfoStore } from '../Store/index.js'
2
+ import { SPAM_FLOWS, REPORT_REASON_CODES, resolveReportContext, buildSpamReportIq, buildSimpleReportNode, parseSpamReportResponse } from '../Utils/index.js'
3
+ import { isJidGroup, isPnUser, isLidUser, jidNormalizedUser, S_WHATSAPP_NET } from '../WABinary/index.js'
4
+
5
+ export const makeSpamReportSocket = (sock, config) => {
6
+ const { query, generateMessageTag, signalRepository, logger } = sock
7
+ const store = config.reportingInfoStore ?? createReportingInfoStore()
8
+
9
+ if (!signalRepository?.lidMapping) logger?.warn?.({}, 'makeSpamReportSocket: signalRepository.lidMapping unavailable — LID resolution disabled')
10
+
11
+ const simpleReportQuery = (jid, messageKeys) => query({
12
+ tag: 'iq',
13
+ attrs: { type: 'set', xmlns: 'spam', to: S_WHATSAPP_NET },
14
+ content: [buildSimpleReportNode(jid, messageKeys)],
15
+ })
16
+
17
+ const wReportQuery = async (node, label, meta, waitForAckMs = 5000) => {
18
+ try {
19
+ await query(node, waitForAckMs)
20
+ logger?.info?.(meta, `${label} (ack received)`)
21
+ return true
22
+ } catch (err) {
23
+ const code = err?.output?.statusCode || err?.statusCode
24
+ if (code === 408 || err?.message?.toLowerCase?.().includes('timed out')) {
25
+ logger?.warn?.(meta, `${label} (no ack; request likely sent)`)
26
+ return false
27
+ }
28
+ throw err
29
+ }
30
+ }
31
+
32
+ const resolveToPN = async jid => {
33
+ if (!isLidUser(jid)) return jidNormalizedUser(jid)
34
+ const pn = await signalRepository?.lidMapping?.getPNForLID?.(jid)
35
+ if (!pn) {
36
+ logger?.error?.({ jid }, 'resolveToPN: could not resolve LID to PN')
37
+ throw new Error(`resolveToPN: no PN found for LID ${jid}`)
38
+ }
39
+ logger?.debug?.({ lid: jid, pn }, 'resolveToPN: resolved LID → PN')
40
+ return jidNormalizedUser(pn)
41
+ }
42
+
43
+ const reportSpam = async (jid, options = {}) => {
44
+ const { spamFlow: manualFlow, messages: manualMessages, maxMessages = 5 } = options
45
+ const { reportJid, spamFlow: autoFlow, isGroup } = await resolveReportContext(jid, signalRepository?.lidMapping)
46
+ const spamFlow = manualFlow ?? autoFlow
47
+ let messages = manualMessages
48
+ if (!messages?.length) {
49
+ messages = store.getForJid(reportJid, maxMessages)
50
+ if (!messages.length && !isGroup) {
51
+ messages = store.getForJid(jid, maxMessages)
52
+ if (messages.length) logger?.debug?.({ jid, reportJid }, 'reportSpam: fell back to raw JID for store lookup')
53
+ }
54
+ }
55
+ if (!messages?.length) {
56
+ logger?.error?.({ jid, reportJid }, 'reportSpam: no reporting_tag stored — receive at least one message first')
57
+ throw new Error(`reportSpam: no reporting_tag stored for ${jid}`)
58
+ }
59
+ const normalized = messages.slice(0, maxMessages).map(m => ({
60
+ stanzaId: m.stanzaId || m.id,
61
+ timestamp: Number(m.timestamp || m.sendTimestamp || m.t) || Math.floor(Date.now() / 1000),
62
+ reportingTag: m.reportingTag || m.tag,
63
+ text: m.text != null ? String(m.text) : m.raw != null ? String(m.raw) : '',
64
+ pushName: m.pushName || m.reportedPushName || '',
65
+ messageType: m.messageType || m.type || 'text',
66
+ fromJid: m.fromJid || m.from || reportJid,
67
+ }))
68
+ logger?.debug?.({ jid: reportJid, spamFlow, count: normalized.length }, 'reportSpam: raw sending IQ')
69
+ const result = await query(buildSpamReportIq(reportJid, normalized, spamFlow, logger))
70
+ return { ...parseSpamReportResponse(result), messageCount: normalized.length }
71
+ }
72
+
73
+ const reportContact = async (jid, messageKeys = []) => {
74
+ if (!isPnUser(jid) && !isLidUser(jid)) {
75
+ logger?.error?.({ jid }, 'reportContact: invalid contact JID')
76
+ throw new Error('reportContact requires a valid contact JID')
77
+ }
78
+ const pnJid = await resolveToPN(jid)
79
+ return parseSpamReportResponse(await simpleReportQuery(pnJid, messageKeys))
80
+ }
81
+
82
+ const reportGroup = async (jid, messageKeys = []) => {
83
+ if (!isJidGroup(jid)) {
84
+ logger?.error?.({ jid }, 'reportGroup: invalid group JID')
85
+ throw new Error('reportGroup requires a valid group JID')
86
+ }
87
+ const parsed = parseSpamReportResponse(await simpleReportQuery(jid, messageKeys))
88
+ if (parsed.success) {
89
+ try {
90
+ await query({ tag: 'iq', attrs: { type: 'set', xmlns: 'w:g2', to: '@g.us' }, content: [{ tag: 'leave', attrs: {}, content: [{ tag: 'group', attrs: { id: jid } }] }] })
91
+ logger?.info?.({ jid }, 'reportGroup: left group after successful report')
92
+ } catch (err) {
93
+ logger?.warn?.({ jid, err: err?.message }, 'reportGroup: leave failed after successful report')
94
+ }
95
+ }
96
+ return parsed
97
+ }
98
+
99
+ const reportUser = async (jid, reason = 'spam', waitForAckMs = 5000) => {
100
+ const pnJid = await resolveToPN(jid)
101
+ return wReportQuery(
102
+ { tag: 'iq', attrs: { id: generateMessageTag(), xmlns: 'w:report', to: 's.whatsapp.net', type: 'set' }, content: [{ tag: 'user', attrs: { jid: pnJid, reason: String(REPORT_REASON_CODES[reason] ?? 1) } }] },
103
+ 'reported user', { jid: pnJid, reason }, waitForAckMs,
104
+ )
105
+ }
106
+
107
+ const reportMessage = async (jid, messageId, reason = 'spam', participantJid, waitForAckMs = 5000) => {
108
+ const pnJid = await resolveToPN(jid)
109
+ const participant = participantJid ? await resolveToPN(participantJid) : undefined
110
+ const attrs = { id: String(messageId), reason: String(REPORT_REASON_CODES[reason] ?? 1), ...(participant ? { participant } : {}) }
111
+ return wReportQuery(
112
+ { tag: 'iq', attrs: { id: generateMessageTag(), xmlns: 'w:report', to: 's.whatsapp.net', type: 'set' }, content: [{ tag: 'message', attrs }] },
113
+ 'reported message', { jid: pnJid, messageId, reason, participant }, waitForAckMs,
114
+ )
115
+ }
116
+
117
+ const reportAndBlockUser = async (jid, reason = 'spam', options = {}) => {
118
+ const { waitForAckMs = 5000, maxAttempts = 4, delayMs = 1500 } = options
119
+ const pnJid = await resolveToPN(jid)
120
+ let attempts = 0
121
+ while (attempts < maxAttempts) {
122
+ await reportUser(pnJid, reason, waitForAckMs)
123
+ attempts++
124
+ logger?.debug?.({ jid: pnJid, attempts }, 'reportAndBlockUser: attempt sent')
125
+ await new Promise(r => setTimeout(r, delayMs))
126
+ }
127
+ return { attempts }
128
+ }
129
+
130
+ return {
131
+ ...sock,
132
+ reportSpam,
133
+ reportContact,
134
+ reportGroup,
135
+ reportUser,
136
+ reportMessage,
137
+ reportAndBlockUser,
138
+ getStoredReportingInfo: (jid, max = 5) => store.getForJid(jid, max),
139
+ clearStoredReportingInfo: jid => store.clear(jid),
140
+ reportingInfoStore: store,
141
+ SPAM_FLOWS,
142
+ REPORT_REASON_CODES,
143
+ }
144
144
  }
@@ -1,82 +1,82 @@
1
- import { randomUUID } from 'crypto';
2
- import { executeWMexQuery } from './mex.js';
3
- import { USyncQuery, USyncUser } from '../WAUSync/index.js';
4
- import { makeRegistrationSocket } from './registration.js';
5
- import { makeSpamReportSocket } from './spam-report.js';
6
- import { USERNAME_QUERY_IDS, USERNAME_CHECK_RESULT, USERNAME_SOURCE } from '../Defaults/index.js';
7
-
8
- export const makeUsernameSocket = config => {
9
- const sock = makeRegistrationSocket(config);
10
- const { query, generateMessageTag, executeUSyncQuery } = sock;
11
-
12
- const mexQuery = (variables, queryId, dataPath) => executeWMexQuery(variables, queryId, dataPath, query, generateMessageTag);
13
-
14
- const checkUsername = async (username, includeSuggestions = true, sessionId) => {
15
- const session_id = sessionId || randomUUID();
16
- const data = await mexQuery({ username, include_suggestions: includeSuggestions, session_id, source: USERNAME_SOURCE.USER_INPUT }, USERNAME_QUERY_IDS.CHECK, 'xwa2_username_check');
17
- if (data?.result === USERNAME_CHECK_RESULT.SUCCESS) return { available: true, username, session_id };
18
- return { available: false, username, session_id, suggestions: data?.suggestions ?? [], rejectionReasons: data?.rejection_reasons ?? [], suggestionsEligible: data?.suggestions_eligible ?? true };
19
- };
20
-
21
- const setUsername = async (username, options = {}) => {
22
- const { source = USERNAME_SOURCE.USER_INPUT, sessionId, pin } = options;
23
- const session_id = sessionId || randomUUID();
24
- return mexQuery({ username, reserved: true, source, session_id, ...(pin ? { pin } : {}) }, USERNAME_QUERY_IDS.SET, 'xwa2_username_set');
25
- };
26
-
27
- const checkAndSetUsername = async username => {
28
- const r = await checkUsername(username);
29
- if (r.available) return setUsername(username);
30
- return r;
31
- };
32
-
33
- const deleteUsername = async () => mexQuery({ username: null }, USERNAME_QUERY_IDS.SET, 'xwa2_username_delete');
34
-
35
- const getMyUsername = async () => {
36
- const data = await mexQuery({}, USERNAME_QUERY_IDS.GET, 'xwa2_username_get');
37
- return data?.username ?? null;
38
- };
39
-
40
- const setUsernamePin = async pin => mexQuery(pin != null ? { pin } : {}, USERNAME_QUERY_IDS.PIN_SET, 'xwa2_username_pin_set');
41
-
42
- const findUserByUsername = async (username, pin) => {
43
- const usyncQuery = new USyncQuery().withContactProtocol();
44
- const user = new USyncUser().withUsername(username);
45
- if (pin) user.withUsernameKey(pin);
46
- usyncQuery.withUser(user);
47
- const result = await executeUSyncQuery(usyncQuery);
48
- if (!result?.list?.length) return null;
49
- const entry = result.list[0];
50
- return { jid: entry.id, contact: entry.contact ?? false };
51
- };
52
-
53
- const fetchContactUsernames = async (...jids) => {
54
- const usyncQuery = new USyncQuery().withUsernameProtocol();
55
- for (const jid of jids) usyncQuery.withUser(new USyncUser().withId(jid));
56
- const result = await executeUSyncQuery(usyncQuery);
57
- return result?.list ?? [];
58
- };
59
-
60
- const checkUsernameMulti = async usernames => mexQuery({ usernames }, USERNAME_QUERY_IDS.CHECK_MULTI, 'xwa2_username_check_multi');
61
-
62
- const getUsernameRecommendations = async (source = null) => mexQuery(source ? { source } : {}, USERNAME_QUERY_IDS.GET_RECOMMENDATIONS, 'xwa2_username_get_recommendations');
63
-
64
- const base = {
65
- ...sock,
66
- checkUsername,
67
- checkUsernameMulti,
68
- setUsername,
69
- checkAndSetUsername,
70
- deleteUsername,
71
- getMyUsername,
72
- getUsernameRecommendations,
73
- setUsernamePin,
74
- findUserByUsername,
75
- fetchContactUsernames,
76
- USERNAME_QUERY_IDS,
77
- USERNAME_CHECK_RESULT,
78
- USERNAME_SOURCE
79
- };
80
-
81
- return makeSpamReportSocket(base, config);
1
+ import { randomUUID } from 'crypto';
2
+ import { executeWMexQuery } from './mex.js';
3
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
4
+ import { makeRegistrationSocket } from './registration.js';
5
+ import { makeSpamReportSocket } from './spam-report.js';
6
+ import { USERNAME_QUERY_IDS, USERNAME_CHECK_RESULT, USERNAME_SOURCE } from '../Defaults/index.js';
7
+
8
+ export const makeUsernameSocket = config => {
9
+ const sock = makeRegistrationSocket(config);
10
+ const { query, generateMessageTag, executeUSyncQuery } = sock;
11
+
12
+ const mexQuery = (variables, queryId, dataPath) => executeWMexQuery(variables, queryId, dataPath, query, generateMessageTag);
13
+
14
+ const checkUsername = async (username, includeSuggestions = true, sessionId) => {
15
+ const session_id = sessionId || randomUUID();
16
+ const data = await mexQuery({ username, include_suggestions: includeSuggestions, session_id, source: USERNAME_SOURCE.USER_INPUT }, USERNAME_QUERY_IDS.CHECK, 'xwa2_username_check');
17
+ if (data?.result === USERNAME_CHECK_RESULT.SUCCESS) return { available: true, username, session_id };
18
+ return { available: false, username, session_id, suggestions: data?.suggestions ?? [], rejectionReasons: data?.rejection_reasons ?? [], suggestionsEligible: data?.suggestions_eligible ?? true };
19
+ };
20
+
21
+ const setUsername = async (username, options = {}) => {
22
+ const { source = USERNAME_SOURCE.USER_INPUT, sessionId, pin } = options;
23
+ const session_id = sessionId || randomUUID();
24
+ return mexQuery({ username, reserved: true, source, session_id, ...(pin ? { pin } : {}) }, USERNAME_QUERY_IDS.SET, 'xwa2_username_set');
25
+ };
26
+
27
+ const checkAndSetUsername = async username => {
28
+ const r = await checkUsername(username);
29
+ if (r.available) return setUsername(username);
30
+ return r;
31
+ };
32
+
33
+ const deleteUsername = async () => mexQuery({ username: null }, USERNAME_QUERY_IDS.SET, 'xwa2_username_delete');
34
+
35
+ const getMyUsername = async () => {
36
+ const data = await mexQuery({}, USERNAME_QUERY_IDS.GET, 'xwa2_username_get');
37
+ return data?.username ?? null;
38
+ };
39
+
40
+ const setUsernamePin = async pin => mexQuery(pin != null ? { pin } : {}, USERNAME_QUERY_IDS.PIN_SET, 'xwa2_username_pin_set');
41
+
42
+ const findUserByUsername = async (username, pin) => {
43
+ const usyncQuery = new USyncQuery().withContactProtocol();
44
+ const user = new USyncUser().withUsername(username);
45
+ if (pin) user.withUsernameKey(pin);
46
+ usyncQuery.withUser(user);
47
+ const result = await executeUSyncQuery(usyncQuery);
48
+ if (!result?.list?.length) return null;
49
+ const entry = result.list[0];
50
+ return { jid: entry.id, contact: entry.contact ?? false };
51
+ };
52
+
53
+ const fetchContactUsernames = async (...jids) => {
54
+ const usyncQuery = new USyncQuery().withUsernameProtocol();
55
+ for (const jid of jids) usyncQuery.withUser(new USyncUser().withId(jid));
56
+ const result = await executeUSyncQuery(usyncQuery);
57
+ return result?.list ?? [];
58
+ };
59
+
60
+ const checkUsernameMulti = async usernames => mexQuery({ usernames }, USERNAME_QUERY_IDS.CHECK_MULTI, 'xwa2_username_check_multi');
61
+
62
+ const getUsernameRecommendations = async (source = null) => mexQuery(source ? { source } : {}, USERNAME_QUERY_IDS.GET_RECOMMENDATIONS, 'xwa2_username_get_recommendations');
63
+
64
+ const base = {
65
+ ...sock,
66
+ checkUsername,
67
+ checkUsernameMulti,
68
+ setUsername,
69
+ checkAndSetUsername,
70
+ deleteUsername,
71
+ getMyUsername,
72
+ getUsernameRecommendations,
73
+ setUsernamePin,
74
+ findUserByUsername,
75
+ fetchContactUsernames,
76
+ USERNAME_QUERY_IDS,
77
+ USERNAME_CHECK_RESULT,
78
+ USERNAME_SOURCE
79
+ };
80
+
81
+ return makeSpamReportSocket(base, config);
82
82
  };
@@ -1,58 +1,58 @@
1
- import crypto from 'crypto'
2
- import * as Builders from '../Builders/index.js'
3
- import { makeUsernameSocket } from './username.js'
4
- import { MESSAGE_HANDLER_KEYS } from '../Utils/index.js'
5
-
6
- const { buildDispatch, buildPlugins, norm, handleGroupStatus, handleStatusMention, handlePollResult, handleNativeFlow, PRIMITIVE_SHORTCUTS, HANDLER_SHORTCUTS, attachAIRich, getAutoBuilders, BaseBuilder } = Builders
7
-
8
- export const makeMessageBuilderSocket = (config) => {
9
- const sock = makeUsernameSocket(config)
10
- const _send = sock.sendMessage.bind(sock)
11
-
12
- const ALL_BUILDERS = Object.values(Builders).filter(B =>
13
- typeof B === 'function' &&
14
- /^[A-Z]/.test(B.name ?? '') &&
15
- B !== BaseBuilder
16
- )
17
- const ALL_BUILDERS_FINAL = [...ALL_BUILDERS, ...getAutoBuilders(ALL_BUILDERS, MESSAGE_HANDLER_KEYS)]
18
-
19
- const DISPATCH = buildDispatch(ALL_BUILDERS_FINAL, {
20
- groupStatus: (sock, jid, content, opts, config) => handleGroupStatus(sock, jid, norm(content.groupStatus), config),
21
- statusMentionMessage: (sock, jid, content, opts, config) => handleStatusMention(sock, jid, norm(content.statusMentionMessage), config),
22
- pollResultMessage: (sock, jid, content) => handlePollResult(sock, jid, norm(content.pollResultMessage))
23
- })
24
-
25
- const PLUGINS = buildPlugins(ALL_BUILDERS_FINAL, { ...PRIMITIVE_SHORTCUTS, ...HANDLER_SHORTCUTS })
26
-
27
- const result = { ...sock }
28
-
29
- for (const [name, factory] of Object.entries(PLUGINS)) result[name] = factory(result, config)
30
-
31
- result.sendMessage = async (jid, content, options = {}) => {
32
- if (!options.relay) {
33
- options.relay = async (message, relayOptions) =>
34
- result.relayMessage(jid, message, relayOptions)
35
- }
36
- const aiData = content.aiRich ?? content.airich ?? content.richResponse ?? content.AIRich ?? content.richMessage
37
- if (aiData) return result.sendRichFromObject(jid, Array.isArray(aiData) ? { ...content, parts: aiData } : { ...content, ...aiData }, options)
38
-
39
- for (const [key, handler] of Object.entries(DISPATCH)) {
40
- if (key in content) return handler(result, jid, content, options, config)
41
- }
42
-
43
- if (content.templateButtons) return result.sendMessage(jid, { text: content.text ?? content.caption ?? '', footer: content.footer, ...(content.image ? { image: content.image } : {}), nativeFlow: content.templateButtons.map(b => b.url ? { text: b.text, url: b.url } : b.call ? { text: b.text, call: b.call } : { text: b.text, id: b.id }) }, options)
44
- if (content.cards && !content.carouselMessage) return result.sendMessage(jid, { carouselMessage: { caption: content.text ?? content.caption ?? '', footer: content.footer, cards: content.cards } }, options)
45
- if (content.nativeFlow && !content.interactiveMessage) return handleNativeFlow(result, jid, content, options)
46
-
47
- const { ai, aiLabel: contentAiLabel, ...cleanContent } = content
48
- const isAi = !!(ai ?? contentAiLabel ?? options.aiLabel ?? options.ai ?? config.aiLabel)
49
- if (isAi) {
50
- const secret = cleanContent.messageContextInfo?.messageSecret || crypto.randomBytes(32)
51
- cleanContent.messageContextInfo = { ...(cleanContent.messageContextInfo || {}), messageSecret: secret, supportPayload: JSON.stringify({ version: 2, is_ai_message: true, should_show_system_message: true, ticket_id: crypto.randomBytes(16).toString('hex') }) }
52
- }
53
- const { relay: _relay, ...safeContent } = isAi ? cleanContent : content
54
- return _send(jid, safeContent, { ...options, aiLabel: isAi })
55
- }
56
-
57
- return attachAIRich(result, config)
1
+ import crypto from 'crypto'
2
+ import * as Builders from '../Builders/index.js'
3
+ import { makeUsernameSocket } from './username.js'
4
+ import { MESSAGE_HANDLER_KEYS } from '../Utils/index.js'
5
+
6
+ const { buildDispatch, buildPlugins, norm, handleGroupStatus, handleStatusMention, handlePollResult, handleNativeFlow, PRIMITIVE_SHORTCUTS, HANDLER_SHORTCUTS, attachAIRich, getAutoBuilders, BaseBuilder } = Builders
7
+
8
+ export const makeMessageBuilderSocket = (config) => {
9
+ const sock = makeUsernameSocket(config)
10
+ const _send = sock.sendMessage.bind(sock)
11
+
12
+ const ALL_BUILDERS = Object.values(Builders).filter(B =>
13
+ typeof B === 'function' &&
14
+ /^[A-Z]/.test(B.name ?? '') &&
15
+ B !== BaseBuilder
16
+ )
17
+ const ALL_BUILDERS_FINAL = [...ALL_BUILDERS, ...getAutoBuilders(ALL_BUILDERS, MESSAGE_HANDLER_KEYS)]
18
+
19
+ const DISPATCH = buildDispatch(ALL_BUILDERS_FINAL, {
20
+ groupStatus: (sock, jid, content, opts, config) => handleGroupStatus(sock, jid, norm(content.groupStatus), config),
21
+ statusMentionMessage: (sock, jid, content, opts, config) => handleStatusMention(sock, jid, norm(content.statusMentionMessage), config),
22
+ pollResultMessage: (sock, jid, content) => handlePollResult(sock, jid, norm(content.pollResultMessage))
23
+ })
24
+
25
+ const PLUGINS = buildPlugins(ALL_BUILDERS_FINAL, { ...PRIMITIVE_SHORTCUTS, ...HANDLER_SHORTCUTS })
26
+
27
+ const result = { ...sock }
28
+
29
+ for (const [name, factory] of Object.entries(PLUGINS)) result[name] = factory(result, config)
30
+
31
+ result.sendMessage = async (jid, content, options = {}) => {
32
+ if (!options.relay) {
33
+ options.relay = async (message, relayOptions) =>
34
+ result.relayMessage(jid, message, relayOptions)
35
+ }
36
+ const aiData = content.aiRich ?? content.airich ?? content.richResponse ?? content.AIRich ?? content.richMessage
37
+ if (aiData) return result.sendRichFromObject(jid, Array.isArray(aiData) ? { ...content, parts: aiData } : { ...content, ...aiData }, options)
38
+
39
+ for (const [key, handler] of Object.entries(DISPATCH)) {
40
+ if (key in content) return handler(result, jid, content, options, config)
41
+ }
42
+
43
+ if (content.templateButtons) return result.sendMessage(jid, { text: content.text ?? content.caption ?? '', footer: content.footer, ...(content.image ? { image: content.image } : {}), nativeFlow: content.templateButtons.map(b => b.url ? { text: b.text, url: b.url } : b.call ? { text: b.text, call: b.call } : { text: b.text, id: b.id }) }, options)
44
+ if (content.cards && !content.carouselMessage) return result.sendMessage(jid, { carouselMessage: { caption: content.text ?? content.caption ?? '', footer: content.footer, cards: content.cards } }, options)
45
+ if (content.nativeFlow && !content.interactiveMessage) return handleNativeFlow(result, jid, content, options)
46
+
47
+ const { ai, aiLabel: contentAiLabel, ...cleanContent } = content
48
+ const isAi = !!(ai ?? contentAiLabel ?? options.aiLabel ?? options.ai ?? config.aiLabel)
49
+ if (isAi) {
50
+ const secret = cleanContent.messageContextInfo?.messageSecret || crypto.randomBytes(32)
51
+ cleanContent.messageContextInfo = { ...(cleanContent.messageContextInfo || {}), messageSecret: secret, supportPayload: JSON.stringify({ version: 2, is_ai_message: true, should_show_system_message: true, ticket_id: crypto.randomBytes(16).toString('hex') }) }
52
+ }
53
+ const { relay: _relay, ...safeContent } = isAi ? cleanContent : content
54
+ return _send(jid, safeContent, { ...options, aiLabel: isAi })
55
+ }
56
+
57
+ return attachAIRich(result, config)
58
58
  }
@@ -1,6 +1,6 @@
1
- export * from './make-cache-manager-store.js'
2
- export * from './make-in-memory-store.js'
3
- export * from './make-ordered-dictionary.js'
4
- export * from './reporting-info-store.js'
5
- export { makeInMemoryStore as default } from './make-in-memory-store.js'
6
- export * from './object-repository.js'
1
+ export * from './make-cache-manager-store.js'
2
+ export * from './make-in-memory-store.js'
3
+ export * from './make-ordered-dictionary.js'
4
+ export * from './reporting-info-store.js'
5
+ export { makeInMemoryStore as default } from './make-in-memory-store.js'
6
+ export * from './object-repository.js'