@synacwave/baileys 0.0.0-stage → 0.4.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 (229) hide show
  1. package/ATTRIBUTION.md +14 -0
  2. package/CHANGELOG.md +35 -0
  3. package/LICENSE +23 -0
  4. package/README.md +493 -2
  5. package/README.upstream.md +2077 -0
  6. package/WAProto/index.d.ts +15942 -0
  7. package/WAProto/index.js +115911 -0
  8. package/engine-requirements.js +13 -0
  9. package/lib/Defaults/index.d.ts +145 -0
  10. package/lib/Defaults/index.js +155 -0
  11. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  12. package/lib/Signal/Group/ciphertext-message.js +12 -0
  13. package/lib/Signal/Group/group-session-builder.d.ts +8 -0
  14. package/lib/Signal/Group/group-session-builder.js +30 -0
  15. package/lib/Signal/Group/group_cipher.d.ts +11 -0
  16. package/lib/Signal/Group/group_cipher.js +82 -0
  17. package/lib/Signal/Group/index.d.ts +12 -0
  18. package/lib/Signal/Group/index.js +12 -0
  19. package/lib/Signal/Group/keyhelper.d.ts +7 -0
  20. package/lib/Signal/Group/keyhelper.js +18 -0
  21. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  22. package/lib/Signal/Group/sender-chain-key.js +26 -0
  23. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  24. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  25. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  26. package/lib/Signal/Group/sender-key-message.js +66 -0
  27. package/lib/Signal/Group/sender-key-name.d.ts +12 -0
  28. package/lib/Signal/Group/sender-key-name.js +48 -0
  29. package/lib/Signal/Group/sender-key-record.d.ts +13 -0
  30. package/lib/Signal/Group/sender-key-record.js +41 -0
  31. package/lib/Signal/Group/sender-key-state.d.ts +17 -0
  32. package/lib/Signal/Group/sender-key-state.js +84 -0
  33. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  34. package/lib/Signal/Group/sender-message-key.js +26 -0
  35. package/lib/Signal/libsignal.d.ts +55 -0
  36. package/lib/Signal/libsignal.js +431 -0
  37. package/lib/Signal/lid-mapping.d.ts +21 -0
  38. package/lib/Signal/lid-mapping.js +277 -0
  39. package/lib/Socket/Client/index.d.ts +3 -0
  40. package/lib/Socket/Client/index.js +3 -0
  41. package/lib/Socket/Client/types.d.ts +6 -0
  42. package/lib/Socket/Client/types.js +11 -0
  43. package/lib/Socket/Client/websocket.d.ts +13 -0
  44. package/lib/Socket/Client/websocket.js +54 -0
  45. package/lib/Socket/business.d.ts +395 -0
  46. package/lib/Socket/business.js +380 -0
  47. package/lib/Socket/chats.d.ts +144 -0
  48. package/lib/Socket/chats.js +1219 -0
  49. package/lib/Socket/communities.d.ts +562 -0
  50. package/lib/Socket/communities.js +432 -0
  51. package/lib/Socket/groups.d.ts +286 -0
  52. package/lib/Socket/groups.js +348 -0
  53. package/lib/Socket/index.d.ts +531 -0
  54. package/lib/Socket/index.js +13 -0
  55. package/lib/Socket/messages-recv.d.ts +334 -0
  56. package/lib/Socket/messages-recv.js +1772 -0
  57. package/lib/Socket/messages-send.d.ts +330 -0
  58. package/lib/Socket/messages-send.js +1372 -0
  59. package/lib/Socket/mex.d.ts +2 -0
  60. package/lib/Socket/mex.js +42 -0
  61. package/lib/Socket/newsletter.d.ts +283 -0
  62. package/lib/Socket/newsletter.js +226 -0
  63. package/lib/Socket/socket.d.ts +61 -0
  64. package/lib/Socket/socket.js +970 -0
  65. package/lib/Store/index.d.ts +4 -0
  66. package/lib/Store/index.js +4 -0
  67. package/lib/Store/make-in-memory-store.d.ts +63 -0
  68. package/lib/Store/make-in-memory-store.js +421 -0
  69. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  70. package/lib/Store/make-ordered-dictionary.js +79 -0
  71. package/lib/Store/object-repository.d.ts +11 -0
  72. package/lib/Store/object-repository.js +24 -0
  73. package/lib/Types/Auth.d.ts +2 -0
  74. package/lib/Types/Auth.js +2 -0
  75. package/lib/Types/Bussines.d.ts +2 -0
  76. package/lib/Types/Bussines.js +2 -0
  77. package/lib/Types/Call.d.ts +2 -0
  78. package/lib/Types/Call.js +2 -0
  79. package/lib/Types/Chat.d.ts +2 -0
  80. package/lib/Types/Chat.js +8 -0
  81. package/lib/Types/Contact.d.ts +2 -0
  82. package/lib/Types/Contact.js +2 -0
  83. package/lib/Types/Events.d.ts +2 -0
  84. package/lib/Types/Events.js +2 -0
  85. package/lib/Types/GroupMetadata.d.ts +2 -0
  86. package/lib/Types/GroupMetadata.js +2 -0
  87. package/lib/Types/Label.d.ts +3 -0
  88. package/lib/Types/Label.js +25 -0
  89. package/lib/Types/LabelAssociation.d.ts +3 -0
  90. package/lib/Types/LabelAssociation.js +7 -0
  91. package/lib/Types/Message.d.ts +12 -0
  92. package/lib/Types/Message.js +18 -0
  93. package/lib/Types/Mex.d.ts +3 -0
  94. package/lib/Types/Mex.js +39 -0
  95. package/lib/Types/Product.d.ts +2 -0
  96. package/lib/Types/Product.js +2 -0
  97. package/lib/Types/RichType.d.ts +3 -0
  98. package/lib/Types/RichType.js +23 -0
  99. package/lib/Types/Signal.d.ts +2 -0
  100. package/lib/Types/Signal.js +2 -0
  101. package/lib/Types/Socket.d.ts +2 -0
  102. package/lib/Types/Socket.js +2 -0
  103. package/lib/Types/State.d.ts +6 -0
  104. package/lib/Types/State.js +56 -0
  105. package/lib/Types/USync.d.ts +2 -0
  106. package/lib/Types/USync.js +2 -0
  107. package/lib/Types/index.d.ts +14 -0
  108. package/lib/Types/index.js +26 -0
  109. package/lib/Utils/api-wrappers.d.ts +70 -0
  110. package/lib/Utils/api-wrappers.js +248 -0
  111. package/lib/Utils/auth-utils.d.ts +58 -0
  112. package/lib/Utils/auth-utils.js +306 -0
  113. package/lib/Utils/browser-utils.d.ts +10 -0
  114. package/lib/Utils/browser-utils.js +29 -0
  115. package/lib/Utils/business.d.ts +50 -0
  116. package/lib/Utils/business.js +231 -0
  117. package/lib/Utils/chat-utils.d.ts +409 -0
  118. package/lib/Utils/chat-utils.js +886 -0
  119. package/lib/Utils/companion-reg-client-utils.d.ts +5 -0
  120. package/lib/Utils/companion-reg-client-utils.js +40 -0
  121. package/lib/Utils/crypto.d.ts +40 -0
  122. package/lib/Utils/crypto.js +118 -0
  123. package/lib/Utils/decode-wa-message.d.ts +84 -0
  124. package/lib/Utils/decode-wa-message.js +317 -0
  125. package/lib/Utils/event-buffer.d.ts +13 -0
  126. package/lib/Utils/event-buffer.js +622 -0
  127. package/lib/Utils/generics.d.ts +64 -0
  128. package/lib/Utils/generics.js +395 -0
  129. package/lib/Utils/history.d.ts +76 -0
  130. package/lib/Utils/history.js +134 -0
  131. package/lib/Utils/identity-change-handler.d.ts +14 -0
  132. package/lib/Utils/identity-change-handler.js +50 -0
  133. package/lib/Utils/index.d.ts +28 -0
  134. package/lib/Utils/index.js +30 -0
  135. package/lib/Utils/link-preview.d.ts +13 -0
  136. package/lib/Utils/link-preview.js +85 -0
  137. package/lib/Utils/logger.d.ts +3 -0
  138. package/lib/Utils/logger.js +3 -0
  139. package/lib/Utils/lt-hash.d.ts +7 -0
  140. package/lib/Utils/lt-hash.js +8 -0
  141. package/lib/Utils/make-mutex.d.ts +7 -0
  142. package/lib/Utils/make-mutex.js +33 -0
  143. package/lib/Utils/message-retry-manager.d.ts +80 -0
  144. package/lib/Utils/message-retry-manager.js +265 -0
  145. package/lib/Utils/messages-media.d.ts +137 -0
  146. package/lib/Utils/messages-media.js +843 -0
  147. package/lib/Utils/messages.d.ts +46 -0
  148. package/lib/Utils/messages.js +1840 -0
  149. package/lib/Utils/noise-handler.d.ts +21 -0
  150. package/lib/Utils/noise-handler.js +201 -0
  151. package/lib/Utils/offline-node-processor.d.ts +10 -0
  152. package/lib/Utils/offline-node-processor.js +40 -0
  153. package/lib/Utils/pre-key-manager.d.ts +26 -0
  154. package/lib/Utils/pre-key-manager.js +106 -0
  155. package/lib/Utils/process-message.d.ts +84 -0
  156. package/lib/Utils/process-message.js +749 -0
  157. package/lib/Utils/reporting-utils.d.ts +13 -0
  158. package/lib/Utils/reporting-utils.js +258 -0
  159. package/lib/Utils/rich-message-utils.d.ts +49 -0
  160. package/lib/Utils/rich-message-utils.js +363 -0
  161. package/lib/Utils/signal.d.ts +83 -0
  162. package/lib/Utils/signal.js +201 -0
  163. package/lib/Utils/stanza-ack.d.ts +17 -0
  164. package/lib/Utils/stanza-ack.js +38 -0
  165. package/lib/Utils/status-utils.js +178 -0
  166. package/lib/Utils/sticker-reaction.js +104 -0
  167. package/lib/Utils/synacwave.d.ts +111 -0
  168. package/lib/Utils/synacwave.js +474 -0
  169. package/lib/Utils/sync-action-utils.d.ts +3 -0
  170. package/lib/Utils/sync-action-utils.js +49 -0
  171. package/lib/Utils/tc-token-utils.d.ts +30 -0
  172. package/lib/Utils/tc-token-utils.js +164 -0
  173. package/lib/Utils/use-multi-file-auth-state.d.ts +11 -0
  174. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  175. package/lib/Utils/use-single-file-auth-state.d.ts +11 -0
  176. package/lib/Utils/use-single-file-auth-state.js +109 -0
  177. package/lib/Utils/use-sqlite-auth-state.d.ts +11 -0
  178. package/lib/Utils/use-sqlite-auth-state.js +109 -0
  179. package/lib/Utils/validate-connection.d.ts +44 -0
  180. package/lib/Utils/validate-connection.js +210 -0
  181. package/lib/Utils/view-once-text.d.ts +32 -0
  182. package/lib/Utils/view-once-text.js +213 -0
  183. package/lib/WABinary/constants.d.ts +62 -0
  184. package/lib/WABinary/constants.js +1467 -0
  185. package/lib/WABinary/decode.d.ts +10 -0
  186. package/lib/WABinary/decode.js +262 -0
  187. package/lib/WABinary/encode.d.ts +3 -0
  188. package/lib/WABinary/encode.js +220 -0
  189. package/lib/WABinary/generic-utils.d.ts +77 -0
  190. package/lib/WABinary/generic-utils.js +226 -0
  191. package/lib/WABinary/index.d.ts +6 -0
  192. package/lib/WABinary/index.js +6 -0
  193. package/lib/WABinary/jid-utils.d.ts +29 -0
  194. package/lib/WABinary/jid-utils.js +96 -0
  195. package/lib/WABinary/types.d.ts +2 -0
  196. package/lib/WABinary/types.js +2 -0
  197. package/lib/WAM/BinaryInfo.d.ts +8 -0
  198. package/lib/WAM/BinaryInfo.js +10 -0
  199. package/lib/WAM/constants.d.ts +34927 -0
  200. package/lib/WAM/constants.js +22853 -0
  201. package/lib/WAM/encode.d.ts +2 -0
  202. package/lib/WAM/encode.js +150 -0
  203. package/lib/WAM/index.d.ts +4 -0
  204. package/lib/WAM/index.js +4 -0
  205. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +37 -0
  206. package/lib/WAUSync/Protocols/USyncContactProtocol.js +52 -0
  207. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  208. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  209. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  210. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  211. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  212. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  213. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  214. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  215. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +39 -0
  216. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  217. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +15 -0
  218. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  219. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  220. package/lib/WAUSync/Protocols/index.js +6 -0
  221. package/lib/WAUSync/USyncQuery.d.ts +21 -0
  222. package/lib/WAUSync/USyncQuery.js +98 -0
  223. package/lib/WAUSync/USyncUser.d.ts +17 -0
  224. package/lib/WAUSync/USyncUser.js +31 -0
  225. package/lib/WAUSync/index.d.ts +4 -0
  226. package/lib/WAUSync/index.js +4 -0
  227. package/lib/index.d.ts +12 -0
  228. package/lib/index.js +12 -0
  229. package/package.json +118 -5
@@ -0,0 +1,111 @@
1
+ import type { proto } from '../../WAProto/index.js';
2
+ import type { ViewOnceTextOptions, ViewOnceTextResult } from './view-once-text.js';
3
+ import type { ApiWrapperMethods } from './api-wrappers.js';
4
+
5
+ export type MediaInput = Buffer | string | { url: string };
6
+
7
+ export interface ChatThemeOptions {
8
+ /** Colour name from CHAT_THEME_COLORS, a preset key, or hex (RRGGBB / #RRGGBB / RRGGBBAA). */
9
+ color?: string;
10
+ /** Bubble scheme id (e.g. 'Emerald@Minimal') or a preset key (e.g. 'blue'). */
11
+ scheme?: string;
12
+ stockImageId?: string;
13
+ clear?: boolean;
14
+ wallpaper?: WallpaperMedia;
15
+ dimLevel?: number;
16
+ timestampMs?: number;
17
+ }
18
+ export interface WallpaperMedia {
19
+ directPath: string;
20
+ mediaKey: Uint8Array;
21
+ fileEncSha256: Uint8Array;
22
+ fileSha256: Uint8Array;
23
+ }
24
+ export interface ChatThemeResult { id: string; setting: proto.Message.IChatThemeSetting }
25
+ export interface SoundStickerInput {
26
+ sticker: MediaInput;
27
+ /** Ogg/Opus audio when mimetype contains "opus" */
28
+ audio: MediaInput;
29
+ mimetype?: string;
30
+ seconds?: number;
31
+ isAnimated?: boolean;
32
+ }
33
+ export interface MessageContext {
34
+ id?: string | null;
35
+ chat?: string | null;
36
+ sender?: string | null;
37
+ fromMe: boolean;
38
+ isGroup: boolean;
39
+ type?: string;
40
+ text: string;
41
+ mentions: string[];
42
+ isReply: boolean;
43
+ quoted: proto.IWebMessageInfo | { key: any; message: proto.IMessage } | null;
44
+ quotedText: string;
45
+ isMedia: boolean;
46
+ isViewOnce: boolean;
47
+ raw: proto.IWebMessageInfo;
48
+ }
49
+
50
+ export declare const MAX_REMOTE_MEDIA_BYTES: number;
51
+ export declare const CHAT_THEME_COLORS: Record<string, string>;
52
+ export declare const CHAT_BUBBLE_SCHEMES: Record<string, string>;
53
+ export declare const CHAT_THEME_PRESETS: Record<string, { scheme: string; bgLight: number; bgDark: number; doodleLight: number; doodleDark: number }>;
54
+ export declare const parseThemeColor: (input: string) => number | null;
55
+ export declare const buildChatThemeSetting: (opts?: ChatThemeOptions) => proto.Message.IChatThemeSetting;
56
+ export declare const verifyChatThemeEncoding: (setting: proto.Message.IChatThemeSetting) => { bytes: Uint8Array; decoded: proto.Message.IChatThemeSetting };
57
+ export declare const uploadChatWallpaper: (sock: any, image: Buffer, opts?: { logger?: any }) => Promise<WallpaperMedia>;
58
+ export declare const isAnimatedWebP: (buf: Buffer) => boolean;
59
+ export declare const isOggOpus: (buf: Buffer) => boolean;
60
+ export declare const verifySoundStickerWire: (message: proto.IMessage) => { bytes: Buffer; audioBytes: Buffer };
61
+ export declare const downloadRemoteMedia: (url: string, opts?: { maxBytes?: number; timeoutMs?: number; maxRedirects?: number }) => Promise<Buffer>;
62
+ export declare const getMessageType: (msg: any) => string | undefined;
63
+ export declare const getMessageText: (msg: any) => string;
64
+ export declare const getMentions: (msg: any) => string[];
65
+ export declare const getQuotedMessage: (msg: any) => { key: any; message: proto.IMessage } | null;
66
+ export declare const isViewOnce: (msg: any) => boolean;
67
+ export declare const isMediaMessage: (msg: any) => boolean;
68
+ export declare const buildMessageContext: (msg: proto.IWebMessageInfo, selfJid?: string) => MessageContext;
69
+ export declare const META_AI_JIDS: string[];
70
+ export declare const isMetaAiParticipant: (p: any) => boolean;
71
+ export declare const formatMention: (jid: string) => string;
72
+
73
+ export interface SynacwaveSocketExtensions extends ApiWrapperMethods {
74
+ sendViewOnceText(jid: string, text: string, options?: ViewOnceTextOptions): Promise<ViewOnceTextResult>;
75
+ sendViewOnceTextMessage(jid: string, text: string, options?: ViewOnceTextOptions): Promise<ViewOnceTextResult>;
76
+ sendVotext(jid: string, text: string, options?: ViewOnceTextOptions): Promise<ViewOnceTextResult>;
77
+ /** `current` is the favorites list you already know; WhatsApp syncs it as one value. */
78
+ addToFavorites(jids: string | string[], opts?: { current?: string[] }): Promise<void>;
79
+ removeFromFavorites(jids: string | string[], opts?: { current?: string[] }): Promise<void>;
80
+ sendSoundSticker(jid: string, input: SoundStickerInput, options?: { quoted?: proto.IWebMessageInfo; messageId?: string }): Promise<proto.IWebMessageInfo>;
81
+ /** colour / scheme string, wallpaper Buffer or URL, null to clear, or an options object */
82
+ setChatTheme(jid: string, value: string | Buffer | null | ChatThemeOptions): Promise<ChatThemeResult>;
83
+ setChatThemeColor(jid: string, color: string): Promise<ChatThemeResult>;
84
+ setChatBubbleScheme(jid: string, scheme: string): Promise<ChatThemeResult>;
85
+ setChatWallpaper(jid: string, image: MediaInput): Promise<ChatThemeResult>;
86
+ clearChatTheme(jid: string): Promise<ChatThemeResult>;
87
+ getChatThemeDiagnostics(): { encoderOk: boolean; error: string | null; type: string | null; wallpaperMediaMapped: boolean; note: string };
88
+ getMessageContext(msg: proto.IWebMessageInfo): Promise<MessageContext>;
89
+ getQuotedMessage: typeof getQuotedMessage;
90
+ getMessageText: typeof getMessageText;
91
+ getMessageType: typeof getMessageType;
92
+ getMentions: typeof getMentions;
93
+ isViewOnce: typeof isViewOnce;
94
+ getMediaBuffer(msg: proto.IWebMessageInfo, opts?: { maxBytes?: number }): Promise<Buffer>;
95
+ getBotJid(): string | undefined;
96
+ isFromBot(msg: proto.IWebMessageInfo): boolean;
97
+ isGroupAdmin(groupJid: string, jid: string): Promise<boolean>;
98
+ formatMention: typeof formatMention;
99
+ reply(msg: proto.IWebMessageInfo, text: string, options?: any): Promise<any>;
100
+ sendText(jid: string, text: string, options?: any): Promise<any>;
101
+ sendReact(msg: proto.IWebMessageInfo, emoji: string): Promise<any>;
102
+ sendImage(jid: string, image: MediaInput, caption?: string, options?: any): Promise<any>;
103
+ sendVideo(jid: string, video: MediaInput, caption?: string, options?: any): Promise<any>;
104
+ sendAudio(jid: string, audio: MediaInput, options?: { mimetype?: string; ptt?: boolean }): Promise<any>;
105
+ sendSticker(jid: string, sticker: MediaInput, options?: any): Promise<any>;
106
+ sendPremiumSticker(jid: string, sticker: MediaInput, options?: any): Promise<any>;
107
+ hasMetaAI(groupJid: string): Promise<boolean>;
108
+ addMetaAI(groupJid: string): Promise<{ ok: boolean; jid?: string; attempts: { jid: string; status?: string; error?: string }[] }>;
109
+ removeMetaAI(groupJid: string): Promise<{ ok: boolean; jid?: string; attempts: { jid: string; status?: string; error?: string }[] }>;
110
+ }
111
+ export declare const extendSocket: <T extends object>(sock: T, config?: any) => T & SynacwaveSocketExtensions;
@@ -0,0 +1,474 @@
1
+ import { lookup } from 'dns/promises';
2
+ import { promises as fs } from 'fs';
3
+ import { isIP } from 'net';
4
+ import { Boom } from '@hapi/boom';
5
+ import { proto } from '../../WAProto/index.js';
6
+ import { jidNormalizedUser, areJidsSameUser, isJidGroup } from '../WABinary/index.js';
7
+ import { encryptedStream } from './messages-media.js';
8
+ import { generateMessageIDV2 } from './generics.js';
9
+ import { createApiWrappers } from './api-wrappers.js';
10
+ import { sendViewOnceTextWithSocket } from './view-once-text.js';
11
+ import { sendGroupStatusMessage, sendGroupStatusMessageClosefriends, sendStatus, buildGroupStatusContextInfo, STATUS_RING_PALETTE } from './status-utils.js';
12
+ import { sendStickerReaction, buildStickerReactionPayload, extractStickerMessage, isStickerReactionMessage, ASSOCIATION_TYPE_STICKER_REACTION } from './sticker-reaction.js';
13
+ import { generateWAMessageFromContent, getContentType, normalizeMessageContent, prepareWAMessageMedia, downloadMediaMessage } from './messages.js';
14
+
15
+ export const MAX_REMOTE_MEDIA_BYTES = 16 * 1024 * 1024;
16
+
17
+ export const CHAT_THEME_COLORS = {
18
+ red: 'FF0000', green: '00FF00', blue: '0000FF', yellow: 'FFFF00',
19
+ orange: 'FF8000', pink: 'FF69B4', purple: '800080', black: '000000',
20
+ white: 'FFFFFF', brown: 'A52A2A', grey: '808080', gray: '808080',
21
+ cyan: '00FFFF', lime: '00FF00', gold: 'FFD700', silver: 'C0C0C0',
22
+ maroon: '800000', navy: '000080', teal: '008080', magenta: 'FF00FF',
23
+ violet: '8A2BE2', indigo: '4B0082', peach: 'FFDAB9', sky: '87CEEB',
24
+ mint: '98FF98', coral: 'FF7F50', lavender: 'E6E6FA', crimson: 'DC143C',
25
+ turquoise: '40E0D0'
26
+ };
27
+
28
+ export const CHAT_BUBBLE_SCHEMES = {
29
+ blue: 'Default-Blue@Minimal',
30
+ tonal: 'Default-Blue@Tonal@Minimal',
31
+ emerald: 'Emerald@Minimal',
32
+ emeraldtonal: 'Emerald@Tonal@Minimal',
33
+ pink: 'Pink@Minimal',
34
+ red: 'Red@Minimal',
35
+ royal: 'Royal-Blue@Minimal',
36
+ purple: 'Tyrian-Purple@Minimal',
37
+ green: 'WhatsApp-Green@Minimal'
38
+ };
39
+
40
+ const preset = (scheme, bgLight, bgDark, doodleLight, doodleDark) => ({ scheme, bgLight, bgDark, doodleLight, doodleDark });
41
+ export const CHAT_THEME_PRESETS = {
42
+ blue: preset(CHAT_BUBBLE_SCHEMES.blue, 0xffe7f3fb, 0xff0b141a, 0xff7ec8e3, 0xff4a9fd8),
43
+ tonal: preset(CHAT_BUBBLE_SCHEMES.tonal, 0xffe7f3fb, 0xff0b141a, 0xff7ec8e3, 0xff4a9fd8),
44
+ emerald: preset(CHAT_BUBBLE_SCHEMES.emerald, 0xffe8f8ef, 0xff0b1a12, 0xff6bcf9b, 0xff3d9b6e),
45
+ emeraldtonal: preset(CHAT_BUBBLE_SCHEMES.emeraldtonal, 0xffe8f8ef, 0xff0b1a12, 0xff6bcf9b, 0xff3d9b6e),
46
+ pink: preset(CHAT_BUBBLE_SCHEMES.pink, 0xfffff0f5, 0xff1a0b12, 0xfff48fb1, 0xffe91e8c),
47
+ red: preset(CHAT_BUBBLE_SCHEMES.red, 0xffffebee, 0xff1a0b0b, 0xffef9a9a, 0xffe53935),
48
+ royal: preset(CHAT_BUBBLE_SCHEMES.royal, 0xffe8eeff, 0xff0b0f1a, 0xff90caf9, 0xff3f51b5),
49
+ purple: preset(CHAT_BUBBLE_SCHEMES.purple, 0xfff3e5f5, 0xff120b1a, 0xffce93d8, 0xff9c27b0),
50
+ green: preset(CHAT_BUBBLE_SCHEMES.green, 0xffe8f5e9, 0xff0b1a0f, 0xffa5d6a7, 0xff25d366)
51
+ };
52
+
53
+ export const parseThemeColor = (input) => {
54
+ const raw = String(input ?? '').trim().toLowerCase();
55
+ if (CHAT_THEME_COLORS[raw]) {
56
+ return parseInt(CHAT_THEME_COLORS[raw], 16);
57
+ }
58
+ const hex = raw.replace(/^#/, '');
59
+ if (/^[0-9a-f]{6}([0-9a-f]{2})?$/.test(hex)) {
60
+ return parseInt(hex.slice(0, 6), 16);
61
+ }
62
+ return null;
63
+ };
64
+
65
+ const argb = (rgb) => (0xff000000 | rgb) >>> 0;
66
+ const darken = (rgb, k = 0.35) => {
67
+ const r = Math.round(((rgb >> 16) & 255) * k);
68
+ const g = Math.round(((rgb >> 8) & 255) * k);
69
+ const b = Math.round((rgb & 255) * k);
70
+ return argb((r << 16) | (g << 8) | b);
71
+ };
72
+
73
+ export const buildChatThemeSetting = (opts = {}) => {
74
+ const settingTimestampMs = opts.timestampMs ?? Date.now();
75
+ if (opts.clear) {
76
+ return { settingTimestampMs, clearTheme: true };
77
+ }
78
+ if (opts.wallpaper) {
79
+ const w = opts.wallpaper;
80
+ for (const k of ['directPath', 'mediaKey', 'fileEncSha256', 'fileSha256']) {
81
+ if (!w[k]) {
82
+ throw new Boom(`wallpaper media descriptor is missing ${k}`, { statusCode: 400 });
83
+ }
84
+ }
85
+ return { settingTimestampMs, customImage: { directPath: w.directPath, mediaKey: w.mediaKey, fileEncSha256: w.fileEncSha256, fileSha256: w.fileSha256, dimLevel: opts.dimLevel ?? 0 } };
86
+ }
87
+ if (opts.stockImageId) {
88
+ return { settingTimestampMs, stockImage: { stockImageId: opts.stockImageId, dimLevel: opts.dimLevel ?? 0 } };
89
+ }
90
+ if (opts.scheme) {
91
+ const key = String(opts.scheme).trim().toLowerCase().replace(/[\s_-]+/g, '');
92
+ const p = CHAT_THEME_PRESETS[key] || Object.values(CHAT_THEME_PRESETS).find(v => v.scheme === opts.scheme);
93
+ const base = p || { scheme: opts.scheme, bgLight: 0xffe8f4fd, bgDark: 0xff0b141a, doodleLight: 0xff7ec8e3, doodleDark: 0xff4a9fd8 };
94
+ return {
95
+ settingTimestampMs,
96
+ colorSchemeId: base.scheme,
97
+ solidColor: { backgroundLightArgb: base.bgLight >>> 0, backgroundDarkArgb: base.bgDark >>> 0, isDoodleEnabled: true, doodleLightArgb: base.doodleLight >>> 0, doodleDarkArgb: base.doodleDark >>> 0 }
98
+ };
99
+ }
100
+ if (opts.color) {
101
+ const key = String(opts.color).trim().toLowerCase().replace(/[\s_-]+/g, '');
102
+ if (CHAT_THEME_PRESETS[key]) {
103
+ return buildChatThemeSetting({ scheme: key, timestampMs: settingTimestampMs });
104
+ }
105
+ const rgb = parseThemeColor(opts.color);
106
+ if (rgb == null) {
107
+ throw new Boom(`Invalid theme colour: ${opts.color}`, { statusCode: 400 });
108
+ }
109
+ const light = argb(rgb);
110
+ const dark = darken(rgb);
111
+ return { settingTimestampMs, solidColor: { backgroundLightArgb: light, backgroundDarkArgb: dark, isDoodleEnabled: true, doodleLightArgb: light, doodleDarkArgb: dark } };
112
+ }
113
+ throw new Boom('buildChatThemeSetting needs one of: color, scheme, wallpaper, stockImageId, clear', { statusCode: 400 });
114
+ };
115
+
116
+ export const verifyChatThemeEncoding = (setting) => {
117
+ const content = { protocolMessage: { type: 34, chatThemeSetting: setting } };
118
+ const bytes = proto.Message.encode(proto.Message.fromObject(content)).finish();
119
+ const back = proto.Message.decode(bytes);
120
+ const pm = back.protocolMessage;
121
+ if (!pm || pm.type !== 34 || !pm.chatThemeSetting) {
122
+ throw new Boom('chatThemeSetting did not survive protobuf encoding', { statusCode: 500 });
123
+ }
124
+ return { bytes, decoded: pm.chatThemeSetting };
125
+ };
126
+
127
+ export const uploadChatWallpaper = async (sock, image, { logger } = {}) => {
128
+ if (typeof sock.waUploadToServer !== 'function') {
129
+ throw new Boom('waUploadToServer is not available on this socket', { statusCode: 500 });
130
+ }
131
+ const media = Buffer.isBuffer(image) ? image : image;
132
+ const enc = await encryptedStream(media, 'chat-wallpaper-image', { logger: logger || sock.logger });
133
+ try {
134
+ const uploaded = await sock.waUploadToServer(enc.encFilePath, { mediaType: 'chat-wallpaper-image', fileEncSha256B64: enc.fileEncSha256.toString('base64') });
135
+ if (!uploaded?.directPath) {
136
+ throw new Boom('Wallpaper upload returned no directPath', { statusCode: 502 });
137
+ }
138
+ return { directPath: uploaded.directPath, mediaKey: enc.mediaKey, fileEncSha256: enc.fileEncSha256, fileSha256: enc.fileSha256 };
139
+ }
140
+ finally {
141
+ await fs.unlink(enc.encFilePath).catch(() => { });
142
+ if (enc.originalFilePath) {
143
+ await fs.unlink(enc.originalFilePath).catch(() => { });
144
+ }
145
+ }
146
+ };
147
+
148
+ export const isAnimatedWebP = (buf) => {
149
+ if (!Buffer.isBuffer(buf) || buf.length < 21) {
150
+ return false;
151
+ }
152
+ if (buf.toString('ascii', 0, 4) !== 'RIFF' || buf.toString('ascii', 8, 12) !== 'WEBP') {
153
+ return false;
154
+ }
155
+ if (buf.toString('ascii', 12, 16) === 'VP8X') {
156
+ return (buf[20] & 0x02) !== 0;
157
+ }
158
+ return buf.includes(Buffer.from('ANIM'));
159
+ };
160
+
161
+ export const isOggOpus = (buf) => Buffer.isBuffer(buf) && buf.length > 36 && buf.toString('ascii', 0, 4) === 'OggS' && buf.includes(Buffer.from('OpusHead'));
162
+
163
+ const readFields = (buf) => {
164
+ const out = [];
165
+ let pos = 0;
166
+ const varint = () => { let v = 0, shift = 0, b; do { b = buf[pos++]; v += (b & 0x7f) * 2 ** shift; shift += 7; } while (b & 0x80 && pos < buf.length); return v; };
167
+ while (pos < buf.length) {
168
+ const tag = varint();
169
+ const field = Math.floor(tag / 8), wire = tag & 7;
170
+ let start = pos, end;
171
+ if (wire === 0) { varint(); end = pos; }
172
+ else if (wire === 1) { pos += 8; end = pos; }
173
+ else if (wire === 2) { const len = varint(); start = pos; pos += len; end = pos; }
174
+ else if (wire === 5) { pos += 4; end = pos; }
175
+ else { throw new Boom(`unsupported wire type ${wire}`); }
176
+ out.push({ field, wire, start, end });
177
+ }
178
+ return out;
179
+ };
180
+
181
+ export const verifySoundStickerWire = (message) => {
182
+ const bytes = Buffer.from(proto.Message.encode(proto.Message.fromObject(message)).finish());
183
+ const decoded = proto.Message.decode(bytes);
184
+ if (!decoded.stickerMessage?.audioMessage) {
185
+ throw new Boom('audioMessage was dropped during StickerMessage encoding', { statusCode: 500 });
186
+ }
187
+ const stickerBytes = Buffer.from(proto.Message.StickerMessage.encode(proto.Message.StickerMessage.fromObject(message.stickerMessage)).finish());
188
+ const audioField = readFields(stickerBytes).find(f => f.field === 26 && f.wire === 2);
189
+ if (!audioField) {
190
+ throw new Boom('StickerMessage field 26 missing on the wire', { statusCode: 500 });
191
+ }
192
+ return { bytes, audioBytes: stickerBytes.subarray(audioField.start, audioField.end) };
193
+ };
194
+
195
+ const isPrivateAddress = (addr) => {
196
+ if (isIP(addr) === 6) {
197
+ const a = addr.toLowerCase();
198
+ return a === '::1' || a === '::' || a.startsWith('fc') || a.startsWith('fd') || a.startsWith('fe80') || (a.startsWith('::ffff:') && isPrivateAddress(a.slice(7)));
199
+ }
200
+ const p = addr.split('.').map(Number);
201
+ if (p.length !== 4 || p.some(n => Number.isNaN(n))) {
202
+ return true;
203
+ }
204
+ const [a, b] = p;
205
+ return a === 0 || a === 10 || a === 127 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127) || a >= 224;
206
+ };
207
+
208
+ export const downloadRemoteMedia = async (url, { maxBytes = MAX_REMOTE_MEDIA_BYTES, timeoutMs = 20000, maxRedirects = 3 } = {}) => {
209
+ let current = new URL(url);
210
+ for (let hop = 0; hop <= maxRedirects; hop++) {
211
+ if (!['http:', 'https:'].includes(current.protocol)) {
212
+ throw new Boom('Only http(s) URLs are allowed', { statusCode: 400 });
213
+ }
214
+ const host = current.hostname.replace(/^\[|\]$/g, '');
215
+ const addrs = isIP(host) ? [{ address: host }] : await lookup(host, { all: true });
216
+ if (!addrs.length || addrs.some(a => isPrivateAddress(a.address))) {
217
+ throw new Boom('Blocked host (private or unresolved address)', { statusCode: 400 });
218
+ }
219
+ const res = await fetch(current, { redirect: 'manual', signal: AbortSignal.timeout(timeoutMs) });
220
+ if (res.status >= 300 && res.status < 400 && res.headers.get('location')) {
221
+ current = new URL(res.headers.get('location'), current);
222
+ continue;
223
+ }
224
+ if (!res.ok) {
225
+ throw new Boom(`Download failed with status ${res.status}`, { statusCode: 502 });
226
+ }
227
+ const declared = Number(res.headers.get('content-length') || 0);
228
+ if (declared > maxBytes) {
229
+ throw new Boom('Remote media exceeds size limit', { statusCode: 413 });
230
+ }
231
+ const chunks = [];
232
+ let total = 0;
233
+ for await (const chunk of res.body) {
234
+ total += chunk.length;
235
+ if (total > maxBytes) {
236
+ throw new Boom('Remote media exceeds size limit', { statusCode: 413 });
237
+ }
238
+ chunks.push(chunk);
239
+ }
240
+ return Buffer.concat(chunks);
241
+ }
242
+ throw new Boom('Too many redirects', { statusCode: 400 });
243
+ };
244
+
245
+ const toBuffer = async (input, opts) => {
246
+ if (Buffer.isBuffer(input)) {
247
+ return input;
248
+ }
249
+ if (typeof input === 'string' && /^https?:\/\
250
+ return downloadRemoteMedia(input, opts);
251
+ }
252
+ if (input?.url && /^https?:\/\
253
+ return downloadRemoteMedia(input.url, opts);
254
+ }
255
+ throw new Boom('Expected a Buffer or an http(s) URL', { statusCode: 400 });
256
+ };
257
+
258
+ const unwrap = (msg) => normalizeMessageContent(msg?.message ?? msg) || {};
259
+
260
+ export const getMessageType = (msg) => getContentType(unwrap(msg));
261
+
262
+ export const getMessageText = (msg) => {
263
+ const c = unwrap(msg);
264
+ const t = getContentType(c);
265
+ const m = t ? c[t] : undefined;
266
+ if (!m) {
267
+ return '';
268
+ }
269
+ if (typeof m === 'string') {
270
+ return m;
271
+ }
272
+ return m.text || m.caption || m.conversation || m.selectedDisplayText || m.selectedButtonId || m.title || m.name || '';
273
+ };
274
+
275
+ const contextOf = (msg) => {
276
+ const c = unwrap(msg);
277
+ const t = getContentType(c);
278
+ return t ? c[t]?.contextInfo : undefined;
279
+ };
280
+
281
+ export const getMentions = (msg) => contextOf(msg)?.mentionedJid ?? [];
282
+
283
+ export const getQuotedMessage = (msg) => {
284
+ const ci = contextOf(msg);
285
+ if (!ci?.quotedMessage) {
286
+ return null;
287
+ }
288
+ return { key: { remoteJid: msg.key?.remoteJid, id: ci.stanzaId, participant: ci.participant, fromMe: false }, message: ci.quotedMessage };
289
+ };
290
+
291
+ export const isViewOnce = (msg) => {
292
+ const raw = msg?.message ?? msg ?? {};
293
+ if (raw.viewOnceMessage || raw.viewOnceMessageV2 || raw.viewOnceMessageV2Extension) {
294
+ return true;
295
+ }
296
+ const c = unwrap(msg);
297
+ const t = getContentType(c);
298
+ return !!(t && c[t]?.viewOnce);
299
+ };
300
+
301
+ const MEDIA_TYPES = ['imageMessage', 'videoMessage', 'audioMessage', 'documentMessage', 'stickerMessage', 'ptvMessage'];
302
+ export const isMediaMessage = (msg) => MEDIA_TYPES.includes(getMessageType(msg));
303
+
304
+ export const buildMessageContext = (msg, selfJid) => {
305
+ const chat = msg.key?.remoteJid;
306
+ const sender = msg.key?.fromMe ? selfJid : (msg.key?.participant || msg.participant || chat);
307
+ const quoted = getQuotedMessage(msg);
308
+ return {
309
+ id: msg.key?.id,
310
+ chat,
311
+ sender,
312
+ fromMe: !!msg.key?.fromMe,
313
+ isGroup: !!chat && isJidGroup(chat),
314
+ type: getMessageType(msg),
315
+ text: getMessageText(msg),
316
+ mentions: getMentions(msg),
317
+ isReply: !!quoted,
318
+ quoted,
319
+ quotedText: quoted ? getMessageText(quoted) : '',
320
+ isMedia: isMediaMessage(msg),
321
+ isViewOnce: isViewOnce(msg),
322
+ raw: msg
323
+ };
324
+ };
325
+
326
+ export const META_AI_JIDS = ['867051314767696@bot', '11111111111@bot', '13135550002@s.whatsapp.net'];
327
+ const META_AI_USERS = new Set(['867051314767696', '11111111111', '13135550002']);
328
+ const participantIds = (p) => [p?.id, p?.jid, p?.phoneNumber, p?.lid].filter(v => typeof v === 'string' && v);
329
+ export const isMetaAiParticipant = (p) => participantIds(p).some(id => id.endsWith('@bot') || META_AI_USERS.has(id.split('@')[0].split(':')[0]));
330
+
331
+ export const formatMention = (jid) => `@${jidNormalizedUser(jid).split('@')[0]}`;
332
+
333
+ export const extendSocket = (sock, config = {}) => {
334
+ const selfJid = () => (sock.user?.id ? jidNormalizedUser(sock.user.id) : undefined);
335
+ const selfLid = () => (sock.user?.lid ? jidNormalizedUser(sock.user.lid) : undefined);
336
+
337
+ const relayTheme = async (jid, setting) => {
338
+ verifyChatThemeEncoding(setting);
339
+ const id = generateMessageIDV2(sock.user?.id);
340
+ await sock.relayMessage(jid, { protocolMessage: { type: 34, chatThemeSetting: setting } }, { messageId: id, additionalAttributes: { type: 'media' } });
341
+ return { id, setting };
342
+ };
343
+
344
+ const sendSoundSticker = async (jid, { sticker, audio, mimetype = 'audio/ogg; codecs=opus', seconds, isAnimated } = {}, options = {}) => {
345
+ const stickerBuf = await toBuffer(sticker);
346
+ const audioBuf = await toBuffer(audio);
347
+ if (/opus/i.test(mimetype) && !isOggOpus(audioBuf)) {
348
+ throw new Boom('audio must be an Ogg container with Opus (OpusHead not found)', { statusCode: 400 });
349
+ }
350
+ const upload = sock.waUploadToServer;
351
+ const stickerUp = await prepareWAMessageMedia({ sticker: stickerBuf }, { upload, logger: sock.logger, mediaUploadTimeoutMs: config.mediaUploadTimeoutMs });
352
+ const audioUp = await prepareWAMessageMedia({ audio: audioBuf, mimetype, ptt: false, ...(seconds != null ? { seconds } : {}) }, { upload, logger: sock.logger, mediaUploadTimeoutMs: config.mediaUploadTimeoutMs });
353
+ const stickerMessage = stickerUp.stickerMessage;
354
+ stickerMessage.isAnimated = isAnimated ?? isAnimatedWebP(stickerBuf);
355
+ stickerMessage.stickerSentTs = Date.now();
356
+ stickerMessage.audioMessage = audioUp.audioMessage;
357
+ const full = generateWAMessageFromContent(jid, { stickerMessage }, { userJid: sock.user?.id, quoted: options.quoted, messageId: options.messageId });
358
+ verifySoundStickerWire(full.message);
359
+ await sock.relayMessage(jid, full.message, { messageId: full.key.id });
360
+ return full;
361
+ };
362
+
363
+ const send = (jid, content, options) => sock.sendMessage(jid, content, options);
364
+
365
+ const metaAiUpdate = async (groupJid, action, extra = []) => {
366
+ const attempts = [];
367
+ for (const jid of [...new Set([...extra, ...META_AI_JIDS])]) {
368
+ try {
369
+ const res = await sock.groupParticipantsUpdate(groupJid, [jid], action);
370
+ const status = res?.[0]?.status != null ? String(res[0].status) : '200';
371
+ attempts.push({ jid, status });
372
+ if (status === '200') {
373
+ return { ok: true, jid, attempts };
374
+ }
375
+ }
376
+ catch (error) {
377
+ attempts.push({ jid, error: error.message });
378
+ }
379
+ }
380
+ return { ok: false, attempts };
381
+ };
382
+ const originalSendMessage = sock.sendMessage;
383
+
384
+ const getMediaBuffer = async (msg, { maxBytes = 64 * 1024 * 1024 } = {}) => {
385
+ const m = unwrap(msg);
386
+ const t = getContentType(m);
387
+ const declared = Number(m[t]?.fileLength ?? 0);
388
+ if (declared > maxBytes) {
389
+ throw new Boom('Media exceeds size limit', { statusCode: 413 });
390
+ }
391
+ const buf = await downloadMediaMessage(msg, 'buffer', {}, { logger: sock.logger, reuploadRequest: sock.updateMediaMessage });
392
+ if (buf.length > maxBytes) {
393
+ throw new Boom('Media exceeds size limit', { statusCode: 413 });
394
+ }
395
+ return buf;
396
+ };
397
+
398
+ const api = {
399
+ sendSoundSticker,
400
+
401
+ setChatTheme: async (jid, value) => {
402
+ if (value == null || (typeof value === 'string' && /^(clear|off|reset|none)$/i.test(value.trim()))) {
403
+ return relayTheme(jid, buildChatThemeSetting({ clear: true }));
404
+ }
405
+ if (Buffer.isBuffer(value) || (typeof value === 'string' && /^https?:\/\
406
+ return relayTheme(jid, buildChatThemeSetting({ wallpaper: await uploadChatWallpaper(sock, await toBuffer(value, { maxBytes: 5 * 1024 * 1024 })) }));
407
+ }
408
+ if (typeof value === 'string') {
409
+ return relayTheme(jid, buildChatThemeSetting(value.includes('@') ? { scheme: value } : { color: value }));
410
+ }
411
+ return relayTheme(jid, buildChatThemeSetting(value));
412
+ },
413
+ setChatThemeColor: (jid, color) => api.setChatTheme(jid, { color }),
414
+ setChatBubbleScheme: (jid, scheme) => api.setChatTheme(jid, { scheme }),
415
+ setChatWallpaper: (jid, image) => api.setChatTheme(jid, image),
416
+ clearChatTheme: (jid) => api.setChatTheme(jid, null),
417
+ getChatThemeDiagnostics: () => {
418
+ const probe = buildChatThemeSetting({ color: 'red' });
419
+ let encoderOk = false, error = null;
420
+ try { encoderOk = !!verifyChatThemeEncoding(probe).decoded; } catch (e) { error = e.message; }
421
+ return { encoderOk, error, type: proto.Message.ProtocolMessage.Type[34] ?? null, wallpaperMediaMapped: true, note: 'Client acceptance of themes is not verified by this library' };
422
+ },
423
+ getMessageContext: async (msg) => buildMessageContext(msg, selfJid()),
424
+ getQuotedMessage, getMessageText, getMessageType, getMentions, isViewOnce, getMediaBuffer,
425
+ getBotJid: selfJid,
426
+ isFromBot: (msg) => !!msg.key?.fromMe || (!!msg.key?.participant && [selfJid(), selfLid()].some(j => j && areJidsSameUser(j, msg.key.participant))),
427
+ isGroupAdmin: async (groupJid, jid) => {
428
+ const meta = await sock.groupMetadata(groupJid);
429
+ const p = meta.participants.find(x => [x.id, x.jid, x.lid, x.phoneNumber].some(v => v && areJidsSameUser(v, jid)));
430
+ return p?.admin === 'admin' || p?.admin === 'superadmin';
431
+ },
432
+ formatMention,
433
+ reply: (msg, text, options = {}) => send(msg.key.remoteJid, { text }, { ...options, quoted: msg }),
434
+ sendText: (jid, text, options) => send(jid, { text }, options),
435
+ sendReact: (msg, emoji) => send(msg.key.remoteJid, { react: { text: emoji, key: msg.key } }),
436
+ sendImage: (jid, image, caption, options) => send(jid, { image, caption }, options),
437
+ sendVideo: (jid, video, caption, options) => send(jid, { video, caption }, options),
438
+ sendAudio: (jid, audio, options = {}) => send(jid, { audio, mimetype: options.mimetype || 'audio/mpeg', ptt: !!options.ptt }, options),
439
+ sendSticker: (jid, sticker, options) => send(jid, { sticker }, options),
440
+
441
+ sendPremiumSticker: (jid, sticker, options) => send(jid, { sticker, premium: 1 }, options),
442
+ hasMetaAI: async (groupJid) => (await sock.groupMetadata(groupJid)).participants.some(isMetaAiParticipant),
443
+ addMetaAI: (groupJid) => metaAiUpdate(groupJid, 'add'),
444
+ removeMetaAI: async (groupJid) => metaAiUpdate(groupJid, 'remove', (await sock.groupMetadata(groupJid)).participants.filter(isMetaAiParticipant).flatMap(participantIds))
445
+ };
446
+
447
+ const viewOnceText = (jid, text, options) => sendViewOnceTextWithSocket(sock, jid, text, options);
448
+ api.sendViewOnceText = viewOnceText;
449
+ api.sendViewOnceTextMessage = viewOnceText;
450
+ api.sendVotext = viewOnceText;
451
+
452
+ const uniq = (a) => [...new Set(a)];
453
+ api.addToFavorites = (jids, { current = [] } = {}) => sock.chatModify({ favorites: { jids: uniq([...current, ...[].concat(jids)]), add: true } }, '');
454
+ api.removeFromFavorites = (jids, { current = [] } = {}) => {
455
+ const drop = new Set([].concat(jids));
456
+ const rest = current.filter(j => !drop.has(j));
457
+ return sock.chatModify({ favorites: { jids: rest.length ? rest : [].concat(jids), add: rest.length > 0 } }, '');
458
+ };
459
+ Object.assign(api, createApiWrappers(sock));
460
+ for (const [k, v] of Object.entries(api)) {
461
+ if (!(k in sock)) {
462
+ sock[k] = v;
463
+ }
464
+ }
465
+
466
+ sock.sendMessage = async (jid, content, options = {}) => {
467
+ if (content && content.sticker && content.audioMessage && !content.audioMessage.directPath) {
468
+ const { buffer, mimetype, seconds } = content.audioMessage;
469
+ return sendSoundSticker(jid, { sticker: content.sticker, audio: buffer, mimetype, seconds }, options);
470
+ }
471
+ return originalSendMessage(jid, content, options);
472
+ };
473
+ return sock;
474
+ };
@@ -0,0 +1,3 @@
1
+ export function processContactAction(action: any, id: any, logger: any): any[];
2
+ export function emitSyncActionResults(ev: any, results: any): void;
3
+ //# sourceMappingURL=sync-action-utils.d.ts.map
@@ -0,0 +1,49 @@
1
+ import { proto } from '../../WAProto/index.js';
2
+ import { isLidUser, isPnUser } from '../WABinary/index.js';
3
+ /**
4
+ * Process contactAction and return events to emit.
5
+ * Pure function - no side effects.
6
+ */
7
+ export const processContactAction = (action, id, logger) => {
8
+ const results = [];
9
+ if (!id) {
10
+ logger?.warn({ hasFullName: !!action.fullName, hasLidJid: !!action.lidJid, hasPnJid: !!action.pnJid }, 'contactAction sync: missing id in index');
11
+ return results;
12
+ }
13
+ const lidJid = action.lidJid;
14
+ const idIsPn = isPnUser(id);
15
+ // PN is in index[1], not in contactAction.pnJid which is usually null
16
+ const phoneNumber = idIsPn ? id : action.pnJid || undefined;
17
+ // Always emit contacts.upsert
18
+ results.push({
19
+ event: 'contacts.upsert',
20
+ data: [
21
+ {
22
+ id,
23
+ name: action.fullName || action.firstName || action.username || undefined,
24
+ username: action.username || undefined,
25
+ lid: lidJid || undefined,
26
+ phoneNumber
27
+ }
28
+ ]
29
+ });
30
+ // Emit lid-mapping.update if we have valid LID-PN pair
31
+ if (lidJid && isLidUser(lidJid) && idIsPn) {
32
+ results.push({
33
+ event: 'lid-mapping.update',
34
+ data: { lid: lidJid, pn: id }
35
+ });
36
+ }
37
+ return results;
38
+ };
39
+ export const emitSyncActionResults = (ev, results) => {
40
+ for (const result of results) {
41
+ if (result.event === 'contacts.upsert') {
42
+ ev.emit('contacts.upsert', result.data);
43
+ }
44
+ else {
45
+ ev.emit('lid-mapping.update', result.data);
46
+ }
47
+ }
48
+ };
49
+ //# sourceMappingURL=sync-action-utils.js.map
@@ -0,0 +1,30 @@
1
+ /** Read the persisted tctoken JID index and return its entries (never contains the sentinel key itself). */
2
+ export function readTcTokenIndex(keys: any): Promise<any[]>;
3
+ /** Build a SignalDataSet fragment that writes the merged index (persisted ∪ added) under the sentinel key. */
4
+ export function buildMergedTcTokenIndexWrite(keys: any, addedJids: any): Promise<{
5
+ __index: {
6
+ token: any;
7
+ };
8
+ }>;
9
+ export function isTcTokenExpired(timestamp: any): boolean;
10
+ export function shouldSendNewTcToken(senderTimestamp: any): boolean;
11
+ /** Resolve JID to LID for tctoken storage (WA Web stores under LID) */
12
+ export function resolveTcTokenJid(jid: any, getLIDForPN: any): Promise<any>;
13
+ /** Resolve target JID for issuing privacy token based on AB prop 14303 */
14
+ export function resolveIssuanceJid(jid: any, issueToLid: any, getLIDForPN: any, getPNForLID: any): Promise<any>;
15
+ export function buildTcTokenFromJid({ authState, jid, baseContent, getLIDForPN }: {
16
+ authState: any;
17
+ jid: any;
18
+ baseContent?: never[] | undefined;
19
+ getLIDForPN: any;
20
+ }): Promise<any[] | undefined>;
21
+ export function storeTcTokensFromIqResult({ result, fallbackJid, keys, getLIDForPN, onNewJidStored }: {
22
+ result: any;
23
+ fallbackJid: any;
24
+ keys: any;
25
+ getLIDForPN: any;
26
+ onNewJidStored: any;
27
+ }): Promise<void>;
28
+ /** Sentinel key under `tctoken` store holding a JSON array of tracked storage JIDs for cross-session pruning. */
29
+ export const TC_TOKEN_INDEX_KEY: "__index";
30
+ //# sourceMappingURL=tc-token-utils.d.ts.map