ruby-baileys 0.0.0-stage → 1.5.17

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 (296) hide show
  1. package/EXPERIMENTAL.md +350 -0
  2. package/LICENSE +23 -0
  3. package/NOTICE.md +14 -0
  4. package/README.md +6265 -2
  5. package/WAProto/GenerateStatics.sh +3 -0
  6. package/WAProto/WAProto.proto +5479 -0
  7. package/WAProto/fix-imports.js +81 -0
  8. package/WAProto/index.d.ts +16877 -0
  9. package/WAProto/index.js +122159 -0
  10. package/assets/ruby_aspirant.jpg +0 -0
  11. package/assets/ruby_aspirant_4k.jpg +88 -0
  12. package/assets/ruby_aspirant_full.jpg +0 -0
  13. package/assets/ruby_aspirant_render.png +1 -0
  14. package/assets/ruby_aspirants_hd.jpg +0 -0
  15. package/assets/thumb.jpg +0 -0
  16. package/engine-requirements.js +14 -0
  17. package/index.cjs +29 -0
  18. package/index.d.ts +2 -0
  19. package/package.json +178 -4
  20. package/src/Defaults/index.d.ts +153 -0
  21. package/src/Defaults/index.js +165 -0
  22. package/src/MessageBuilder/bot-signature.d.ts +22 -0
  23. package/src/MessageBuilder/bot-signature.js +123 -0
  24. package/src/MessageBuilder/extras.d.ts +396 -0
  25. package/src/MessageBuilder/extras.js +1229 -0
  26. package/src/MessageBuilder/index.d.ts +210 -0
  27. package/src/MessageBuilder/index.js +3521 -0
  28. package/src/MessageBuilder/metaai.d.ts +438 -0
  29. package/src/MessageBuilder/metaai.js +891 -0
  30. package/src/Signal/Group/ciphertext-message.d.ts +10 -0
  31. package/src/Signal/Group/ciphertext-message.js +12 -0
  32. package/src/Signal/Group/group-session-builder.d.ts +8 -0
  33. package/src/Signal/Group/group-session-builder.js +28 -0
  34. package/src/Signal/Group/group_cipher.d.ts +11 -0
  35. package/src/Signal/Group/group_cipher.js +79 -0
  36. package/src/Signal/Group/index.d.ts +12 -0
  37. package/src/Signal/Group/index.js +12 -0
  38. package/src/Signal/Group/keyhelper.d.ts +7 -0
  39. package/src/Signal/Group/keyhelper.js +18 -0
  40. package/src/Signal/Group/sender-chain-key.d.ts +14 -0
  41. package/src/Signal/Group/sender-chain-key.js +26 -0
  42. package/src/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  43. package/src/Signal/Group/sender-key-distribution-message.js +63 -0
  44. package/src/Signal/Group/sender-key-message.d.ts +19 -0
  45. package/src/Signal/Group/sender-key-message.js +66 -0
  46. package/src/Signal/Group/sender-key-name.d.ts +12 -0
  47. package/src/Signal/Group/sender-key-name.js +48 -0
  48. package/src/Signal/Group/sender-key-record.d.ts +13 -0
  49. package/src/Signal/Group/sender-key-record.js +41 -0
  50. package/src/Signal/Group/sender-key-state.d.ts +17 -0
  51. package/src/Signal/Group/sender-key-state.js +84 -0
  52. package/src/Signal/Group/sender-message-key.d.ts +12 -0
  53. package/src/Signal/Group/sender-message-key.js +26 -0
  54. package/src/Signal/libsignal.d.ts +55 -0
  55. package/src/Signal/libsignal.js +429 -0
  56. package/src/Signal/lid-mapping.d.ts +21 -0
  57. package/src/Signal/lid-mapping.js +275 -0
  58. package/src/Socket/Client/index.d.ts +3 -0
  59. package/src/Socket/Client/index.js +3 -0
  60. package/src/Socket/Client/types.d.ts +6 -0
  61. package/src/Socket/Client/types.js +10 -0
  62. package/src/Socket/Client/websocket.d.ts +13 -0
  63. package/src/Socket/Client/websocket.js +54 -0
  64. package/src/Socket/business.d.ts +432 -0
  65. package/src/Socket/business.js +380 -0
  66. package/src/Socket/chats.d.ts +248 -0
  67. package/src/Socket/chats.js +1485 -0
  68. package/src/Socket/communities.d.ts +599 -0
  69. package/src/Socket/communities.js +422 -0
  70. package/src/Socket/groups.d.ts +299 -0
  71. package/src/Socket/groups.js +340 -0
  72. package/src/Socket/index.d.ts +582 -0
  73. package/src/Socket/index.js +48 -0
  74. package/src/Socket/messages-recv.d.ts +371 -0
  75. package/src/Socket/messages-recv.js +1803 -0
  76. package/src/Socket/messages-send.d.ts +391 -0
  77. package/src/Socket/messages-send.js +1575 -0
  78. package/src/Socket/mex.d.ts +2 -0
  79. package/src/Socket/mex.js +45 -0
  80. package/src/Socket/newsletter.d.ts +469 -0
  81. package/src/Socket/newsletter.js +643 -0
  82. package/src/Socket/socket.d.ts +78 -0
  83. package/src/Socket/socket.js +1088 -0
  84. package/src/Store/index.d.ts +4 -0
  85. package/src/Store/index.js +4 -0
  86. package/src/Store/make-in-memory-store.d.ts +63 -0
  87. package/src/Store/make-in-memory-store.js +398 -0
  88. package/src/Store/make-ordered-dictionary.d.ts +13 -0
  89. package/src/Store/make-ordered-dictionary.js +79 -0
  90. package/src/Store/object-repository.d.ts +11 -0
  91. package/src/Store/object-repository.js +24 -0
  92. package/src/Types/Auth.d.ts +2 -0
  93. package/src/Types/Auth.js +2 -0
  94. package/src/Types/Bussines.d.ts +2 -0
  95. package/src/Types/Bussines.js +2 -0
  96. package/src/Types/Call.d.ts +2 -0
  97. package/src/Types/Call.js +2 -0
  98. package/src/Types/Chat.d.ts +3 -0
  99. package/src/Types/Chat.js +25 -0
  100. package/src/Types/Contact.d.ts +2 -0
  101. package/src/Types/Contact.js +2 -0
  102. package/src/Types/Events.d.ts +2 -0
  103. package/src/Types/Events.js +1 -0
  104. package/src/Types/GroupMetadata.d.ts +6 -0
  105. package/src/Types/GroupMetadata.js +7 -0
  106. package/src/Types/Label.d.ts +3 -0
  107. package/src/Types/Label.js +25 -0
  108. package/src/Types/LabelAssociation.d.ts +3 -0
  109. package/src/Types/LabelAssociation.js +7 -0
  110. package/src/Types/Message.d.ts +14 -0
  111. package/src/Types/Message.js +24 -0
  112. package/src/Types/Mex.d.ts +3 -0
  113. package/src/Types/Mex.js +96 -0
  114. package/src/Types/Product.d.ts +2 -0
  115. package/src/Types/Product.js +2 -0
  116. package/src/Types/Signal.d.ts +2 -0
  117. package/src/Types/Signal.js +1 -0
  118. package/src/Types/Socket.d.ts +2 -0
  119. package/src/Types/Socket.js +1 -0
  120. package/src/Types/State.d.ts +6 -0
  121. package/src/Types/State.js +55 -0
  122. package/src/Types/USync.d.ts +2 -0
  123. package/src/Types/USync.js +1 -0
  124. package/src/Types/index.d.ts +14 -0
  125. package/src/Types/index.js +26 -0
  126. package/src/Utils/auth-store.d.ts +30 -0
  127. package/src/Utils/auth-store.js +77 -0
  128. package/src/Utils/auth-utils.d.ts +59 -0
  129. package/src/Utils/auth-utils.js +274 -0
  130. package/src/Utils/browser-utils.d.ts +10 -0
  131. package/src/Utils/browser-utils.js +29 -0
  132. package/src/Utils/business.d.ts +50 -0
  133. package/src/Utils/business.js +227 -0
  134. package/src/Utils/chat-utils.d.ts +409 -0
  135. package/src/Utils/chat-utils.js +847 -0
  136. package/src/Utils/companion-reg-client-utils.d.ts +5 -0
  137. package/src/Utils/companion-reg-client-utils.js +40 -0
  138. package/src/Utils/crypto.d.ts +40 -0
  139. package/src/Utils/crypto.js +111 -0
  140. package/src/Utils/decode-wa-message.d.ts +100 -0
  141. package/src/Utils/decode-wa-message.js +374 -0
  142. package/src/Utils/event-buffer.d.ts +23 -0
  143. package/src/Utils/event-buffer.js +625 -0
  144. package/src/Utils/generics.d.ts +64 -0
  145. package/src/Utils/generics.js +376 -0
  146. package/src/Utils/group-metadata-cache.d.ts +5 -0
  147. package/src/Utils/group-metadata-cache.js +26 -0
  148. package/src/Utils/history.d.ts +76 -0
  149. package/src/Utils/history.js +132 -0
  150. package/src/Utils/html-app.d.ts +19 -0
  151. package/src/Utils/html-app.js +97 -0
  152. package/src/Utils/html-multiplayer.d.ts +10 -0
  153. package/src/Utils/html-multiplayer.js +95 -0
  154. package/src/Utils/identity-change-handler.d.ts +14 -0
  155. package/src/Utils/identity-change-handler.js +49 -0
  156. package/src/Utils/index.d.ts +45 -0
  157. package/src/Utils/index.js +45 -0
  158. package/src/Utils/link-preview-metadata.d.ts +47 -0
  159. package/src/Utils/link-preview-metadata.js +89 -0
  160. package/src/Utils/link-preview.d.ts +13 -0
  161. package/src/Utils/link-preview.js +80 -0
  162. package/src/Utils/logger.d.ts +3 -0
  163. package/src/Utils/logger.js +3 -0
  164. package/src/Utils/lt-hash.d.ts +7 -0
  165. package/src/Utils/lt-hash.js +4 -0
  166. package/src/Utils/make-mutex.d.ts +7 -0
  167. package/src/Utils/make-mutex.js +33 -0
  168. package/src/Utils/message-retry-manager.d.ts +80 -0
  169. package/src/Utils/message-retry-manager.js +256 -0
  170. package/src/Utils/messages-media.d.ts +137 -0
  171. package/src/Utils/messages-media.js +815 -0
  172. package/src/Utils/messages.d.ts +63 -0
  173. package/src/Utils/messages.js +2149 -0
  174. package/src/Utils/modern-messages.d.ts +150 -0
  175. package/src/Utils/modern-messages.js +496 -0
  176. package/src/Utils/native-flow.d.ts +11 -0
  177. package/src/Utils/native-flow.js +116 -0
  178. package/src/Utils/newsletter-status.d.ts +158 -0
  179. package/src/Utils/newsletter-status.js +651 -0
  180. package/src/Utils/noise-handler.d.ts +21 -0
  181. package/src/Utils/noise-handler.js +201 -0
  182. package/src/Utils/offline-node-processor.d.ts +10 -0
  183. package/src/Utils/offline-node-processor.js +34 -0
  184. package/src/Utils/optional-media.d.ts +3 -0
  185. package/src/Utils/optional-media.js +46 -0
  186. package/src/Utils/payment-messages.d.ts +66 -0
  187. package/src/Utils/payment-messages.js +161 -0
  188. package/src/Utils/pre-key-manager.d.ts +26 -0
  189. package/src/Utils/pre-key-manager.js +96 -0
  190. package/src/Utils/process-message.d.ts +61 -0
  191. package/src/Utils/process-message.js +689 -0
  192. package/src/Utils/reporting-utils.d.ts +13 -0
  193. package/src/Utils/reporting-utils.js +257 -0
  194. package/src/Utils/scheduled-message.d.ts +51 -0
  195. package/src/Utils/scheduled-message.js +113 -0
  196. package/src/Utils/sender-key-memory.d.ts +20 -0
  197. package/src/Utils/sender-key-memory.js +52 -0
  198. package/src/Utils/signal.d.ts +83 -0
  199. package/src/Utils/signal.js +194 -0
  200. package/src/Utils/stanza-ack.d.ts +17 -0
  201. package/src/Utils/stanza-ack.js +31 -0
  202. package/src/Utils/status-stickers.d.ts +127 -0
  203. package/src/Utils/status-stickers.js +261 -0
  204. package/src/Utils/sync-action-utils.d.ts +3 -0
  205. package/src/Utils/sync-action-utils.js +45 -0
  206. package/src/Utils/tc-token-utils.d.ts +30 -0
  207. package/src/Utils/tc-token-utils.js +156 -0
  208. package/src/Utils/ttl-cache.d.ts +29 -0
  209. package/src/Utils/ttl-cache.js +121 -0
  210. package/src/Utils/use-mongo-auth-state.d.ts +22 -0
  211. package/src/Utils/use-mongo-auth-state.js +68 -0
  212. package/src/Utils/use-multi-file-auth-state.d.ts +12 -0
  213. package/src/Utils/use-multi-file-auth-state.js +107 -0
  214. package/src/Utils/use-mysql-auth-state.d.ts +20 -0
  215. package/src/Utils/use-mysql-auth-state.js +80 -0
  216. package/src/Utils/use-postgres-auth-state.d.ts +20 -0
  217. package/src/Utils/use-postgres-auth-state.js +80 -0
  218. package/src/Utils/use-redis-auth-state.d.ts +20 -0
  219. package/src/Utils/use-redis-auth-state.js +90 -0
  220. package/src/Utils/use-single-file-auth-state.d.ts +11 -0
  221. package/src/Utils/use-single-file-auth-state.js +109 -0
  222. package/src/Utils/use-sqlite-auth-state.d.ts +13 -0
  223. package/src/Utils/use-sqlite-auth-state.js +121 -0
  224. package/src/Utils/useNekoDBAuth.d.ts +19 -0
  225. package/src/Utils/useNekoDBAuth.js +111 -0
  226. package/src/Utils/username.d.ts +12 -0
  227. package/src/Utils/username.js +59 -0
  228. package/src/Utils/validate-connection.d.ts +44 -0
  229. package/src/Utils/validate-connection.js +208 -0
  230. package/src/Utils/voice-recognition.d.ts +53 -0
  231. package/src/Utils/voice-recognition.js +219 -0
  232. package/src/Voip/audio-feeder.d.ts +25 -0
  233. package/src/Voip/audio-feeder.js +269 -0
  234. package/src/Voip/index.d.ts +89 -0
  235. package/src/Voip/index.js +937 -0
  236. package/src/Voip/relay-transport.d.ts +6 -0
  237. package/src/Voip/relay-transport.js +825 -0
  238. package/src/Voip/signaling.d.ts +12 -0
  239. package/src/Voip/signaling.js +1100 -0
  240. package/src/Voip/types.d.ts +3 -0
  241. package/src/Voip/types.js +13 -0
  242. package/src/Voip/video-feeder.d.ts +25 -0
  243. package/src/Voip/video-feeder.js +269 -0
  244. package/src/Voip/wasm-engine.d.ts +27 -0
  245. package/src/Voip/wasm-engine.js +1308 -0
  246. package/src/Voip/worker-bootstrap.js +1024 -0
  247. package/src/WABinary/constants.d.ts +23 -0
  248. package/src/WABinary/constants.js +1301 -0
  249. package/src/WABinary/decode.d.ts +10 -0
  250. package/src/WABinary/decode.js +262 -0
  251. package/src/WABinary/encode.d.ts +3 -0
  252. package/src/WABinary/encode.js +220 -0
  253. package/src/WABinary/generic-utils.d.ts +77 -0
  254. package/src/WABinary/generic-utils.js +214 -0
  255. package/src/WABinary/index.d.ts +6 -0
  256. package/src/WABinary/index.js +6 -0
  257. package/src/WABinary/jid-utils.d.ts +31 -0
  258. package/src/WABinary/jid-utils.js +98 -0
  259. package/src/WABinary/types.d.ts +2 -0
  260. package/src/WABinary/types.js +1 -0
  261. package/src/WAM/BinaryInfo.d.ts +8 -0
  262. package/src/WAM/BinaryInfo.js +10 -0
  263. package/src/WAM/constants.d.ts +34927 -0
  264. package/src/WAM/constants.js +22853 -0
  265. package/src/WAM/encode.d.ts +2 -0
  266. package/src/WAM/encode.js +149 -0
  267. package/src/WAM/index.d.ts +4 -0
  268. package/src/WAM/index.js +4 -0
  269. package/src/WAUSync/Protocols/USyncContactProtocol.d.ts +37 -0
  270. package/src/WAUSync/Protocols/USyncContactProtocol.js +51 -0
  271. package/src/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  272. package/src/WAUSync/Protocols/USyncDeviceProtocol.js +52 -0
  273. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  274. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  275. package/src/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  276. package/src/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  277. package/src/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  278. package/src/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  279. package/src/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +39 -0
  280. package/src/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -0
  281. package/src/WAUSync/Protocols/UsyncLIDProtocol.d.ts +15 -0
  282. package/src/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  283. package/src/WAUSync/Protocols/index.d.ts +6 -0
  284. package/src/WAUSync/Protocols/index.js +6 -0
  285. package/src/WAUSync/USyncQuery.d.ts +21 -0
  286. package/src/WAUSync/USyncQuery.js +94 -0
  287. package/src/WAUSync/USyncUser.d.ts +17 -0
  288. package/src/WAUSync/USyncUser.js +31 -0
  289. package/src/WAUSync/index.d.ts +4 -0
  290. package/src/WAUSync/index.js +4 -0
  291. package/src/assets/wasm/README.md +76 -0
  292. package/src/assets/wasm/loader.js +5 -0
  293. package/src/assets/wasm/whatsapp.wasm +0 -0
  294. package/src/assets/wasm/worker-modules.js +273 -0
  295. package/src/index.d.ts +49 -0
  296. package/src/index.js +54 -0
@@ -0,0 +1,64 @@
1
+ /* Elaina Baileys maintained distribution. Upstream notices and license are preserved in LICENSE and NOTICE.md. */
2
+ export function promiseTimeout(ms: any, promise: any): Promise<any>;
3
+ export function bindWaitForEvent(ev: any, event: any): (check: any, timeoutMs: any) => Promise<void>;
4
+ export function trimUndefined(obj: any): any;
5
+ export function bytesToCrockford(buffer: any): string;
6
+ export function encodeNewsletterMessage(message: any): any;
7
+ export namespace BufferJSON {
8
+ function replacer(k: any, value: any): any;
9
+ function reviver(_: any, value: any): any;
10
+ }
11
+ export function getKeyAuthor(key: any, meId?: string): any;
12
+ export function isStringNullOrEmpty(value: any): boolean;
13
+ export function writeRandomPadMax16(msg: any): any;
14
+ export function unpadRandomMax16(e: any): Uint8Array<any>;
15
+ export function generateParticipantHashV2(participants: any): string;
16
+ export function encodeWAMessage(message: any): any;
17
+ export function generateRegistrationId(): number;
18
+ export function encodeBigEndian(e: any, t?: number): Uint8Array<ArrayBuffer>;
19
+ export function toNumber(t: any): any;
20
+ export function unixTimestampSeconds(date?: Date): number;
21
+ export function debouncedTimeout(intervalMs: number | undefined, task: any): {
22
+ start: (newIntervalMs: any, newTask: any) => void;
23
+ cancel: () => void;
24
+ setTask: (newTask: any) => any;
25
+ setInterval: (newInterval: any) => any;
26
+ };
27
+ export function delay(ms: any): Promise<any>;
28
+ export function delayCancellable(ms: any): {
29
+ delay: Promise<any>;
30
+ cancel: () => void;
31
+ };
32
+ export function generateMessageIDV2(userId: any): string;
33
+ export function generateMessageID(): string;
34
+ export function bindWaitForConnectionUpdate(ev: any): (check: any, timeoutMs: any) => Promise<void>;
35
+ export function fetchLatestBaileysVersion(options?: {}): Promise<{
36
+ version: number[];
37
+ isLatest: boolean;
38
+ error?: undefined;
39
+ } | {
40
+ version: number[];
41
+ isLatest: boolean;
42
+ error: unknown;
43
+ }>;
44
+ export function fetchLatestWaWebVersion(options?: {}): Promise<{
45
+ version: number[];
46
+ isLatest: boolean;
47
+ error?: undefined;
48
+ } | {
49
+ version: number[];
50
+ isLatest: boolean;
51
+ error: unknown;
52
+ }>;
53
+ export function generateMdTagPrefix(): string;
54
+ export function getStatusFromReceiptType(type: any): any;
55
+ export function getErrorCodeFromStreamError(node: any): {
56
+ reason: any;
57
+ statusCode: number;
58
+ };
59
+ export function getCallStatusFromNode({ tag, attrs }: {
60
+ tag: any;
61
+ attrs: any;
62
+ }): string;
63
+ export function getCodeFromWSError(error: any): number;
64
+ export function isWABusinessPlatform(platform: any): boolean;
@@ -0,0 +1,376 @@
1
+ /* Elaina Baileys maintained distribution. Upstream notices and license are preserved in LICENSE and NOTICE.md. */
2
+ import { Boom } from '@hapi/boom';
3
+ import { createHash, randomBytes, randomFillSync } from 'crypto';
4
+ import { proto } from '../../WAProto/index.js';
5
+ const baileysVersion = [2, 3000, 1049236237];
6
+ import { DisconnectReason } from '../Types/index.js';
7
+ import { getAllBinaryNodeChildren } from '../WABinary/index.js';
8
+ import { sha256 } from './crypto.js';
9
+ export const BufferJSON = {
10
+
11
+ replacer: (k, value) => {
12
+ if (Buffer.isBuffer(value) || value instanceof Uint8Array || value?.type === 'Buffer') {
13
+ return { type: 'Buffer', data: Buffer.from(value?.data || value).toString('base64') };
14
+ }
15
+ return value;
16
+ },
17
+
18
+ reviver: (_, value) => {
19
+ if (typeof value === 'object' && value !== null && value.type === 'Buffer' && typeof value.data === 'string') {
20
+ return Buffer.from(value.data, 'base64');
21
+ }
22
+ if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
23
+ const keys = Object.keys(value);
24
+ if (keys.length > 0 && keys.every(k => !isNaN(parseInt(k, 10)))) {
25
+ const values = Object.values(value);
26
+ if (values.every(v => typeof v === 'number')) {
27
+ return Buffer.from(values);
28
+ }
29
+ }
30
+ }
31
+ return value;
32
+ }
33
+ };
34
+ export const getKeyAuthor = (key, meId = 'me') => (key?.fromMe ? meId : key?.participantAlt || key?.remoteJidAlt || key?.participant || key?.remoteJid) || '';
35
+ export const isStringNullOrEmpty = (value) =>
36
+
37
+ value == null || value === '';
38
+ export const writeRandomPadMax16 = (msg) => {
39
+ const pad = randomBytes(1);
40
+ const padLength = (pad[0] & 0x0f) + 1;
41
+ return Buffer.concat([msg, Buffer.alloc(padLength, padLength)]);
42
+ };
43
+ export const unpadRandomMax16 = (e) => {
44
+ const t = new Uint8Array(e);
45
+ if (0 === t.length) {
46
+ throw new Error('unpadPkcs7 given empty bytes');
47
+ }
48
+ var r = t[t.length - 1];
49
+ if (r > t.length) {
50
+ throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`);
51
+ }
52
+ return new Uint8Array(t.buffer, t.byteOffset, t.length - r);
53
+ };
54
+
55
+ export const generateParticipantHashV2 = (participants) => {
56
+ participants.sort();
57
+ const sha256Hash = sha256(Buffer.from(participants.join(''))).toString('base64');
58
+ return '2:' + sha256Hash.slice(0, 6);
59
+ };
60
+ export const encodeWAMessage = (message) => writeRandomPadMax16(proto.Message.encode(message).finish());
61
+ export const generateRegistrationId = () => {
62
+ return Uint16Array.from(randomBytes(2))[0] & 16383;
63
+ };
64
+ export const encodeBigEndian = (e, t = 4) => {
65
+ let r = e;
66
+ const a = new Uint8Array(t);
67
+ for (let i = t - 1; i >= 0; i--) {
68
+ a[i] = 255 & r;
69
+ r >>>= 8;
70
+ }
71
+ return a;
72
+ };
73
+ export const toNumber = (t) => typeof t === 'object' && t ? ('toNumber' in t ? t.toNumber() : t.low) : t || 0;
74
+
75
+ export const unixTimestampSeconds = (date = new Date()) => date.getTime() / 1000 | 0;
76
+ export const debouncedTimeout = (intervalMs = 1000, task) => {
77
+ let timeout;
78
+ return {
79
+ start: (newIntervalMs, newTask) => {
80
+ task = newTask || task;
81
+ intervalMs = newIntervalMs || intervalMs;
82
+ timeout && clearTimeout(timeout);
83
+ timeout = setTimeout(() => task?.(), intervalMs);
84
+ },
85
+ cancel: () => {
86
+ timeout && clearTimeout(timeout);
87
+ timeout = undefined;
88
+ },
89
+ setTask: (newTask) => (task = newTask),
90
+ setInterval: (newInterval) => (intervalMs = newInterval)
91
+ };
92
+ };
93
+ export const delay = (ms) => delayCancellable(ms).delay;
94
+ export const delayCancellable = (ms) => {
95
+ const stack = new Error().stack;
96
+ let timeout;
97
+ let reject;
98
+ const delay = new Promise((resolve, _reject) => {
99
+ timeout = setTimeout(resolve, ms);
100
+ reject = _reject;
101
+ });
102
+ const cancel = () => {
103
+ clearTimeout(timeout);
104
+ reject(new Boom('Cancelled', {
105
+ statusCode: 500,
106
+ data: {
107
+ stack
108
+ }
109
+ }));
110
+ };
111
+ return { delay, cancel };
112
+ };
113
+ export async function promiseTimeout(ms, promise) {
114
+ if (!ms) {
115
+ return new Promise(promise);
116
+ }
117
+ const stack = new Error().stack;
118
+
119
+ const { delay, cancel } = delayCancellable(ms);
120
+ const p = new Promise((resolve, reject) => {
121
+ delay
122
+ .then(() => reject(new Boom('Timed Out', {
123
+ statusCode: DisconnectReason.timedOut,
124
+ data: {
125
+ stack
126
+ }
127
+ })))
128
+ .catch(err => reject(err));
129
+ promise(resolve, reject);
130
+ }).finally(cancel);
131
+ return p;
132
+ }
133
+
134
+ export const generateMessageIDV2 = (userId) => {
135
+ const data = Buffer.allocUnsafe(44);
136
+ data.writeBigUInt64BE(BigInt(Date.now() / 1000 | 0), 0);
137
+ if (userId) {
138
+ const userStr = userId.split('@')[0].split(':')[0];
139
+ if (userStr) {
140
+ const len = data.write(userStr, 8);
141
+ data.write('@c.us', 8 + len);
142
+ }
143
+ }
144
+ randomFillSync(data, 28, 16);
145
+ const hash = createHash('sha256').update(data).digest();
146
+ return '3EB0' + hash.toString('hex', 0, 9).toUpperCase();
147
+ };
148
+
149
+ export const generateMessageID = () => '3EB0' + randomBytes(8).toString('hex').toUpperCase();
150
+ export function bindWaitForEvent(ev, event) {
151
+ return async (check, timeoutMs) => {
152
+ let listener;
153
+ let closeListener;
154
+ await promiseTimeout(timeoutMs, (resolve, reject) => {
155
+ closeListener = ({ connection, lastDisconnect }) => {
156
+ if (connection === 'close') {
157
+ reject(lastDisconnect?.error || new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed }));
158
+ }
159
+ };
160
+ ev.on('connection.update', closeListener);
161
+ listener = async (update) => {
162
+ if (await check(update)) {
163
+ resolve();
164
+ }
165
+ };
166
+ ev.on(event, listener);
167
+ }).finally(() => {
168
+ ev.off(event, listener);
169
+ ev.off('connection.update', closeListener);
170
+ });
171
+ };
172
+ }
173
+ export const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
174
+
175
+ export const fetchLatestBaileysVersion = async (options = {}) => {
176
+ const URL = 'https://raw.githubusercontent.com/rexxhayanasi/elaina-baileys/main/src/Defaults/index.js';
177
+ try {
178
+ const response = await fetch(URL, {
179
+ dispatcher: options.dispatcher,
180
+ method: 'GET',
181
+ headers: options.headers
182
+ });
183
+ if (!response.ok) {
184
+ throw new Boom(`Failed to fetch latest Baileys version: ${response.statusText}`, { statusCode: response.status });
185
+ }
186
+ const text = await response.text();
187
+
188
+ const lines = text.split('\n');
189
+ const versionLine = lines[4];
190
+ const versionMatch = versionLine.match(/const version = \[(\d+),\s*(\d+),\s*(\d+)\]/);
191
+ if (versionMatch) {
192
+ const version = [parseInt(versionMatch[1]), parseInt(versionMatch[2]), parseInt(versionMatch[3])];
193
+ return {
194
+ version,
195
+ isLatest: true
196
+ };
197
+ }
198
+ else {
199
+ throw new Error('Could not parse version from Defaults/index.ts');
200
+ }
201
+ }
202
+ catch (error) {
203
+ return {
204
+ version: baileysVersion,
205
+ isLatest: false,
206
+ error
207
+ };
208
+ }
209
+ };
210
+
211
+ export const fetchLatestWaWebVersion = async (options = {}) => {
212
+ try {
213
+
214
+ const defaultHeaders = {
215
+ 'sec-fetch-site': 'none',
216
+ 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
217
+ };
218
+ const headers = { ...defaultHeaders, ...options.headers };
219
+ const response = await fetch('https://web.whatsapp.com/sw.js', {
220
+ ...options,
221
+ method: 'GET',
222
+ headers
223
+ });
224
+ if (!response.ok) {
225
+ throw new Boom(`Failed to fetch sw.js: ${response.statusText}`, { statusCode: response.status });
226
+ }
227
+ const data = await response.text();
228
+ const regex = /\\?"client_revision\\?":\s*(\d+)/;
229
+ const match = data.match(regex);
230
+ if (!match?.[1]) {
231
+ return {
232
+ version: baileysVersion,
233
+ isLatest: false,
234
+ error: {
235
+ message: 'Could not find client revision in the fetched content'
236
+ }
237
+ };
238
+ }
239
+ const clientRevision = match[1];
240
+ return {
241
+ version: [2, 3000, +clientRevision],
242
+ isLatest: true
243
+ };
244
+ }
245
+ catch (error) {
246
+ return {
247
+ version: baileysVersion,
248
+ isLatest: false,
249
+ error
250
+ };
251
+ }
252
+ };
253
+
254
+ export const generateMdTagPrefix = () => {
255
+ const bytes = randomBytes(4);
256
+ return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
257
+ };
258
+ const STATUS_MAP = {
259
+ sender: proto.WebMessageInfo.Status.SERVER_ACK,
260
+ played: proto.WebMessageInfo.Status.PLAYED,
261
+ read: proto.WebMessageInfo.Status.READ,
262
+ 'read-self': proto.WebMessageInfo.Status.READ
263
+ };
264
+
265
+ export const getStatusFromReceiptType = (type) => {
266
+ const status = STATUS_MAP[type];
267
+ if (typeof type === 'undefined') {
268
+ return proto.WebMessageInfo.Status.DELIVERY_ACK;
269
+ }
270
+ return status;
271
+ };
272
+ const CODE_MAP = {
273
+ conflict: DisconnectReason.connectionReplaced
274
+ };
275
+
276
+ export const getErrorCodeFromStreamError = (node) => {
277
+ const [reasonNode] = getAllBinaryNodeChildren(node);
278
+ let reason = reasonNode?.tag || 'unknown';
279
+ const statusCode = +(node.attrs.code || CODE_MAP[reason] || DisconnectReason.badSession);
280
+ if (statusCode === DisconnectReason.restartRequired) {
281
+ reason = 'restart required';
282
+ }
283
+ return {
284
+ reason,
285
+ statusCode
286
+ };
287
+ };
288
+ export const getCallStatusFromNode = ({ tag, attrs }) => {
289
+ let status;
290
+ switch (tag) {
291
+ case 'offer':
292
+ case 'offer_notice':
293
+ status = 'offer';
294
+ break;
295
+ case 'terminate':
296
+ if (attrs.reason === 'timeout') {
297
+ status = 'timeout';
298
+ }
299
+ else {
300
+
301
+ status = 'terminate';
302
+ }
303
+ break;
304
+ case 'preaccept':
305
+ status = 'preaccept';
306
+ break;
307
+ case 'transport':
308
+ status = 'transport';
309
+ break;
310
+ case 'relaylatency':
311
+ status = 'relaylatency';
312
+ break;
313
+ case 'reject':
314
+ status = 'reject';
315
+ break;
316
+ case 'accept':
317
+ status = 'accept';
318
+ break;
319
+ default:
320
+ status = 'ringing';
321
+ break;
322
+ }
323
+ return status;
324
+ };
325
+ const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: ';
326
+ export const getCodeFromWSError = (error) => {
327
+ let statusCode = 500;
328
+ if (error?.message?.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
329
+ const code = +error?.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length);
330
+ if (!Number.isNaN(code) && code >= 400) {
331
+ statusCode = code;
332
+ }
333
+ }
334
+ else if (
335
+
336
+ error?.code?.startsWith('E') ||
337
+ error?.message?.includes('timed out')) {
338
+
339
+ statusCode = 408;
340
+ }
341
+ return statusCode;
342
+ };
343
+
344
+ export const isWABusinessPlatform = (platform) => {
345
+ return platform === 'smbi' || platform === 'smba';
346
+ };
347
+
348
+ export function trimUndefined(obj) {
349
+ for (const key in obj) {
350
+ if (typeof obj[key] === 'undefined') {
351
+ delete obj[key];
352
+ }
353
+ }
354
+ return obj;
355
+ }
356
+ const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ';
357
+ export function bytesToCrockford(buffer) {
358
+ let value = 0;
359
+ let bitCount = 0;
360
+ const crockford = [];
361
+ for (const element of buffer) {
362
+ value = (value << 8) | (element & 0xff);
363
+ bitCount += 8;
364
+ while (bitCount >= 5) {
365
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31));
366
+ bitCount -= 5;
367
+ }
368
+ }
369
+ if (bitCount > 0) {
370
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31));
371
+ }
372
+ return crockford.join('');
373
+ }
374
+ export function encodeNewsletterMessage(message) {
375
+ return proto.Message.encode(message).finish();
376
+ }
@@ -0,0 +1,5 @@
1
+ /* Elaina Baileys maintained distribution. Upstream notices and license are preserved in LICENSE and NOTICE.md. */
2
+
3
+ export declare const GROUP_ADDRESSING_MODES: readonly string[]
4
+ export declare function isUsableGroupMetadata(metadata: any): boolean
5
+ export declare function describeUnusableGroupMetadata(metadata: any): string
@@ -0,0 +1,26 @@
1
+ /* Elaina Baileys maintained distribution. Upstream notices and license are preserved in LICENSE and NOTICE.md. */
2
+
3
+ export const GROUP_ADDRESSING_MODES = Object.freeze(['pn', 'lid'])
4
+
5
+ export const isUsableGroupMetadata = metadata => {
6
+ if (!metadata || typeof metadata !== 'object') {
7
+ return false
8
+ }
9
+ if (!Array.isArray(metadata.participants)) {
10
+ return false
11
+ }
12
+ return GROUP_ADDRESSING_MODES.includes(metadata.addressingMode)
13
+ }
14
+
15
+ export const describeUnusableGroupMetadata = metadata => {
16
+ if (!metadata || typeof metadata !== 'object') {
17
+ return 'nothing cached'
18
+ }
19
+ if (!Array.isArray(metadata.participants)) {
20
+ return 'no participants'
21
+ }
22
+ if (metadata.addressingMode === undefined || metadata.addressingMode === null) {
23
+ return 'no addressingMode'
24
+ }
25
+ return `addressingMode ${JSON.stringify(metadata.addressingMode)} is not pn or lid`
26
+ }
@@ -0,0 +1,76 @@
1
+ /* Elaina Baileys maintained distribution. Upstream notices and license are preserved in LICENSE and NOTICE.md. */
2
+ export function downloadHistory(msg: any, options: any): Promise<proto.HistorySync>;
3
+ export function processHistoryMessage(item: any, logger: any): {
4
+ chats: any[];
5
+ contacts: ({
6
+ id: any;
7
+ name: any;
8
+ username: any;
9
+ lid: any;
10
+ phoneNumber: any;
11
+ verifiedName?: undefined;
12
+ notify?: undefined;
13
+ } | {
14
+ id: any;
15
+ verifiedName: any;
16
+ name?: undefined;
17
+ username?: undefined;
18
+ lid?: undefined;
19
+ phoneNumber?: undefined;
20
+ notify?: undefined;
21
+ } | {
22
+ id: any;
23
+ notify: any;
24
+ name?: undefined;
25
+ username?: undefined;
26
+ lid?: undefined;
27
+ phoneNumber?: undefined;
28
+ verifiedName?: undefined;
29
+ })[];
30
+ messages: any[];
31
+ lidPnMappings: {
32
+ lid: any;
33
+ pn: any;
34
+ }[];
35
+ pastParticipants: any;
36
+ syncType: any;
37
+ progress: any;
38
+ };
39
+ export function downloadAndProcessHistorySyncNotification(msg: any, options: any, logger: any): Promise<{
40
+ chats: any[];
41
+ contacts: ({
42
+ id: any;
43
+ name: any;
44
+ username: any;
45
+ lid: any;
46
+ phoneNumber: any;
47
+ verifiedName?: undefined;
48
+ notify?: undefined;
49
+ } | {
50
+ id: any;
51
+ verifiedName: any;
52
+ name?: undefined;
53
+ username?: undefined;
54
+ lid?: undefined;
55
+ phoneNumber?: undefined;
56
+ notify?: undefined;
57
+ } | {
58
+ id: any;
59
+ notify: any;
60
+ name?: undefined;
61
+ username?: undefined;
62
+ lid?: undefined;
63
+ phoneNumber?: undefined;
64
+ verifiedName?: undefined;
65
+ })[];
66
+ messages: any[];
67
+ lidPnMappings: {
68
+ lid: any;
69
+ pn: any;
70
+ }[];
71
+ pastParticipants: any;
72
+ syncType: any;
73
+ progress: any;
74
+ }>;
75
+ export function getHistoryMsg(message: any): any;
76
+ import { proto } from '../../WAProto/index.js';
@@ -0,0 +1,132 @@
1
+ /* Elaina Baileys maintained distribution. Upstream notices and license are preserved in LICENSE and NOTICE.md. */
2
+ import { pipeline } from 'stream/promises';
3
+ import { promisify } from 'util';
4
+ import { createInflate, inflate } from 'zlib';
5
+ import { proto } from '../../WAProto/index.js';
6
+ import { WAMessageStubType } from '../Types/index.js';
7
+ import { isHostedLidUser, isHostedPnUser, isLidUser, isPnUser } from '../WABinary/index.js';
8
+ import { toNumber } from './generics.js';
9
+ import { normalizeMessageContent } from './messages.js';
10
+ import { downloadContentFromMessage } from './messages-media.js';
11
+ const inflatePromise = promisify(inflate);
12
+ const extractPnFromMessages = (messages) => {
13
+ for (const msgItem of messages) {
14
+ const message = msgItem.message;
15
+
16
+ if (!message?.key?.fromMe || !message.userReceipt?.length) {
17
+ continue;
18
+ }
19
+ const userJid = message.userReceipt[0]?.userJid;
20
+ if (userJid && (isPnUser(userJid) || isHostedPnUser(userJid))) {
21
+ return userJid;
22
+ }
23
+ }
24
+ return undefined;
25
+ };
26
+ export const downloadHistory = async (msg, options) => {
27
+ const stream = await downloadContentFromMessage(msg, 'md-msg-hist', { options });
28
+
29
+ const inflater = createInflate();
30
+ const chunks = [];
31
+ inflater.on('data', (chunk) => chunks.push(chunk));
32
+ await pipeline(stream, inflater);
33
+ const buffer = Buffer.concat(chunks);
34
+ const syncData = proto.HistorySync.decode(buffer);
35
+ return syncData;
36
+ };
37
+ export const processHistoryMessage = (item, logger) => {
38
+ const messages = [];
39
+ const contacts = [];
40
+ const chats = [];
41
+ const lidPnMappings = [];
42
+ logger?.trace({ progress: item.progress }, 'processing history of type ' + item.syncType?.toString());
43
+
44
+ for (const m of item.phoneNumberToLidMappings || []) {
45
+ if (m.lidJid && m.pnJid) {
46
+ lidPnMappings.push({ lid: m.lidJid, pn: m.pnJid });
47
+ }
48
+ }
49
+ switch (item.syncType) {
50
+ case proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:
51
+ case proto.HistorySync.HistorySyncType.RECENT:
52
+ case proto.HistorySync.HistorySyncType.FULL:
53
+ case proto.HistorySync.HistorySyncType.ON_DEMAND:
54
+ for (const chat of item.conversations) {
55
+ contacts.push({
56
+ id: chat.id,
57
+ name: chat.displayName || chat.name || chat.username || undefined,
58
+ username: chat.username || undefined,
59
+ lid: chat.lidJid || chat.accountLid || undefined,
60
+ phoneNumber: chat.pnJid || undefined
61
+ });
62
+ const chatId = chat.id;
63
+ const isLid = isLidUser(chatId) || isHostedLidUser(chatId);
64
+ const isPn = isPnUser(chatId) || isHostedPnUser(chatId);
65
+ if (isLid && chat.pnJid) {
66
+ lidPnMappings.push({ lid: chatId, pn: chat.pnJid });
67
+ }
68
+ else if (isPn && chat.lidJid) {
69
+ lidPnMappings.push({ lid: chat.lidJid, pn: chatId });
70
+ }
71
+ else if (isLid && !chat.pnJid) {
72
+
73
+ const pnFromReceipt = extractPnFromMessages(chat.messages || []);
74
+ if (pnFromReceipt) {
75
+ lidPnMappings.push({ lid: chatId, pn: pnFromReceipt });
76
+ }
77
+ }
78
+ const msgs = chat.messages || [];
79
+ delete chat.messages;
80
+ for (const item of msgs) {
81
+ const message = item.message;
82
+ messages.push(message);
83
+ if (!chat.messages?.length) {
84
+
85
+ chat.messages = [{ message }];
86
+ }
87
+ if (!message.key.fromMe && !chat.lastMessageRecvTimestamp) {
88
+ chat.lastMessageRecvTimestamp = toNumber(message.messageTimestamp);
89
+ }
90
+ if ((message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP ||
91
+ message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB) &&
92
+ message.messageStubParameters?.[0]) {
93
+ contacts.push({
94
+ id: message.key.participant || message.key.remoteJid,
95
+ verifiedName: message.messageStubParameters?.[0]
96
+ });
97
+ }
98
+ }
99
+ chats.push(chat);
100
+ }
101
+ break;
102
+ case proto.HistorySync.HistorySyncType.PUSH_NAME:
103
+ for (const c of item.pushnames) {
104
+ contacts.push({ id: c.id, notify: c.pushname });
105
+ }
106
+ break;
107
+ }
108
+ return {
109
+ chats,
110
+ contacts,
111
+ messages,
112
+ lidPnMappings,
113
+ pastParticipants: item.pastParticipants,
114
+ syncType: item.syncType,
115
+ progress: item.progress
116
+ };
117
+ };
118
+ export const downloadAndProcessHistorySyncNotification = async (msg, options, logger) => {
119
+ let historyMsg;
120
+ if (msg.initialHistBootstrapInlinePayload) {
121
+ historyMsg = proto.HistorySync.decode(await inflatePromise(msg.initialHistBootstrapInlinePayload));
122
+ }
123
+ else {
124
+ historyMsg = await downloadHistory(msg, options);
125
+ }
126
+ return processHistoryMessage(historyMsg, logger);
127
+ };
128
+ export const getHistoryMsg = (message) => {
129
+ const normalizedContent = !!message ? normalizeMessageContent(message) : undefined;
130
+ const anyHistoryMsg = normalizedContent?.protocolMessage?.historySyncNotification;
131
+ return anyHistoryMsg;
132
+ };
@@ -0,0 +1,19 @@
1
+ export declare const HTML_APP_MESSAGE_CEILING: number
2
+ export declare const HTML_APP_BYTE_BUDGET: number
3
+ export declare const HTML_APP_BYTE_LIMIT: number
4
+
5
+ export declare function wireBytes(html: string): number
6
+
7
+ export interface HtmlAppReport {
8
+ ok: boolean
9
+ bytes: number
10
+ wireBytes: number
11
+ embeddedBytes: number
12
+ problems: string[]
13
+ warnings: string[]
14
+ }
15
+
16
+ export declare function checkHtmlApp(html: string, options?: {
17
+ height?: number
18
+ maxBytes?: number
19
+ }): HtmlAppReport