@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,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
+ }
144
+ }
@@ -0,0 +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);
82
+ };
@@ -0,0 +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)
58
+ }
@@ -0,0 +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'
@@ -0,0 +1,80 @@
1
+ import * as cacheManager from 'cache-manager';
2
+ import * as WAProto from '../../WAProto/index.js';
3
+ import { BufferJSON, initAuthCreds, logger } from '../Utils/index.js';
4
+
5
+ const makeCacheManagerAuthState = async (store, sessionKey) => {
6
+ const defaultKey = (file) => `${sessionKey}:${file}`;
7
+ const databaseConn = await cacheManager.caching(store);
8
+
9
+ const writeData = async (file, data) => {
10
+ let ttl = undefined;
11
+ if (file === 'creds') {
12
+ ttl = 63115200; // 2 years
13
+ }
14
+ await databaseConn.set(defaultKey(file), JSON.stringify(data, BufferJSON.replacer), ttl);
15
+ };
16
+
17
+ const readData = async (file) => {
18
+ try {
19
+ const data = await databaseConn.get(defaultKey(file));
20
+ if (data) {
21
+ return JSON.parse(data, BufferJSON.reviver);
22
+ }
23
+ return null;
24
+ } catch (error) {
25
+ logger.error(error);
26
+ return null;
27
+ }
28
+ };
29
+
30
+ const removeData = async (file) => {
31
+ try {
32
+ return await databaseConn.del(defaultKey(file));
33
+ } catch {
34
+ logger.error(`Error removing ${file} from session ${sessionKey}`);
35
+ }
36
+ };
37
+
38
+ const clearState = async () => {
39
+ try {
40
+ const result = await databaseConn.store.keys(`${sessionKey}*`);
41
+ await Promise.all(result.map(async (key) => await databaseConn.del(key)));
42
+ } catch { }
43
+ };
44
+
45
+ const creds = (await readData('creds')) || initAuthCreds();
46
+
47
+ return {
48
+ clearState,
49
+ saveCreds: () => writeData('creds', creds),
50
+ state: {
51
+ creds,
52
+ keys: {
53
+ get: async (type, ids) => {
54
+ const data = {};
55
+ await Promise.all(ids.map(async (id) => {
56
+ let value = await readData(`${type}-${id}`);
57
+ if (type === 'app-state-sync-key' && value) {
58
+ value = WAProto.proto.Message.AppStateSyncKeyData.fromObject(value);
59
+ }
60
+ data[id] = value;
61
+ }));
62
+ return data;
63
+ },
64
+ set: async (data) => {
65
+ const tasks = [];
66
+ for (const category in data) {
67
+ for (const id in data[category]) {
68
+ const value = data[category][id];
69
+ const key = `${category}-${id}`;
70
+ tasks.push(value ? writeData(key, value) : removeData(key));
71
+ }
72
+ }
73
+ await Promise.all(tasks);
74
+ },
75
+ },
76
+ },
77
+ };
78
+ };
79
+
80
+ export { makeCacheManagerAuthState };