astrabail 1.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (224) hide show
  1. package/WAProto/GenerateStatics.sh +3 -0
  2. package/WAProto/WAProto.proto +5479 -0
  3. package/WAProto/fix-imports.js +73 -0
  4. package/WAProto/index.d.ts +14017 -0
  5. package/WAProto/index.js +89351 -0
  6. package/WAProto/p.html +1 -0
  7. package/engine-requirements.js +7 -0
  8. package/lib/Defaults/astrabail-version.json +8 -0
  9. package/lib/Defaults/index.d.ts +74 -0
  10. package/lib/Defaults/index.js +166 -0
  11. package/lib/Defaults/phonenumber-mcc.json +223 -0
  12. package/lib/Defaults/update-wa-version.js +75 -0
  13. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  14. package/lib/Signal/Group/ciphertext-message.js +15 -0
  15. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  16. package/lib/Signal/Group/group-session-builder.js +66 -0
  17. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  18. package/lib/Signal/Group/group_cipher.js +85 -0
  19. package/lib/Signal/Group/index.d.ts +12 -0
  20. package/lib/Signal/Group/index.js +57 -0
  21. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  22. package/lib/Signal/Group/keyhelper.js +55 -0
  23. package/lib/Signal/Group/queue-job.js +57 -0
  24. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  25. package/lib/Signal/Group/sender-chain-key.js +29 -0
  26. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  27. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  28. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  29. package/lib/Signal/Group/sender-key-message.js +69 -0
  30. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  31. package/lib/Signal/Group/sender-key-name.js +51 -0
  32. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  33. package/lib/Signal/Group/sender-key-record.js +44 -0
  34. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  35. package/lib/Signal/Group/sender-key-state.js +87 -0
  36. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  37. package/lib/Signal/Group/sender-message-key.js +29 -0
  38. package/lib/Signal/libsignal.d.ts +5 -0
  39. package/lib/Signal/libsignal.js +478 -0
  40. package/lib/Signal/lid-mapping.d.ts +19 -0
  41. package/lib/Signal/lid-mapping.js +274 -0
  42. package/lib/Socket/Client/index.d.ts +3 -0
  43. package/lib/Socket/Client/index.js +18 -0
  44. package/lib/Socket/Client/types.d.ts +16 -0
  45. package/lib/Socket/Client/types.js +14 -0
  46. package/lib/Socket/Client/websocket.d.ts +13 -0
  47. package/lib/Socket/Client/websocket.js +60 -0
  48. package/lib/Socket/business.d.ts +202 -0
  49. package/lib/Socket/business.js +382 -0
  50. package/lib/Socket/chats.d.ts +111 -0
  51. package/lib/Socket/chats.js +1155 -0
  52. package/lib/Socket/communities.d.ts +258 -0
  53. package/lib/Socket/communities.js +438 -0
  54. package/lib/Socket/community.js +333 -0
  55. package/lib/Socket/groups.d.ts +150 -0
  56. package/lib/Socket/groups.js +470 -0
  57. package/lib/Socket/index.d.ts +245 -0
  58. package/lib/Socket/index.js +13 -0
  59. package/lib/Socket/messages-recv.d.ts +187 -0
  60. package/lib/Socket/messages-recv.js +1708 -0
  61. package/lib/Socket/messages-send.d.ts +183 -0
  62. package/lib/Socket/messages-send.js +1692 -0
  63. package/lib/Socket/mex.d.ts +3 -0
  64. package/lib/Socket/mex.js +45 -0
  65. package/lib/Socket/newsletter.d.ts +160 -0
  66. package/lib/Socket/newsletter.js +293 -0
  67. package/lib/Socket/socket.d.ts +55 -0
  68. package/lib/Socket/socket.js +947 -0
  69. package/lib/Socket/usync.js +70 -0
  70. package/lib/Store/index.js +20 -0
  71. package/lib/Store/make-cache-manager-store.js +83 -0
  72. package/lib/Store/make-in-memory-store.js +398 -0
  73. package/lib/Store/make-ordered-dictionary.js +81 -0
  74. package/lib/Store/object-repository.js +27 -0
  75. package/lib/Types/Auth.d.ts +116 -0
  76. package/lib/Types/Auth.js +2 -0
  77. package/lib/Types/Bussines.d.ts +25 -0
  78. package/lib/Types/Bussines.js +2 -0
  79. package/lib/Types/Call.d.ts +15 -0
  80. package/lib/Types/Call.js +2 -0
  81. package/lib/Types/Chat.d.ts +123 -0
  82. package/lib/Types/Chat.js +10 -0
  83. package/lib/Types/Contact.d.ts +24 -0
  84. package/lib/Types/Contact.js +2 -0
  85. package/lib/Types/Events.d.ts +237 -0
  86. package/lib/Types/Events.js +3 -0
  87. package/lib/Types/GroupMetadata.d.ts +67 -0
  88. package/lib/Types/GroupMetadata.js +2 -0
  89. package/lib/Types/Label.d.ts +47 -0
  90. package/lib/Types/Label.js +25 -0
  91. package/lib/Types/LabelAssociation.d.ts +30 -0
  92. package/lib/Types/LabelAssociation.js +7 -0
  93. package/lib/Types/Message.d.ts +305 -0
  94. package/lib/Types/Message.js +11 -0
  95. package/lib/Types/MexUpdates.js +11 -0
  96. package/lib/Types/Newsletter.d.ts +135 -0
  97. package/lib/Types/Newsletter.js +43 -0
  98. package/lib/Types/Product.d.ts +79 -0
  99. package/lib/Types/Product.js +2 -0
  100. package/lib/Types/Signal.d.ts +76 -0
  101. package/lib/Types/Signal.js +3 -0
  102. package/lib/Types/Socket.d.ts +133 -0
  103. package/lib/Types/Socket.js +3 -0
  104. package/lib/Types/State.d.ts +39 -0
  105. package/lib/Types/State.js +14 -0
  106. package/lib/Types/USync.d.ts +26 -0
  107. package/lib/Types/USync.js +3 -0
  108. package/lib/Types/index.d.ts +65 -0
  109. package/lib/Types/index.js +42 -0
  110. package/lib/Utils/astrabail-event-stream.js +3 -0
  111. package/lib/Utils/audioToBuffer.js +31 -0
  112. package/lib/Utils/auth-utils.d.ts +19 -0
  113. package/lib/Utils/auth-utils.js +298 -0
  114. package/lib/Utils/baileys-event-stream.js +60 -0
  115. package/lib/Utils/bridge-runtime.d.ts +1 -0
  116. package/lib/Utils/bridge-runtime.js +14 -0
  117. package/lib/Utils/browser-utils.d.ts +4 -0
  118. package/lib/Utils/browser-utils.js +44 -0
  119. package/lib/Utils/business.d.ts +23 -0
  120. package/lib/Utils/business.js +240 -0
  121. package/lib/Utils/chat-utils.d.ts +70 -0
  122. package/lib/Utils/chat-utils.js +825 -0
  123. package/lib/Utils/crypto.d.ts +37 -0
  124. package/lib/Utils/crypto.js +168 -0
  125. package/lib/Utils/decode-wa-message.d.ts +48 -0
  126. package/lib/Utils/decode-wa-message.js +287 -0
  127. package/lib/Utils/event-buffer.d.ts +34 -0
  128. package/lib/Utils/event-buffer.js +580 -0
  129. package/lib/Utils/generics.d.ts +91 -0
  130. package/lib/Utils/generics.js +483 -0
  131. package/lib/Utils/history.d.ts +22 -0
  132. package/lib/Utils/history.js +137 -0
  133. package/lib/Utils/identity-change-handler.d.ts +37 -0
  134. package/lib/Utils/identity-change-handler.js +54 -0
  135. package/lib/Utils/index.d.ts +22 -0
  136. package/lib/Utils/index.js +48 -0
  137. package/lib/Utils/link-preview.d.ts +21 -0
  138. package/lib/Utils/link-preview.js +121 -0
  139. package/lib/Utils/logger.d.ts +13 -0
  140. package/lib/Utils/logger.js +7 -0
  141. package/lib/Utils/lt-hash.d.ts +8 -0
  142. package/lib/Utils/lt-hash.js +10 -0
  143. package/lib/Utils/make-mutex.d.ts +9 -0
  144. package/lib/Utils/make-mutex.js +37 -0
  145. package/lib/Utils/message-retry-manager.d.ts +110 -0
  146. package/lib/Utils/message-retry-manager.js +226 -0
  147. package/lib/Utils/messages-media.d.ts +130 -0
  148. package/lib/Utils/messages-media.js +887 -0
  149. package/lib/Utils/messages-newsletter.d.ts +84 -0
  150. package/lib/Utils/messages-newsletter.js +295 -0
  151. package/lib/Utils/messages.d.ts +92 -0
  152. package/lib/Utils/messages.js +1752 -0
  153. package/lib/Utils/noise-handler.d.ts +20 -0
  154. package/lib/Utils/noise-handler.js +204 -0
  155. package/lib/Utils/pre-key-manager.d.ts +28 -0
  156. package/lib/Utils/pre-key-manager.js +112 -0
  157. package/lib/Utils/process-message.d.ts +60 -0
  158. package/lib/Utils/process-message.js +536 -0
  159. package/lib/Utils/reporting-utils.d.ts +11 -0
  160. package/lib/Utils/reporting-utils.js +262 -0
  161. package/lib/Utils/resolve-jid.d.ts +43 -0
  162. package/lib/Utils/resolve-jid.js +95 -0
  163. package/lib/Utils/rust-bridge-shim.d.ts +22 -0
  164. package/lib/Utils/rust-bridge-shim.js +70 -0
  165. package/lib/Utils/serial-task-queue.js +29 -0
  166. package/lib/Utils/signal.d.ts +34 -0
  167. package/lib/Utils/signal.js +170 -0
  168. package/lib/Utils/streamToBuffer.js +17 -0
  169. package/lib/Utils/sync-action-utils.d.ts +19 -0
  170. package/lib/Utils/sync-action-utils.js +52 -0
  171. package/lib/Utils/tc-token-utils.d.ts +12 -0
  172. package/lib/Utils/tc-token-utils.js +20 -0
  173. package/lib/Utils/use-mongo-file-auth-state.js +71 -0
  174. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  175. package/lib/Utils/use-multi-file-auth-state.js +124 -0
  176. package/lib/Utils/use-single-file-auth-state.js +73 -0
  177. package/lib/Utils/validate-connection.d.ts +11 -0
  178. package/lib/Utils/validate-connection.js +206 -0
  179. package/lib/WABinary/constants.d.ts +28 -0
  180. package/lib/WABinary/constants.js +1303 -0
  181. package/lib/WABinary/decode.d.ts +7 -0
  182. package/lib/WABinary/decode.js +300 -0
  183. package/lib/WABinary/encode.d.ts +3 -0
  184. package/lib/WABinary/encode.js +256 -0
  185. package/lib/WABinary/generic-utils.d.ts +15 -0
  186. package/lib/WABinary/generic-utils.js +138 -0
  187. package/lib/WABinary/index.d.ts +6 -0
  188. package/lib/WABinary/index.js +25 -0
  189. package/lib/WABinary/jid-utils.d.ts +48 -0
  190. package/lib/WABinary/jid-utils.js +115 -0
  191. package/lib/WABinary/types.d.ts +19 -0
  192. package/lib/WABinary/types.js +36 -0
  193. package/lib/WAM/BinaryInfo.d.ts +9 -0
  194. package/lib/WAM/BinaryInfo.js +13 -0
  195. package/lib/WAM/constants.d.ts +40 -0
  196. package/lib/WAM/constants.js +22855 -0
  197. package/lib/WAM/encode.d.ts +3 -0
  198. package/lib/WAM/encode.js +153 -0
  199. package/lib/WAM/index.d.ts +4 -0
  200. package/lib/WAM/index.js +19 -0
  201. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  202. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  203. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  204. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  205. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  206. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  207. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  208. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +41 -0
  209. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  210. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +54 -0
  211. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  212. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +32 -0
  213. package/lib/WAUSync/Protocols/index.d.ts +5 -0
  214. package/lib/WAUSync/Protocols/index.js +22 -0
  215. package/lib/WAUSync/USyncQuery.d.ts +29 -0
  216. package/lib/WAUSync/USyncQuery.js +97 -0
  217. package/lib/WAUSync/USyncUser.d.ts +13 -0
  218. package/lib/WAUSync/USyncUser.js +26 -0
  219. package/lib/WAUSync/index.d.ts +4 -0
  220. package/lib/WAUSync/index.js +19 -0
  221. package/lib/index.d.ts +12 -0
  222. package/lib/index.js +124 -0
  223. package/package.json +120 -0
  224. package/readme.md +1956 -0
@@ -0,0 +1,1692 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.makeMessagesSocket = void 0;
40
+ const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
41
+ const boom_1 = require("@hapi/boom");
42
+ const crypto_1 = require("crypto");
43
+ const index_js_1 = require("../../WAProto/index.js");
44
+ const index_js_2 = require("../Defaults/index.js");
45
+ const index_js_3 = require("../Utils/index.js");
46
+ const link_preview_js_1 = require("../Utils/link-preview.js");
47
+ const make_mutex_js_1 = require("../Utils/make-mutex.js");
48
+ const reporting_utils_js_1 = require("../Utils/reporting-utils.js");
49
+ const index_js_4 = require("../WABinary/index.js");
50
+ const generics_js_1 = require("../Utils/generics.js");
51
+ const index_js_5 = require("../WAUSync/index.js");
52
+ const newsletter_js_1 = require("./newsletter.js");
53
+ // Inline helper — no external import needed
54
+ const _isNewsletterJid = (jid) => typeof jid === 'string' && jid.endsWith('@newsletter');
55
+ const makeMessagesSocket = (config) => {
56
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
57
+ const sock = (0, newsletter_js_1.makeNewsletterSocket)(config);
58
+ const { ev, authState, messageMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral } = sock;
59
+ const userDevicesCache = config.userDevicesCache ||
60
+ new node_cache_1.default({
61
+ stdTTL: index_js_2.DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
62
+ useClones: false
63
+ });
64
+ const peerSessionsCache = new node_cache_1.default({
65
+ stdTTL: index_js_2.DEFAULT_CACHE_TTLS.USER_DEVICES,
66
+ useClones: false
67
+ });
68
+ // Initialize message retry manager if enabled
69
+ const messageRetryManager = enableRecentMessageCache ? new index_js_3.MessageRetryManager(logger, maxMsgRetryCount) : null;
70
+ // Prevent race conditions in Signal session encryption by user
71
+ const encryptionMutex = (0, make_mutex_js_1.makeKeyedMutex)();
72
+ let mediaConn;
73
+ const refreshMediaConn = async (forceGet = false) => {
74
+ const media = await mediaConn;
75
+ if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
76
+ mediaConn = (async () => {
77
+ const result = await query({
78
+ tag: 'iq',
79
+ attrs: {
80
+ type: 'set',
81
+ xmlns: 'w:m',
82
+ to: index_js_4.S_WHATSAPP_NET
83
+ },
84
+ content: [{ tag: 'media_conn', attrs: {} }]
85
+ });
86
+ const mediaConnNode = (0, index_js_4.getBinaryNodeChild)(result, 'media_conn');
87
+ // TODO: explore full length of data that whatsapp provides
88
+ const node = {
89
+ hosts: (0, index_js_4.getBinaryNodeChildren)(mediaConnNode, 'host').map(({ attrs }) => ({
90
+ hostname: attrs.hostname,
91
+ maxContentLengthBytes: +attrs.maxContentLengthBytes
92
+ })),
93
+ auth: mediaConnNode.attrs.auth,
94
+ ttl: +mediaConnNode.attrs.ttl,
95
+ fetchDate: new Date()
96
+ };
97
+ logger.debug('fetched media conn');
98
+ return node;
99
+ })();
100
+ }
101
+ return mediaConn;
102
+ };
103
+ /**
104
+ * generic send receipt function
105
+ * used for receipts of phone call, read, delivery etc.
106
+ * */
107
+ const sendReceipt = async (jid, participant, messageIds, type) => {
108
+ if (!messageIds || messageIds.length === 0) {
109
+ throw new boom_1.Boom('missing ids in receipt');
110
+ }
111
+ const node = {
112
+ tag: 'receipt',
113
+ attrs: {
114
+ id: messageIds[0]
115
+ }
116
+ };
117
+ const isReadReceipt = type === 'read' || type === 'read-self';
118
+ if (isReadReceipt) {
119
+ node.attrs.t = (0, index_js_3.unixTimestampSeconds)().toString();
120
+ }
121
+ if (type === 'sender' && ((0, index_js_4.isPnUser)(jid) || (0, index_js_4.isLidUser)(jid))) {
122
+ node.attrs.recipient = jid;
123
+ node.attrs.to = participant;
124
+ }
125
+ else {
126
+ node.attrs.to = jid;
127
+ if (participant) {
128
+ node.attrs.participant = participant;
129
+ }
130
+ }
131
+ if (type) {
132
+ node.attrs.type = type;
133
+ }
134
+ const remainingMessageIds = messageIds.slice(1);
135
+ if (remainingMessageIds.length) {
136
+ node.content = [
137
+ {
138
+ tag: 'list',
139
+ attrs: {},
140
+ content: remainingMessageIds.map(id => ({
141
+ tag: 'item',
142
+ attrs: { id }
143
+ }))
144
+ }
145
+ ];
146
+ }
147
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
148
+ await sendNode(node);
149
+ };
150
+ /** Correctly bulk send receipts to multiple chats, participants */
151
+ const sendReceipts = async (keys, type) => {
152
+ const recps = (0, index_js_3.aggregateMessageKeysNotFromMe)(keys);
153
+ for (const { jid, participant, messageIds } of recps) {
154
+ await sendReceipt(jid, participant, messageIds, type);
155
+ }
156
+ };
157
+ /** Bulk read messages. Keys can be from different chats & participants */
158
+ const readMessages = async (keys) => {
159
+ const privacySettings = await fetchPrivacySettings();
160
+ // based on privacy settings, we have to change the read type
161
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
162
+ await sendReceipts(keys, readType);
163
+ };
164
+ /** Fetch all the devices we've to send a message to */
165
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
166
+ const deviceResults = [];
167
+ if (!useCache) {
168
+ logger.debug('not using cache for devices');
169
+ }
170
+ const toFetch = [];
171
+ const jidsWithUser = jids
172
+ .map(jid => {
173
+ const decoded = (0, index_js_4.jidDecode)(jid);
174
+ const user = decoded?.user;
175
+ const device = decoded?.device;
176
+ const isExplicitDevice = typeof device === 'number' && device >= 0;
177
+ if (isExplicitDevice && user) {
178
+ deviceResults.push({
179
+ user,
180
+ device,
181
+ jid
182
+ });
183
+ return null;
184
+ }
185
+ jid = (0, index_js_4.jidNormalizedUser)(jid);
186
+ return { jid, user };
187
+ })
188
+ .filter(jid => jid !== null);
189
+ let mgetDevices;
190
+ if (useCache && userDevicesCache.mget) {
191
+ const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean);
192
+ mgetDevices = await userDevicesCache.mget(usersToFetch);
193
+ }
194
+ for (const { jid, user } of jidsWithUser) {
195
+ if (useCache) {
196
+ const devices = mgetDevices?.[user] ||
197
+ (userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
198
+ if (devices) {
199
+ const devicesWithJid = devices.map(d => ({
200
+ ...d,
201
+ jid: (0, index_js_4.jidEncode)(d.user, d.server, d.device)
202
+ }));
203
+ deviceResults.push(...devicesWithJid);
204
+ logger.trace({ user }, 'using cache for devices');
205
+ }
206
+ else {
207
+ toFetch.push(jid);
208
+ }
209
+ }
210
+ else {
211
+ toFetch.push(jid);
212
+ }
213
+ }
214
+ if (!toFetch.length) {
215
+ return deviceResults;
216
+ }
217
+ const requestedLidUsers = new Set();
218
+ for (const jid of toFetch) {
219
+ if ((0, index_js_4.isLidUser)(jid) || (0, index_js_4.isHostedLidUser)(jid)) {
220
+ const user = (0, index_js_4.jidDecode)(jid)?.user;
221
+ if (user)
222
+ requestedLidUsers.add(user);
223
+ }
224
+ }
225
+ const query = new index_js_5.USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol();
226
+ for (const jid of toFetch) {
227
+ query.withUser(new index_js_5.USyncUser().withId(jid)); // todo: investigate - the idea here is that <user> should have an inline lid field with the lid being the pn equivalent
228
+ }
229
+ const result = await sock.executeUSyncQuery(query);
230
+ if (result) {
231
+ // TODO: LID MAP this stuff (lid protocol will now return lid with devices)
232
+ const lidResults = result.list.filter(a => !!a.lid);
233
+ if (lidResults.length > 0) {
234
+ logger.trace('Storing LID maps from device call');
235
+ await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
236
+ // Force-refresh sessions for newly mapped LIDs to align identity addressing
237
+ try {
238
+ const lids = lidResults.map(a => a.lid);
239
+ if (lids.length) {
240
+ await assertSessions(lids, true);
241
+ }
242
+ }
243
+ catch (e) {
244
+ logger.warn({ e, count: lidResults.length }, 'failed to assert sessions for newly mapped LIDs');
245
+ }
246
+ }
247
+ const extracted = (0, index_js_3.extractDeviceJids)(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices);
248
+ const deviceMap = {};
249
+ for (const item of extracted) {
250
+ deviceMap[item.user] = deviceMap[item.user] || [];
251
+ deviceMap[item.user]?.push(item);
252
+ }
253
+ // Process each user's devices as a group for bulk LID migration
254
+ for (const [user, userDevices] of Object.entries(deviceMap)) {
255
+ const isLidUser = requestedLidUsers.has(user);
256
+ // Process all devices for this user
257
+ for (const item of userDevices) {
258
+ const finalJid = isLidUser
259
+ ? (0, index_js_4.jidEncode)(user, item.server, item.device)
260
+ : (0, index_js_4.jidEncode)(item.user, item.server, item.device);
261
+ deviceResults.push({
262
+ ...item,
263
+ jid: finalJid
264
+ });
265
+ logger.debug({
266
+ user: item.user,
267
+ device: item.device,
268
+ finalJid,
269
+ usedLid: isLidUser
270
+ }, 'Processed device with LID priority');
271
+ }
272
+ }
273
+ if (userDevicesCache.mset) {
274
+ // if the cache supports mset, we can set all devices in one go
275
+ await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
276
+ }
277
+ else {
278
+ for (const key in deviceMap) {
279
+ if (deviceMap[key])
280
+ await userDevicesCache.set(key, deviceMap[key]);
281
+ }
282
+ }
283
+ const userDeviceUpdates = {};
284
+ for (const [userId, devices] of Object.entries(deviceMap)) {
285
+ if (devices && devices.length > 0) {
286
+ userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0');
287
+ }
288
+ }
289
+ if (Object.keys(userDeviceUpdates).length > 0) {
290
+ try {
291
+ await authState.keys.set({ 'device-list': userDeviceUpdates });
292
+ logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, 'stored user device lists for bulk migration');
293
+ }
294
+ catch (error) {
295
+ logger.warn({ error }, 'failed to store user device lists');
296
+ }
297
+ }
298
+ }
299
+ return deviceResults;
300
+ };
301
+ /**
302
+ * Update Member Label
303
+ */
304
+ const updateMemberLabel = (jid, memberLabel) => {
305
+ return relayMessage(jid, {
306
+ protocolMessage: {
307
+ type: index_js_1.proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
308
+ memberLabel: {
309
+ label: memberLabel?.slice(0, 30),
310
+ labelTimestamp: (0, index_js_3.unixTimestampSeconds)()
311
+ }
312
+ }
313
+ }, {
314
+ additionalNodes: [
315
+ {
316
+ tag: 'meta',
317
+ attrs: {
318
+ tag_reason: 'user_update',
319
+ appdata: 'member_tag'
320
+ },
321
+ content: undefined
322
+ }
323
+ ]
324
+ });
325
+ };
326
+ const assertSessions = async (jids, force) => {
327
+ let didFetchNewSession = false;
328
+ const uniqueJids = [...new Set(jids)]; // Deduplicate JIDs
329
+ const jidsRequiringFetch = [];
330
+ logger.debug({ jids }, 'assertSessions call with jids');
331
+ // Check peerSessionsCache and validate sessions using libsignal loadSession
332
+ for (const jid of uniqueJids) {
333
+ const signalId = signalRepository.jidToSignalProtocolAddress(jid);
334
+ const cachedSession = peerSessionsCache.get(signalId);
335
+ if (cachedSession !== undefined) {
336
+ if (cachedSession && !force) {
337
+ continue; // Session exists in cache
338
+ }
339
+ }
340
+ else {
341
+ const sessionValidation = await signalRepository.validateSession(jid);
342
+ const hasSession = sessionValidation.exists;
343
+ peerSessionsCache.set(signalId, hasSession);
344
+ if (hasSession && !force) {
345
+ continue;
346
+ }
347
+ }
348
+ jidsRequiringFetch.push(jid);
349
+ }
350
+ if (jidsRequiringFetch.length) {
351
+ // LID if mapped, otherwise original
352
+ const wireJids = [
353
+ ...jidsRequiringFetch.filter(jid => !!(0, index_js_4.isLidUser)(jid) || !!(0, index_js_4.isHostedLidUser)(jid)),
354
+ ...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!(0, index_js_4.isPnUser)(jid) || !!(0, index_js_4.isHostedPnUser)(jid)))) || []).map(a => a.lid)
355
+ ];
356
+ logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions');
357
+ const result = await query({
358
+ tag: 'iq',
359
+ attrs: {
360
+ xmlns: 'encrypt',
361
+ type: 'get',
362
+ to: index_js_4.S_WHATSAPP_NET
363
+ },
364
+ content: [
365
+ {
366
+ tag: 'key',
367
+ attrs: {},
368
+ content: wireJids.map(jid => {
369
+ const attrs = { jid };
370
+ if (force)
371
+ attrs.reason = 'identity';
372
+ return { tag: 'user', attrs };
373
+ })
374
+ }
375
+ ]
376
+ });
377
+ await (0, index_js_3.parseAndInjectE2ESessions)(result, signalRepository);
378
+ didFetchNewSession = true;
379
+ // Cache fetched sessions using wire JIDs
380
+ for (const wireJid of wireJids) {
381
+ const signalId = signalRepository.jidToSignalProtocolAddress(wireJid);
382
+ peerSessionsCache.set(signalId, true);
383
+ }
384
+ }
385
+ return didFetchNewSession;
386
+ };
387
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
388
+ //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
389
+ if (!authState.creds.me?.id) {
390
+ throw new boom_1.Boom('Not authenticated');
391
+ }
392
+ const protocolMessage = {
393
+ protocolMessage: {
394
+ peerDataOperationRequestMessage: pdoMessage,
395
+ type: index_js_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
396
+ }
397
+ };
398
+ const meJid = (0, index_js_4.jidNormalizedUser)(authState.creds.me.id);
399
+ const msgId = await relayMessage(meJid, protocolMessage, {
400
+ additionalAttributes: {
401
+ category: 'peer',
402
+ push_priority: 'high_force'
403
+ },
404
+ additionalNodes: [
405
+ {
406
+ tag: 'meta',
407
+ attrs: { appdata: 'default' }
408
+ }
409
+ ]
410
+ });
411
+ return msgId;
412
+ };
413
+ const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
414
+ if (!recipientJids.length) {
415
+ return { nodes: [], shouldIncludeDeviceIdentity: false };
416
+ }
417
+ const patched = await patchMessageBeforeSending(message, recipientJids);
418
+ const patchedMessages = Array.isArray(patched)
419
+ ? patched
420
+ : recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
421
+ let shouldIncludeDeviceIdentity = false;
422
+ const meId = authState.creds.me.id;
423
+ const meLid = authState.creds.me?.lid;
424
+ const meLidUser = meLid ? (0, index_js_4.jidDecode)(meLid)?.user : null;
425
+ const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
426
+ try {
427
+ if (!jid)
428
+ return null;
429
+ let msgToEncrypt = patchedMessage;
430
+ if (dsmMessage) {
431
+ const { user: targetUser } = (0, index_js_4.jidDecode)(jid);
432
+ const { user: ownPnUser } = (0, index_js_4.jidDecode)(meId);
433
+ const ownLidUser = meLidUser;
434
+ const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
435
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
436
+ if (isOwnUser && !isExactSenderDevice) {
437
+ msgToEncrypt = dsmMessage;
438
+ logger.debug({ jid, targetUser }, 'Using DSM for own device');
439
+ }
440
+ }
441
+ const bytes = (0, index_js_3.encodeWAMessage)(msgToEncrypt);
442
+ const mutexKey = jid;
443
+ const node = await encryptionMutex.mutex(mutexKey, async () => {
444
+ const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes });
445
+ if (type === 'pkmsg') {
446
+ shouldIncludeDeviceIdentity = true;
447
+ }
448
+ return {
449
+ tag: 'to',
450
+ attrs: { jid },
451
+ content: [
452
+ {
453
+ tag: 'enc',
454
+ attrs: { v: '2', type, ...(extraAttrs || {}) },
455
+ content: ciphertext
456
+ }
457
+ ]
458
+ };
459
+ });
460
+ return node;
461
+ }
462
+ catch (err) {
463
+ logger.error({ jid, err }, 'Failed to encrypt for recipient');
464
+ return null;
465
+ }
466
+ });
467
+ const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null);
468
+ if (recipientJids.length > 0 && nodes.length === 0) {
469
+ throw new boom_1.Boom('All encryptions failed', { statusCode: 500 });
470
+ }
471
+ return { nodes, shouldIncludeDeviceIdentity };
472
+ };
473
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList, AI = false }) => {
474
+ const meId = authState.creds.me.id;
475
+ const meLid = authState.creds.me?.lid;
476
+ const isRetryResend = Boolean(participant?.jid);
477
+ let shouldIncludeDeviceIdentity = isRetryResend;
478
+ const statusJid = 'status@broadcast';
479
+ const { user, server } = (0, index_js_4.jidDecode)(jid);
480
+ const isGroup = server === 'g.us';
481
+ const isStatus = jid === statusJid;
482
+ const isLid = server === 'lid';
483
+ const isNewsletter = server === 'newsletter';
484
+ const isGroupOrStatus = isGroup || isStatus;
485
+ const finalJid = jid;
486
+ msgId = msgId || (0, index_js_3.generateMessageIDV2)(meId);
487
+ useUserDevicesCache = useUserDevicesCache !== false;
488
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
489
+ const participants = [];
490
+ const destinationJid = !isStatus ? finalJid : statusJid;
491
+ const binaryNodeContent = [];
492
+ const devices = [];
493
+ let reportingMessage;
494
+ const meMsg = {
495
+ deviceSentMessage: {
496
+ destinationJid,
497
+ message
498
+ },
499
+ messageContextInfo: message.messageContextInfo
500
+ };
501
+ const extraAttrs = {};
502
+ if ((message?.interactiveMessage || message?.buttonsMessage || message?.listMessage || message?.templateMessage)
503
+ && !additionalNodes?.some(node => node?.tag === 'biz')) {
504
+ const btnNode = getButtonArgs(message);
505
+ if (btnNode) {
506
+ additionalNodes = [...(additionalNodes || []), btnNode];
507
+ }
508
+ }
509
+ if (participant) {
510
+ if (!isGroup && !isStatus) {
511
+ additionalAttributes = { ...additionalAttributes, device_fanout: 'false' };
512
+ }
513
+ const { user, device } = (0, index_js_4.jidDecode)(participant.jid);
514
+ devices.push({
515
+ user,
516
+ device,
517
+ jid: participant.jid
518
+ });
519
+ }
520
+ await authState.keys.transaction(async () => {
521
+ const mediaType = getMediaType(message);
522
+ if (mediaType) {
523
+ extraAttrs['mediatype'] = mediaType;
524
+ }
525
+ if (isNewsletter) {
526
+ // Handle edit
527
+ if (message.protocolMessage?.editedMessage) {
528
+ msgId = message.protocolMessage.key?.id;
529
+ message = message.protocolMessage.editedMessage;
530
+ }
531
+ // Handle delete/revoke
532
+ if (message.protocolMessage?.type === index_js_1.proto.Message.ProtocolMessage.Type.REVOKE) {
533
+ msgId = message.protocolMessage.key?.id;
534
+ message = {};
535
+ }
536
+ // ── Newsletter Button Compatibility Patch ──────────────────────
537
+ // interactiveMessage (quick_reply / single_select / cta_url) bisa
538
+ // dikirim ke newsletter langsung — WA menerima via proto encoding.
539
+ // listMessage & buttonsMessage dikonversi ke interactiveMessage
540
+ // supaya konsisten dengan cara bot menulis pesan.
541
+ // ──────────────────────────────────────────────────────────────
542
+ if (message.listMessage) {
543
+ const list = message.listMessage;
544
+ message = {
545
+ interactiveMessage: {
546
+ nativeFlowMessage: {
547
+ buttons: [{
548
+ name: 'single_select',
549
+ buttonParamsJson: JSON.stringify({
550
+ title: list.buttonText || 'Select',
551
+ sections: (list.sections || []).map(sec => ({
552
+ title: sec.title || '',
553
+ highlight_label: '',
554
+ rows: (sec.rows || []).map(row => ({
555
+ header: '',
556
+ title: row.title || '',
557
+ description: row.description || '',
558
+ id: row.rowId || row.id || ''
559
+ }))
560
+ }))
561
+ })
562
+ }],
563
+ messageParamsJson: '',
564
+ messageVersion: 1
565
+ },
566
+ body: { text: list.description || '' },
567
+ ...(list.footerText ? { footer: { text: list.footerText } } : {}),
568
+ ...(list.title ? { header: { title: list.title, hasMediaAttachment: false, subtitle: '' } } : {})
569
+ }
570
+ };
571
+ }
572
+ else if (message.buttonsMessage) {
573
+ const bMsg = message.buttonsMessage;
574
+ message = {
575
+ interactiveMessage: {
576
+ nativeFlowMessage: {
577
+ buttons: (bMsg.buttons || []).map(btn => ({
578
+ name: 'quick_reply',
579
+ buttonParamsJson: JSON.stringify({
580
+ display_text: btn.buttonText?.displayText || btn.buttonText || '',
581
+ id: btn.buttonId || btn.buttonText?.displayText || ''
582
+ })
583
+ })),
584
+ messageParamsJson: '',
585
+ messageVersion: 1
586
+ },
587
+ body: { text: bMsg.contentText || bMsg.text || '' },
588
+ ...(bMsg.footerText ? { footer: { text: bMsg.footerText } } : {}),
589
+ }
590
+ };
591
+ }
592
+ // ── End Newsletter Button Compatibility Patch ──────────────────
593
+ const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
594
+ if (Array.isArray(patched)) {
595
+ throw new Error('Per-jid patching is not supported in channel');
596
+ }
597
+ const bytes = (0, index_js_3.encodeNewsletterMessage)(patched);
598
+ // Set mediatype for interactive messages
599
+ if (patched.interactiveMessage && !extraAttrs['mediatype']) {
600
+ extraAttrs['mediatype'] = 'interactive';
601
+ }
602
+ // extraAttrs already has mediatype set above if media message
603
+ binaryNodeContent.push({
604
+ tag: 'plaintext',
605
+ attrs: extraAttrs,
606
+ content: bytes
607
+ });
608
+ logger.debug({ msgId, extraAttrs }, `sending newsletter message to ${jid}`);
609
+ const stanza = {
610
+ tag: 'message',
611
+ attrs: {
612
+ to: jid,
613
+ id: msgId,
614
+ type: getMessageType(message),
615
+ ...(additionalAttributes || {})
616
+ },
617
+ content: binaryNodeContent
618
+ };
619
+ await sendNode(stanza);
620
+ return;
621
+ }
622
+ if ((0, index_js_3.normalizeMessageContent)(message)?.pinInChatMessage || (0, index_js_3.normalizeMessageContent)(message)?.reactionMessage) {
623
+ extraAttrs['decrypt-fail'] = 'hide'; // todo: expand for reactions and other types
624
+ }
625
+ if (isGroupOrStatus && !isRetryResend) {
626
+ const [groupData, senderKeyMap] = await Promise.all([
627
+ (async () => {
628
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined; // todo: should we rely on the cache specially if the cache is outdated and the metadata has new fields?
629
+ if (groupData && Array.isArray(groupData?.participants)) {
630
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
631
+ }
632
+ else if (!isStatus) {
633
+ groupData = await groupMetadata(jid); // TODO: start storing group participant list + addr mode in Signal & stop relying on this
634
+ }
635
+ return groupData;
636
+ })(),
637
+ (async () => {
638
+ if (!participant && !isStatus) {
639
+ // what if sender memory is less accurate than the cached metadata
640
+ // on participant change in group, we should do sender memory manipulation
641
+ const result = await authState.keys.get('sender-key-memory', [jid]); // TODO: check out what if the sender key memory doesn't include the LID stuff now?
642
+ return result[jid] || {};
643
+ }
644
+ return {};
645
+ })()
646
+ ]);
647
+ const participantsList = groupData ? groupData.participants.map(p => p.id) : [];
648
+ if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
649
+ additionalAttributes = {
650
+ ...additionalAttributes,
651
+ expiration: groupData.ephemeralDuration.toString()
652
+ };
653
+ }
654
+ if (isStatus && statusJidList) {
655
+ participantsList.push(...statusJidList);
656
+ }
657
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
658
+ devices.push(...additionalDevices);
659
+ if (isGroup) {
660
+ additionalAttributes = {
661
+ ...additionalAttributes,
662
+ addressing_mode: groupData?.addressingMode || 'lid'
663
+ };
664
+ }
665
+ // Ensure groupStatusMessageV2 always has messageContextInfo.messageSecret
666
+ if (message?.groupStatusMessageV2 && !message?.messageContextInfo?.messageSecret) {
667
+ const { randomBytes } = await Promise.resolve().then(() => __importStar(require('node:crypto')));
668
+ message = {
669
+ ...message,
670
+ messageContextInfo: {
671
+ ...(message.messageContextInfo || {}),
672
+ messageSecret: randomBytes(32)
673
+ },
674
+ groupStatusMessageV2: {
675
+ ...message.groupStatusMessageV2,
676
+ message: {
677
+ ...(message.groupStatusMessageV2.message || {}),
678
+ messageContextInfo: {
679
+ ...(message.groupStatusMessageV2.message?.messageContextInfo || {}),
680
+ messageSecret: message.messageContextInfo?.messageSecret || randomBytes(32)
681
+ }
682
+ }
683
+ }
684
+ };
685
+ }
686
+ // ── Group Interactive Message Compatibility Patch ──────────────
687
+ // WhatsApp groups do NOT render listMessage, buttonsMessage, or
688
+ // templateMessage natively in MD protocol. All must be converted
689
+ // to interactiveMessage with nativeFlowMessage so they display
690
+ // and are interactive in group chats.
691
+ // ──────────────────────────────────────────────────────────────
692
+ // 1. listMessage → interactiveMessage single_select
693
+ if (message.listMessage) {
694
+ const list = message.listMessage;
695
+ const interactiveMessage = {
696
+ nativeFlowMessage: {
697
+ buttons: [{
698
+ name: 'single_select',
699
+ buttonParamsJson: JSON.stringify({
700
+ title: list.buttonText || 'Select',
701
+ sections: (list.sections || []).map(section => ({
702
+ title: section.title || '',
703
+ highlight_label: '',
704
+ rows: (section.rows || []).map(row => ({
705
+ header: '',
706
+ title: row.title || '',
707
+ description: row.description || '',
708
+ id: row.rowId || row.id || ''
709
+ }))
710
+ }))
711
+ })
712
+ }],
713
+ messageParamsJson: '',
714
+ messageVersion: 1
715
+ },
716
+ body: { text: list.description || '' },
717
+ footer: list.footerText ? { text: list.footerText } : undefined,
718
+ header: list.title ? { title: list.title, hasMediaAttachment: false, subtitle: '' } : undefined,
719
+ contextInfo: list.contextInfo
720
+ };
721
+ message = { interactiveMessage };
722
+ }
723
+ // 2. buttonsMessage → interactiveMessage nativeFlowMessage quick_reply buttons
724
+ else if (message.buttonsMessage) {
725
+ const bMsg = message.buttonsMessage;
726
+ const buttons = (bMsg.buttons || []).map(btn => ({
727
+ name: 'quick_reply',
728
+ buttonParamsJson: JSON.stringify({
729
+ display_text: btn.buttonText?.displayText || btn.buttonText || '',
730
+ id: btn.buttonId || btn.buttonText?.displayText || ''
731
+ })
732
+ }));
733
+ const interactiveMessage = {
734
+ nativeFlowMessage: {
735
+ buttons,
736
+ messageParamsJson: '',
737
+ messageVersion: 1
738
+ },
739
+ body: { text: bMsg.contentText || bMsg.text || '' },
740
+ footer: bMsg.footerText ? { text: bMsg.footerText } : undefined,
741
+ header: bMsg.text
742
+ ? { title: bMsg.text, hasMediaAttachment: false, subtitle: '' }
743
+ : (bMsg.imageMessage || bMsg.videoMessage || bMsg.documentMessage
744
+ ? { hasMediaAttachment: true, ...(bMsg.imageMessage ? { imageMessage: bMsg.imageMessage } : {}), ...(bMsg.videoMessage ? { videoMessage: bMsg.videoMessage } : {}) }
745
+ : undefined),
746
+ contextInfo: bMsg.contextInfo
747
+ };
748
+ message = { interactiveMessage };
749
+ }
750
+ // 3. templateMessage (hydratedFourRowTemplate) → interactiveMessage nativeFlowMessage
751
+ else if (message.templateMessage) {
752
+ const tmpl = message.templateMessage.hydratedTemplate || message.templateMessage.fourRowTemplate;
753
+ if (tmpl) {
754
+ const hydratedButtons = tmpl.hydratedButtons || [];
755
+ const buttons = hydratedButtons.map(hBtn => {
756
+ if (hBtn.quickReplyButton) {
757
+ return {
758
+ name: 'quick_reply',
759
+ buttonParamsJson: JSON.stringify({
760
+ display_text: hBtn.quickReplyButton.displayText || '',
761
+ id: hBtn.quickReplyButton.id || hBtn.quickReplyButton.displayText || ''
762
+ })
763
+ };
764
+ }
765
+ else if (hBtn.urlButton) {
766
+ return {
767
+ name: 'cta_url',
768
+ buttonParamsJson: JSON.stringify({
769
+ display_text: hBtn.urlButton.displayText || '',
770
+ url: hBtn.urlButton.url || '',
771
+ merchant_url: hBtn.urlButton.url || ''
772
+ })
773
+ };
774
+ }
775
+ else if (hBtn.callButton) {
776
+ return {
777
+ name: 'cta_call',
778
+ buttonParamsJson: JSON.stringify({
779
+ display_text: hBtn.callButton.displayText || '',
780
+ phone_number: hBtn.callButton.phoneNumber || ''
781
+ })
782
+ };
783
+ }
784
+ return null;
785
+ }).filter(Boolean);
786
+ const interactiveMessage = {
787
+ nativeFlowMessage: {
788
+ buttons,
789
+ messageParamsJson: '',
790
+ messageVersion: 1
791
+ },
792
+ body: { text: tmpl.hydratedContentText || tmpl.contentText || '' },
793
+ footer: tmpl.hydratedFooterText ? { text: tmpl.hydratedFooterText } : undefined,
794
+ header: tmpl.hydratedTitleText
795
+ ? { title: tmpl.hydratedTitleText, hasMediaAttachment: false, subtitle: '' }
796
+ : (tmpl.imageMessage || tmpl.videoMessage || tmpl.documentMessage
797
+ ? { hasMediaAttachment: true, ...(tmpl.imageMessage ? { imageMessage: tmpl.imageMessage } : {}), ...(tmpl.videoMessage ? { videoMessage: tmpl.videoMessage } : {}) }
798
+ : undefined),
799
+ contextInfo: tmpl.contextInfo
800
+ };
801
+ message = { interactiveMessage };
802
+ }
803
+ }
804
+ // ── End Group Interactive Message Compatibility Patch ──────────
805
+ const patched = await patchMessageBeforeSending(message);
806
+ if (Array.isArray(patched)) {
807
+ throw new boom_1.Boom('Per-jid patching is not supported in groups');
808
+ }
809
+ const bytes = (0, index_js_3.encodeWAMessage)(patched);
810
+ reportingMessage = patched;
811
+ const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid';
812
+ const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId;
813
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
814
+ group: destinationJid,
815
+ data: bytes,
816
+ meId: groupSenderIdentity
817
+ });
818
+ const senderKeyRecipients = [];
819
+ for (const device of devices) {
820
+ const deviceJid = device.jid;
821
+ const hasKey = !!senderKeyMap[deviceJid];
822
+ if ((!hasKey || !!participant) &&
823
+ !(0, index_js_4.isHostedLidUser)(deviceJid) &&
824
+ !(0, index_js_4.isHostedPnUser)(deviceJid) &&
825
+ device.device !== 99) {
826
+ //todo: revamp all this logic
827
+ // the goal is to follow with what I said above for each group, and instead of a true false map of ids, we can set an array full of those the app has already sent pkmsgs
828
+ senderKeyRecipients.push(deviceJid);
829
+ senderKeyMap[deviceJid] = true;
830
+ }
831
+ }
832
+ if (senderKeyRecipients.length) {
833
+ logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key');
834
+ const senderKeyMsg = {
835
+ senderKeyDistributionMessage: {
836
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
837
+ groupId: destinationJid
838
+ }
839
+ };
840
+ const senderKeySessionTargets = senderKeyRecipients;
841
+ await assertSessions(senderKeySessionTargets);
842
+ const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs);
843
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
844
+ participants.push(...result.nodes);
845
+ }
846
+ binaryNodeContent.push({
847
+ tag: 'enc',
848
+ attrs: { v: '2', type: 'skmsg', ...extraAttrs },
849
+ content: ciphertext
850
+ });
851
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
852
+ }
853
+ else {
854
+ // ADDRESSING CONSISTENCY: Match own identity to conversation context
855
+ // TODO: investigate if this is true
856
+ let ownId = meId;
857
+ if (isLid && meLid) {
858
+ ownId = meLid;
859
+ logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation');
860
+ }
861
+ else {
862
+ logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation');
863
+ }
864
+ const { user: ownUser } = (0, index_js_4.jidDecode)(ownId);
865
+ if (!participant) {
866
+ const patchedForReporting = await patchMessageBeforeSending(message, [jid]);
867
+ reportingMessage = Array.isArray(patchedForReporting)
868
+ ? patchedForReporting.find(item => item.recipientJid === jid) || patchedForReporting[0]
869
+ : patchedForReporting;
870
+ }
871
+ if (!isRetryResend) {
872
+ const targetUserServer = isLid ? 'lid' : 's.whatsapp.net';
873
+ devices.push({
874
+ user,
875
+ device: 0,
876
+ jid: (0, index_js_4.jidEncode)(user, targetUserServer, 0) // rajeh, todo: this entire logic is convoluted and weird.
877
+ });
878
+ if (user !== ownUser) {
879
+ const ownUserServer = isLid ? 'lid' : 's.whatsapp.net';
880
+ const ownUserForAddressing = isLid && meLid ? (0, index_js_4.jidDecode)(meLid).user : (0, index_js_4.jidDecode)(meId).user;
881
+ devices.push({
882
+ user: ownUserForAddressing,
883
+ device: 0,
884
+ jid: (0, index_js_4.jidEncode)(ownUserForAddressing, ownUserServer, 0)
885
+ });
886
+ }
887
+ if (additionalAttributes?.['category'] !== 'peer') {
888
+ // Clear placeholders and enumerate actual devices
889
+ devices.length = 0;
890
+ // Use conversation-appropriate sender identity
891
+ const senderIdentity = isLid && meLid
892
+ ? (0, index_js_4.jidEncode)((0, index_js_4.jidDecode)(meLid)?.user, 'lid', undefined)
893
+ : (0, index_js_4.jidEncode)((0, index_js_4.jidDecode)(meId)?.user, 's.whatsapp.net', undefined);
894
+ // Enumerate devices for sender and target with consistent addressing
895
+ const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false);
896
+ devices.push(...sessionDevices);
897
+ logger.debug({
898
+ deviceCount: devices.length,
899
+ devices: devices.map(d => `${d.user}:${d.device}@${(0, index_js_4.jidDecode)(d.jid)?.server}`)
900
+ }, 'Device enumeration complete with unified addressing');
901
+ }
902
+ }
903
+ const allRecipients = [];
904
+ const meRecipients = [];
905
+ const otherRecipients = [];
906
+ const { user: mePnUser } = (0, index_js_4.jidDecode)(meId);
907
+ const { user: meLidUser } = meLid ? (0, index_js_4.jidDecode)(meLid) : { user: null };
908
+ for (const { user, jid } of devices) {
909
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
910
+ if (isExactSenderDevice) {
911
+ logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)');
912
+ continue;
913
+ }
914
+ // Check if this is our device (could match either PN or LID user)
915
+ const isMe = user === mePnUser || user === meLidUser;
916
+ if (isMe) {
917
+ meRecipients.push(jid);
918
+ }
919
+ else {
920
+ otherRecipients.push(jid);
921
+ }
922
+ allRecipients.push(jid);
923
+ }
924
+ await assertSessions(allRecipients);
925
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
926
+ // For own devices: use DSM if available (1:1 chats only)
927
+ createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
928
+ createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
929
+ ]);
930
+ participants.push(...meNodes);
931
+ participants.push(...otherNodes);
932
+ if (meRecipients.length > 0 || otherRecipients.length > 0) {
933
+ extraAttrs['phash'] = (0, index_js_3.generateParticipantHashV2)([...meRecipients, ...otherRecipients]);
934
+ }
935
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
936
+ }
937
+ if (isRetryResend) {
938
+ const isParticipantLid = (0, index_js_4.isLidUser)(participant.jid);
939
+ const isMe = (0, index_js_4.areJidsSameUser)(participant.jid, isParticipantLid ? meLid : meId);
940
+ const encodedMessageToSend = isMe
941
+ ? (0, index_js_3.encodeWAMessage)({
942
+ deviceSentMessage: {
943
+ destinationJid,
944
+ message
945
+ }
946
+ })
947
+ : (0, index_js_3.encodeWAMessage)(message);
948
+ const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
949
+ data: encodedMessageToSend,
950
+ jid: participant.jid
951
+ });
952
+ binaryNodeContent.push({
953
+ tag: 'enc',
954
+ attrs: {
955
+ v: '2',
956
+ type,
957
+ count: participant.count.toString()
958
+ },
959
+ content: encryptedContent
960
+ });
961
+ }
962
+ if (participants.length) {
963
+ if (additionalAttributes?.['category'] === 'peer') {
964
+ const peerNode = participants[0]?.content?.[0];
965
+ if (peerNode) {
966
+ binaryNodeContent.push(peerNode); // push only enc
967
+ }
968
+ }
969
+ else {
970
+ binaryNodeContent.push({
971
+ tag: 'participants',
972
+ attrs: {},
973
+ content: participants
974
+ });
975
+ }
976
+ }
977
+ const stanza = {
978
+ tag: 'message',
979
+ attrs: {
980
+ id: msgId,
981
+ to: destinationJid,
982
+ type: getMessageType(message),
983
+ ...(additionalAttributes || {})
984
+ },
985
+ content: binaryNodeContent
986
+ };
987
+ // if the participant to send to is explicitly specified (generally retry recp)
988
+ // ensure the message is only sent to that person
989
+ // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
990
+ if (participant) {
991
+ if ((0, index_js_4.isJidGroup)(destinationJid)) {
992
+ stanza.attrs.to = destinationJid;
993
+ stanza.attrs.participant = participant.jid;
994
+ }
995
+ else if ((0, index_js_4.areJidsSameUser)(participant.jid, meId)) {
996
+ stanza.attrs.to = participant.jid;
997
+ stanza.attrs.recipient = destinationJid;
998
+ }
999
+ else {
1000
+ stanza.attrs.to = participant.jid;
1001
+ }
1002
+ }
1003
+ else {
1004
+ stanza.attrs.to = destinationJid;
1005
+ }
1006
+ if (shouldIncludeDeviceIdentity) {
1007
+ ;
1008
+ stanza.content.push({
1009
+ tag: 'device-identity',
1010
+ attrs: {},
1011
+ content: (0, index_js_3.encodeSignedDeviceIdentity)(authState.creds.account, true)
1012
+ });
1013
+ logger.debug({ jid }, 'adding device identity');
1014
+ }
1015
+ if (!isNewsletter &&
1016
+ !isRetryResend &&
1017
+ reportingMessage?.messageContextInfo?.messageSecret &&
1018
+ (0, reporting_utils_js_1.shouldIncludeReportingToken)(reportingMessage)) {
1019
+ try {
1020
+ const encoded = (0, index_js_3.encodeWAMessage)(reportingMessage);
1021
+ const reportingKey = {
1022
+ id: msgId,
1023
+ fromMe: true,
1024
+ remoteJid: destinationJid,
1025
+ participant: participant?.jid
1026
+ };
1027
+ const reportingNode = await (0, reporting_utils_js_1.getMessageReportingToken)(encoded, reportingMessage, reportingKey);
1028
+ if (reportingNode) {
1029
+ ;
1030
+ stanza.content.push(reportingNode);
1031
+ logger.trace({ jid }, 'added reporting token to message');
1032
+ }
1033
+ }
1034
+ catch (error) {
1035
+ logger.warn({ jid, trace: error?.stack }, 'failed to attach reporting token');
1036
+ }
1037
+ }
1038
+ const contactTcTokenData = !isGroup && !isRetryResend && !isStatus ? await authState.keys.get('tctoken', [destinationJid]) : {};
1039
+ const tcTokenBuffer = contactTcTokenData[destinationJid]?.token;
1040
+ if (tcTokenBuffer) {
1041
+ ;
1042
+ stanza.content.push({
1043
+ tag: 'tctoken',
1044
+ attrs: {},
1045
+ content: tcTokenBuffer
1046
+ });
1047
+ }
1048
+ if (AI && !isGroup && !isStatus && !isNewsletter) {
1049
+ const existingBizBot = (0, index_js_4.getBinaryFilteredBizBot)(additionalNodes || []);
1050
+ if (existingBizBot) {
1051
+ if (additionalNodes && additionalNodes.length > 0) {
1052
+ stanza.content.push(...additionalNodes);
1053
+ }
1054
+ }
1055
+ else {
1056
+ stanza.content.push({ tag: 'bot', attrs: { biz_bot: '1' } });
1057
+ if (additionalNodes && additionalNodes.length > 0) {
1058
+ stanza.content.push(...additionalNodes);
1059
+ }
1060
+ }
1061
+ }
1062
+ else if (additionalNodes && additionalNodes.length > 0) {
1063
+ ;
1064
+ stanza.content.push(...additionalNodes);
1065
+ }
1066
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
1067
+ await sendNode(stanza);
1068
+ // Add message to retry cache if enabled
1069
+ if (messageRetryManager && !participant) {
1070
+ messageRetryManager.addRecentMessage(destinationJid, msgId, message);
1071
+ }
1072
+ }, meId);
1073
+ return msgId;
1074
+ };
1075
+ const getMessageType = (message) => {
1076
+ // groupStatusMessageV2 must be checked BEFORE normalizeMessageContent
1077
+ // because normalizeMessageContent will unwrap it into inner message
1078
+ if (message?.groupStatusMessageV2 || message?.groupStatusMessage) {
1079
+ return 'text';
1080
+ }
1081
+ const normalizedMessage = (0, index_js_3.normalizeMessageContent)(message);
1082
+ if (!normalizedMessage)
1083
+ return 'text';
1084
+ if (normalizedMessage.reactionMessage || normalizedMessage.encReactionMessage) {
1085
+ return 'reaction';
1086
+ }
1087
+ if (normalizedMessage.pollCreationMessage ||
1088
+ normalizedMessage.pollCreationMessageV2 ||
1089
+ normalizedMessage.pollCreationMessageV3 ||
1090
+ normalizedMessage.pollUpdateMessage) {
1091
+ return 'poll';
1092
+ }
1093
+ if (normalizedMessage.eventMessage) {
1094
+ return 'event';
1095
+ }
1096
+ if (normalizedMessage.interactiveMessage) {
1097
+ return 'text';
1098
+ }
1099
+ if (getMediaType(normalizedMessage) !== '') {
1100
+ return 'media';
1101
+ }
1102
+ return 'text';
1103
+ };
1104
+ const getMediaType = (message) => {
1105
+ if (message.imageMessage) {
1106
+ return 'image';
1107
+ }
1108
+ else if (message.videoMessage) {
1109
+ return message.videoMessage.gifPlayback ? 'gif' : 'video';
1110
+ }
1111
+ else if (message.ptvMessage) {
1112
+ return 'video';
1113
+ }
1114
+ else if (message.audioMessage) {
1115
+ return message.audioMessage.ptt ? 'ptt' : 'audio';
1116
+ }
1117
+ else if (message.contactMessage) {
1118
+ return 'vcard';
1119
+ }
1120
+ else if (message.documentMessage) {
1121
+ return 'document';
1122
+ }
1123
+ else if (message.contactsArrayMessage) {
1124
+ return 'contact_array';
1125
+ }
1126
+ else if (message.liveLocationMessage) {
1127
+ return 'livelocation';
1128
+ }
1129
+ else if (message.stickerMessage) {
1130
+ return 'sticker';
1131
+ }
1132
+ else if (message.stickerPackMessage) {
1133
+ return 'sticker_pack';
1134
+ }
1135
+ else if (message.listMessage) {
1136
+ return 'list';
1137
+ }
1138
+ else if (message.listResponseMessage) {
1139
+ return 'list_response';
1140
+ }
1141
+ else if (message.buttonsResponseMessage) {
1142
+ return 'buttons_response';
1143
+ }
1144
+ else if (message.orderMessage) {
1145
+ return 'order';
1146
+ }
1147
+ else if (message.productMessage) {
1148
+ return 'product';
1149
+ }
1150
+ else if (message.interactiveResponseMessage) {
1151
+ return 'native_flow_response';
1152
+ }
1153
+ else if (message.groupInviteMessage) {
1154
+ return 'url';
1155
+ }
1156
+ return '';
1157
+ };
1158
+ const getPrivacyTokens = async (jids) => {
1159
+ const t = (0, index_js_3.unixTimestampSeconds)().toString();
1160
+ const result = await query({
1161
+ tag: 'iq',
1162
+ attrs: {
1163
+ to: index_js_4.S_WHATSAPP_NET,
1164
+ type: 'set',
1165
+ xmlns: 'privacy'
1166
+ },
1167
+ content: [
1168
+ {
1169
+ tag: 'tokens',
1170
+ attrs: {},
1171
+ content: jids.map(jid => ({
1172
+ tag: 'token',
1173
+ attrs: {
1174
+ jid: (0, index_js_4.jidNormalizedUser)(jid),
1175
+ t,
1176
+ type: 'trusted_contact'
1177
+ }
1178
+ }))
1179
+ }
1180
+ ]
1181
+ });
1182
+ return result;
1183
+ };
1184
+ const waUploadToServer = (0, index_js_3.getWAUploadToServer)(config, refreshMediaConn);
1185
+ const waitForMsgMediaUpdate = (0, index_js_3.bindWaitForEvent)(ev, 'messages.media-update');
1186
+ // ── Button type helpers (ported from itsukichan) ──────────────────────────
1187
+ const getButtonType = (message) => {
1188
+ if (message.listMessage)
1189
+ return 'list';
1190
+ if (message.buttonsMessage)
1191
+ return 'buttons';
1192
+ if (message.templateMessage)
1193
+ return 'template';
1194
+ if (message.interactiveMessage?.nativeFlowMessage)
1195
+ return 'native_flow';
1196
+ if (message.interactiveMessage?.shopStorefrontMessage)
1197
+ return 'shop';
1198
+ if (message.interactiveMessage?.collectionMessage)
1199
+ return 'collection';
1200
+ if (message.interactiveMessage?.carouselMessage)
1201
+ return 'carousel';
1202
+ if (message.interactiveMessage)
1203
+ return 'interactive';
1204
+ return null;
1205
+ };
1206
+ const getButtonArgs = (message) => {
1207
+ const nativeFlow = message.interactiveMessage?.nativeFlowMessage;
1208
+ const firstButtonName = nativeFlow?.buttons?.[0]?.name;
1209
+ const nativeFlowSpecials = [
1210
+ 'mpm', 'cta_catalog', 'send_location',
1211
+ 'call_permission_request', 'wa_payment_transaction_details',
1212
+ 'automated_greeting_message_view_catalog'
1213
+ ];
1214
+ const ts = (0, index_js_3.unixTimestampSeconds)().toString();
1215
+ const bizBase = { actual_actors: '2', host_storage: '2', privacy_mode_ts: ts };
1216
+ const qualityControl = { tag: 'quality_control', attrs: { source_type: 'third_party' } };
1217
+ if (nativeFlow && (firstButtonName === 'review_and_pay' || firstButtonName === 'payment_info')) {
1218
+ return {
1219
+ tag: 'biz',
1220
+ attrs: { native_flow_name: firstButtonName === 'review_and_pay' ? 'order_details' : firstButtonName }
1221
+ };
1222
+ }
1223
+ else if (nativeFlow && nativeFlowSpecials.includes(firstButtonName)) {
1224
+ return {
1225
+ tag: 'biz', attrs: bizBase,
1226
+ content: [{
1227
+ tag: 'interactive', attrs: { type: 'native_flow', v: '1' },
1228
+ content: [{ tag: 'native_flow', attrs: { v: '2', name: firstButtonName } }]
1229
+ }, qualityControl]
1230
+ };
1231
+ }
1232
+ else if (nativeFlow || message.buttonsMessage || message.templateMessage || message.interactiveMessage) {
1233
+ // All interactive types in groups use native_flow biz node
1234
+ // This covers: nativeFlowMessage, buttonsMessage→interactiveMessage,
1235
+ // templateMessage→interactiveMessage, and direct interactiveMessage
1236
+ return {
1237
+ tag: 'biz', attrs: bizBase,
1238
+ content: [{
1239
+ tag: 'interactive', attrs: { type: 'native_flow', v: '1' },
1240
+ content: [{ tag: 'native_flow', attrs: { v: '9', name: 'mixed' } }]
1241
+ }, qualityControl]
1242
+ };
1243
+ }
1244
+ else if (message.listMessage) {
1245
+ // Standalone listMessage (private chat) keeps the list biz node
1246
+ return {
1247
+ tag: 'biz', attrs: bizBase,
1248
+ content: [{ tag: 'list', attrs: { v: '2', type: 'product_list' } }, qualityControl]
1249
+ };
1250
+ }
1251
+ else {
1252
+ return { tag: 'biz', attrs: bizBase };
1253
+ }
1254
+ };
1255
+ // ── End button type helpers ───────────────────────────────────────────────
1256
+ return {
1257
+ ...sock,
1258
+ getPrivacyTokens,
1259
+ assertSessions,
1260
+ relayMessage,
1261
+ sendReceipt,
1262
+ sendReceipts,
1263
+ readMessages,
1264
+ refreshMediaConn,
1265
+ waUploadToServer,
1266
+ fetchPrivacySettings,
1267
+ sendPeerDataOperationMessage,
1268
+ createParticipantNodes,
1269
+ getUSyncDevices,
1270
+ messageRetryManager,
1271
+ updateMemberLabel,
1272
+ updateMediaMessage: async (message) => {
1273
+ const content = (0, index_js_3.assertMediaContent)(message.message);
1274
+ const mediaKey = content.mediaKey;
1275
+ const meId = authState.creds.me.id;
1276
+ const node = (0, index_js_3.encryptMediaRetryRequest)(message.key, mediaKey, meId);
1277
+ let error = undefined;
1278
+ await Promise.all([
1279
+ sendNode(node),
1280
+ waitForMsgMediaUpdate(async (update) => {
1281
+ const result = update.find(c => c.key.id === message.key.id);
1282
+ if (result) {
1283
+ if (result.error) {
1284
+ error = result.error;
1285
+ }
1286
+ else {
1287
+ try {
1288
+ const media = (0, index_js_3.decryptMediaRetryData)(result.media, mediaKey, result.key.id);
1289
+ if (media.result !== index_js_1.proto.MediaRetryNotification.ResultType.SUCCESS) {
1290
+ const resultStr = index_js_1.proto.MediaRetryNotification.ResultType[media.result];
1291
+ throw new boom_1.Boom(`Media re-upload failed by device (${resultStr})`, {
1292
+ data: media,
1293
+ statusCode: (0, index_js_3.getStatusCodeForMediaRetry)(media.result) || 404
1294
+ });
1295
+ }
1296
+ content.directPath = media.directPath;
1297
+ content.url = (0, index_js_3.getUrlFromDirectPath)(content.directPath);
1298
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
1299
+ }
1300
+ catch (err) {
1301
+ error = err;
1302
+ }
1303
+ }
1304
+ return true;
1305
+ }
1306
+ })
1307
+ ]);
1308
+ if (error) {
1309
+ throw error;
1310
+ }
1311
+ ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
1312
+ return message;
1313
+ },
1314
+ resize: async (media, width, height) => {
1315
+ const { getStream, toBuffer } = await Promise.resolve().then(() => __importStar(require('../Utils/messages-media.js')));
1316
+ let sharp;
1317
+ try {
1318
+ sharp = (await Promise.resolve().then(() => __importStar(require('sharp')))).default;
1319
+ }
1320
+ catch (_) { }
1321
+ if (!sharp)
1322
+ throw new Error('sharp is required for resize');
1323
+ const { stream } = await getStream(media);
1324
+ const buf = await toBuffer(stream);
1325
+ return sharp(buf).resize(width, height, { fit: 'cover' }).toBuffer();
1326
+ },
1327
+ sendStatusMentions: async (content, jids = []) => {
1328
+ const userJid = (0, index_js_4.jidNormalizedUser)(authState.creds.me.id);
1329
+ let allUsers = new Set();
1330
+ allUsers.add(userJid);
1331
+ for (const id of jids) {
1332
+ const isGroup = (0, index_js_4.isJidGroup)(id);
1333
+ const isPrivate = (0, index_js_4.isJidUser)(id);
1334
+ if (isGroup) {
1335
+ try {
1336
+ const metadata = (cachedGroupMetadata ? await cachedGroupMetadata(id) : null) || await groupMetadata(id);
1337
+ const participants = metadata.participants.map(p => (0, index_js_4.jidNormalizedUser)(p.id));
1338
+ participants.forEach(j => allUsers.add(j));
1339
+ }
1340
+ catch (error) {
1341
+ logger.error(`Error getting metadata for group ${id}: ${error}`);
1342
+ }
1343
+ }
1344
+ else if (isPrivate) {
1345
+ allUsers.add((0, index_js_4.jidNormalizedUser)(id));
1346
+ }
1347
+ }
1348
+ const uniqueUsers = Array.from(allUsers);
1349
+ const getRandomHexColor = () => '#' + Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0');
1350
+ const isMedia = content.image || content.video || content.audio;
1351
+ const isAudio = !!content.audio;
1352
+ const messageContent = { ...content };
1353
+ if (isMedia && !isAudio) {
1354
+ if (messageContent.text) {
1355
+ messageContent.caption = messageContent.text;
1356
+ delete messageContent.text;
1357
+ }
1358
+ delete messageContent.ptt;
1359
+ delete messageContent.font;
1360
+ delete messageContent.backgroundColor;
1361
+ delete messageContent.textColor;
1362
+ }
1363
+ if (isAudio) {
1364
+ delete messageContent.text;
1365
+ delete messageContent.caption;
1366
+ delete messageContent.font;
1367
+ delete messageContent.textColor;
1368
+ }
1369
+ const font = !isMedia ? (content.font ?? Math.floor(Math.random() * 9)) : undefined;
1370
+ const textColor = !isMedia ? (content.textColor ?? getRandomHexColor()) : undefined;
1371
+ const backgroundColor = (!isMedia || isAudio) ? (content.backgroundColor ?? getRandomHexColor()) : undefined;
1372
+ const ptt = isAudio ? (typeof content.ptt === 'boolean' ? content.ptt : true) : undefined;
1373
+ let msg;
1374
+ let mediaHandle;
1375
+ try {
1376
+ msg = await (0, index_js_3.generateWAMessage)(index_js_4.STORIES_JID, messageContent, {
1377
+ logger,
1378
+ userJid,
1379
+ getUrlInfo: text => (0, link_preview_js_1.getUrlInfo)(text, {
1380
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
1381
+ fetchOpts: { timeout: 3000 },
1382
+ logger,
1383
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1384
+ }),
1385
+ upload: async (encFilePath, opts) => {
1386
+ const up = await waUploadToServer(encFilePath, { ...opts });
1387
+ mediaHandle = up.handle;
1388
+ return up;
1389
+ },
1390
+ mediaCache: config.mediaCache,
1391
+ options: config.options,
1392
+ font,
1393
+ textColor,
1394
+ backgroundColor,
1395
+ ptt
1396
+ });
1397
+ }
1398
+ catch (error) {
1399
+ logger.error(`Error generating status message: ${error}`);
1400
+ throw error;
1401
+ }
1402
+ await relayMessage(index_js_4.STORIES_JID, msg.message, {
1403
+ messageId: msg.key.id,
1404
+ statusJidList: uniqueUsers,
1405
+ additionalNodes: [{
1406
+ tag: 'meta',
1407
+ attrs: {},
1408
+ content: [{
1409
+ tag: 'mentioned_users',
1410
+ attrs: {},
1411
+ content: jids.map(jid => ({
1412
+ tag: 'to',
1413
+ attrs: { jid: (0, index_js_4.jidNormalizedUser)(jid) }
1414
+ }))
1415
+ }]
1416
+ }]
1417
+ });
1418
+ for (const id of jids) {
1419
+ try {
1420
+ const normalizedId = (0, index_js_4.jidNormalizedUser)(id);
1421
+ const isPrivate = (0, index_js_4.isJidUser)(normalizedId);
1422
+ const type = isPrivate ? 'statusMentionMessage' : 'groupStatusMentionMessage';
1423
+ const protocolMessage = {
1424
+ [type]: {
1425
+ message: {
1426
+ protocolMessage: {
1427
+ key: msg.key,
1428
+ type: 25
1429
+ }
1430
+ }
1431
+ },
1432
+ messageContextInfo: {
1433
+ messageSecret: (0, crypto_1.randomBytes)(32)
1434
+ }
1435
+ };
1436
+ const statusMsg = await (0, index_js_3.generateWAMessageFromContent)(normalizedId, protocolMessage, {});
1437
+ await relayMessage(normalizedId, statusMsg.message, {
1438
+ additionalNodes: [{
1439
+ tag: 'meta',
1440
+ attrs: isPrivate
1441
+ ? { is_status_mention: 'true' }
1442
+ : { is_group_status_mention: 'true' }
1443
+ }]
1444
+ });
1445
+ await (0, generics_js_1.delay)(2000);
1446
+ }
1447
+ catch (error) {
1448
+ logger.error(`Error sending status mention to ${id}: ${error}`);
1449
+ }
1450
+ }
1451
+ return msg;
1452
+ },
1453
+ sendMessage: async (jid, content, options = {}) => {
1454
+ const userJid = authState.creds.me.id;
1455
+ // ── Normalize: buttons[].nativeFlowInfo -> interactiveButtons ──────
1456
+ if (typeof content === 'object' &&
1457
+ Array.isArray(content.buttons) &&
1458
+ content.buttons.length > 0 &&
1459
+ content.buttons.some(b => b.nativeFlowInfo)) {
1460
+ const interactiveButtons = content.buttons.map(b => {
1461
+ if (b.nativeFlowInfo) {
1462
+ return {
1463
+ name: b.nativeFlowInfo.name,
1464
+ buttonParamsJson: b.nativeFlowInfo.paramsJson || '{}'
1465
+ };
1466
+ }
1467
+ return {
1468
+ name: 'quick_reply',
1469
+ buttonParamsJson: JSON.stringify({
1470
+ display_text: b.buttonText?.displayText || b.buttonId || 'Button',
1471
+ id: b.buttonId || b.buttonText?.displayText || 'btn'
1472
+ })
1473
+ };
1474
+ });
1475
+ const { buttons, headerType, viewOnce, ...rest } = content;
1476
+ content = { ...rest, interactiveButtons };
1477
+ }
1478
+ // ── Interactive Button (sendButton logic) ──────────────────────────
1479
+ if (typeof content === 'object' && Array.isArray(content.interactiveButtons) && content.interactiveButtons.length > 0) {
1480
+ const { text = '', caption = '', title = '', footer = '', interactiveButtons, hasMediaAttachment = false, image = null, video = null, document = null, mimetype = null, jpegThumbnail = null, location = null, product = null, businessOwnerJid = null, externalAdReply = null, } = content;
1481
+ // Normalize buttons
1482
+ const processedButtons = [];
1483
+ for (let i = 0; i < interactiveButtons.length; i++) {
1484
+ const btn = interactiveButtons[i];
1485
+ if (!btn || typeof btn !== 'object')
1486
+ throw new Error(`interactiveButtons[${i}] must be an object`);
1487
+ if (btn.name && btn.buttonParamsJson) {
1488
+ processedButtons.push(btn);
1489
+ continue;
1490
+ }
1491
+ if (btn.id || btn.text || btn.displayText) {
1492
+ processedButtons.push({ name: 'quick_reply', buttonParamsJson: JSON.stringify({ display_text: btn.text || btn.displayText || `Button ${i + 1}`, id: btn.id || `quick_${i + 1}` }) });
1493
+ continue;
1494
+ }
1495
+ if (btn.buttonId && btn.buttonText?.displayText) {
1496
+ processedButtons.push({ name: 'quick_reply', buttonParamsJson: JSON.stringify({ display_text: btn.buttonText.displayText, id: btn.buttonId }) });
1497
+ continue;
1498
+ }
1499
+ throw new Error(`interactiveButtons[${i}] has invalid shape`);
1500
+ }
1501
+ let messageContent = {};
1502
+ // Header
1503
+ if (image) {
1504
+ const mi = Buffer.isBuffer(image) ? { image } : { image: { url: typeof image === 'object' ? image.url : image } };
1505
+ const pm = await (0, index_js_3.prepareWAMessageMedia)(mi, { upload: waUploadToServer });
1506
+ messageContent.header = { title: title || '', hasMediaAttachment: true, imageMessage: pm.imageMessage };
1507
+ }
1508
+ else if (video) {
1509
+ const mi = Buffer.isBuffer(video) ? { video } : { video: { url: typeof video === 'object' ? video.url : video } };
1510
+ const pm = await (0, index_js_3.prepareWAMessageMedia)(mi, { upload: waUploadToServer });
1511
+ messageContent.header = { title: title || '', hasMediaAttachment: true, videoMessage: pm.videoMessage };
1512
+ }
1513
+ else if (document) {
1514
+ const mi = Buffer.isBuffer(document) ? { document } : { document: { url: typeof document === 'object' ? document.url : document } };
1515
+ if (mimetype && typeof mi.document === 'object')
1516
+ mi.document.mimetype = mimetype;
1517
+ if (jpegThumbnail) {
1518
+ const thumb = Buffer.isBuffer(jpegThumbnail) ? jpegThumbnail : await (async () => { try {
1519
+ const r = await fetch(jpegThumbnail);
1520
+ return Buffer.from(await r.arrayBuffer());
1521
+ }
1522
+ catch {
1523
+ return undefined;
1524
+ } })();
1525
+ if (thumb)
1526
+ mi.document.jpegThumbnail = thumb;
1527
+ }
1528
+ const pm = await (0, index_js_3.prepareWAMessageMedia)(mi, { upload: waUploadToServer });
1529
+ messageContent.header = { title: title || '', hasMediaAttachment: true, documentMessage: pm.documentMessage };
1530
+ }
1531
+ else if (location && typeof location === 'object') {
1532
+ messageContent.header = { title: title || location.name || 'Location', hasMediaAttachment: false, locationMessage: { degreesLatitude: location.degreesLatitude || location.degressLatitude || 0, degreesLongitude: location.degreesLongitude || location.degressLongitude || 0, name: location.name || '', address: location.address || '' } };
1533
+ }
1534
+ else if (product && typeof product === 'object') {
1535
+ let productImageMessage = null;
1536
+ if (product.productImage) {
1537
+ const mi = Buffer.isBuffer(product.productImage) ? { image: product.productImage } : { image: { url: typeof product.productImage === 'object' ? product.productImage.url : product.productImage } };
1538
+ const pm = await (0, index_js_3.prepareWAMessageMedia)(mi, { upload: waUploadToServer });
1539
+ productImageMessage = pm.imageMessage;
1540
+ }
1541
+ messageContent.header = { title: title || product.title || 'Product', hasMediaAttachment: false, productMessage: { product: { productImage: productImageMessage, productId: product.productId || '', title: product.title || '', description: product.description || '', currencyCode: product.currencyCode || 'USD', priceAmount1000: parseInt(product.priceAmount1000) || 0, retailerId: product.retailerId || '', url: product.url || '', productImageCount: product.productImageCount || 1 }, businessOwnerJid: businessOwnerJid || product.businessOwnerJid || userJid } };
1542
+ }
1543
+ else if (title) {
1544
+ messageContent.header = { title, hasMediaAttachment: false };
1545
+ }
1546
+ const hasMedia = !!(image || video || document || location || product);
1547
+ const bodyText = hasMedia ? caption : text || caption;
1548
+ if (bodyText)
1549
+ messageContent.body = { text: bodyText };
1550
+ if (footer)
1551
+ messageContent.footer = { text: footer };
1552
+ messageContent.nativeFlowMessage = { buttons: processedButtons };
1553
+ // Context info
1554
+ if (externalAdReply && typeof externalAdReply === 'object') {
1555
+ messageContent.contextInfo = { externalAdReply: { title: externalAdReply.title || '', body: externalAdReply.body || '', mediaType: externalAdReply.mediaType || 1, sourceUrl: externalAdReply.sourceUrl || externalAdReply.url || '', thumbnailUrl: externalAdReply.thumbnailUrl || externalAdReply.thumbnail || '', renderLargerThumbnail: externalAdReply.renderLargerThumbnail || false, showAdAttribution: externalAdReply.showAdAttribution !== false, containsAutoReply: externalAdReply.containsAutoReply || false, ...(externalAdReply.mediaUrl && { mediaUrl: externalAdReply.mediaUrl }), ...(Buffer.isBuffer(externalAdReply.thumbnail) && { thumbnail: externalAdReply.thumbnail }), ...(externalAdReply.jpegThumbnail && { jpegThumbnail: externalAdReply.jpegThumbnail }) }, ...(options.mentionedJid && { mentionedJid: options.mentionedJid }) };
1556
+ }
1557
+ else if (options.mentionedJid) {
1558
+ messageContent.contextInfo = { mentionedJid: options.mentionedJid };
1559
+ }
1560
+ const payload = index_js_1.proto.Message.InteractiveMessage.create(messageContent);
1561
+ const msg = (0, index_js_3.generateWAMessageFromContent)(jid, { viewOnceMessage: { message: { interactiveMessage: payload } } }, { userJid, quoted: options?.quoted || null });
1562
+ const additionalNodes = [{ tag: 'biz', attrs: {}, content: [{ tag: 'interactive', attrs: { type: 'native_flow', v: '1' }, content: [{ tag: 'native_flow', attrs: { v: '9', name: 'mixed' } }] }] }];
1563
+ await relayMessage(jid, msg.message, { messageId: msg.key.id, additionalNodes });
1564
+ return msg;
1565
+ }
1566
+ // ── End Interactive Button ─────────────────────────────────────────
1567
+ if (typeof content === 'object' &&
1568
+ 'disappearingMessagesInChat' in content &&
1569
+ typeof content['disappearingMessagesInChat'] !== 'undefined' &&
1570
+ (0, index_js_4.isJidGroup)(jid)) {
1571
+ const { disappearingMessagesInChat } = content;
1572
+ const value = typeof disappearingMessagesInChat === 'boolean'
1573
+ ? disappearingMessagesInChat
1574
+ ? index_js_2.WA_DEFAULT_EPHEMERAL
1575
+ : 0
1576
+ : disappearingMessagesInChat;
1577
+ await groupToggleEphemeral(jid, value);
1578
+ }
1579
+ else {
1580
+ let mediaHandle;
1581
+ const fullMsg = await (0, index_js_3.generateWAMessage)(jid, content, {
1582
+ logger,
1583
+ userJid,
1584
+ getUrlInfo: text => (0, link_preview_js_1.getUrlInfo)(text, {
1585
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
1586
+ fetchOpts: {
1587
+ timeout: 3000,
1588
+ ...(httpRequestOptions || {})
1589
+ },
1590
+ logger,
1591
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1592
+ }),
1593
+ //TODO: CACHE
1594
+ getProfilePicUrl: sock.profilePictureUrl,
1595
+ getCallLink: sock.createCallLink,
1596
+ newsletter: _isNewsletterJid(jid),
1597
+ upload: async (encFilePath, opts) => {
1598
+ const up = await waUploadToServer(encFilePath, { ...opts, newsletter: _isNewsletterJid(jid) });
1599
+ mediaHandle = up.handle;
1600
+ return up;
1601
+ },
1602
+ mediaCache: config.mediaCache,
1603
+ options: config.options,
1604
+ messageId: (0, index_js_3.generateMessageIDV2)(sock.user?.id),
1605
+ ...options
1606
+ });
1607
+ if (content?.audio && options?.contextInfo) {
1608
+ const msgContent = fullMsg.message;
1609
+ if (msgContent?.audioMessage) {
1610
+ msgContent.audioMessage.contextInfo = options.contextInfo;
1611
+ }
1612
+ }
1613
+ // Extract handle from newsletter upload (set by prepareWAMessageMedia)
1614
+ if (!mediaHandle) {
1615
+ const msgContent = fullMsg.message;
1616
+ const msgTypes = ['audioMessage', 'imageMessage', 'videoMessage', 'documentMessage', 'stickerMessage'];
1617
+ for (const t of msgTypes) {
1618
+ if (msgContent?.[t]?._uploadHandle) {
1619
+ mediaHandle = msgContent[t]._uploadHandle;
1620
+ delete msgContent[t]._uploadHandle;
1621
+ break;
1622
+ }
1623
+ }
1624
+ }
1625
+ const isEventMsg = 'event' in content && !!content.event;
1626
+ const isDeleteMsg = 'delete' in content && !!content.delete;
1627
+ const isEditMsg = 'edit' in content && !!content.edit;
1628
+ const isPinMsg = 'pin' in content && !!content.pin;
1629
+ const isPollMessage = 'poll' in content && !!content.poll;
1630
+ const additionalAttributes = {};
1631
+ const additionalNodes = [];
1632
+ // required for delete
1633
+ if (isDeleteMsg) {
1634
+ // if the chat is a group, and I am not the author, then delete the message as an admin
1635
+ if ((0, index_js_4.isJidGroup)(content.delete?.remoteJid) && !content.delete?.fromMe) {
1636
+ additionalAttributes.edit = '8';
1637
+ }
1638
+ else {
1639
+ additionalAttributes.edit = '7';
1640
+ }
1641
+ }
1642
+ else if (isEditMsg) {
1643
+ additionalAttributes.edit = '1';
1644
+ }
1645
+ else if (isPinMsg) {
1646
+ additionalAttributes.edit = '2';
1647
+ }
1648
+ else if (isPollMessage) {
1649
+ additionalNodes.push({
1650
+ tag: 'meta',
1651
+ attrs: {
1652
+ polltype: 'creation'
1653
+ }
1654
+ });
1655
+ }
1656
+ else if (isEventMsg) {
1657
+ additionalNodes.push({
1658
+ tag: 'meta',
1659
+ attrs: {
1660
+ event_type: 'creation'
1661
+ }
1662
+ });
1663
+ }
1664
+ // Auto-attach biz node for button/list/interactive messages
1665
+ const buttonType = getButtonType(fullMsg.message);
1666
+ if (buttonType) {
1667
+ const btnNode = getButtonArgs(fullMsg.message);
1668
+ if (btnNode)
1669
+ additionalNodes.push(btnNode);
1670
+ }
1671
+ if (mediaHandle) {
1672
+ additionalAttributes['media_id'] = mediaHandle;
1673
+ }
1674
+ await relayMessage(jid, fullMsg.message, {
1675
+ messageId: fullMsg.key.id,
1676
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1677
+ additionalAttributes,
1678
+ statusJidList: options.statusJidList,
1679
+ additionalNodes,
1680
+ AI: options.ai || false
1681
+ });
1682
+ if (config.emitOwnEvents) {
1683
+ process.nextTick(async () => {
1684
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1685
+ });
1686
+ }
1687
+ return fullMsg;
1688
+ }
1689
+ }
1690
+ };
1691
+ };
1692
+ exports.makeMessagesSocket = makeMessagesSocket;