@hiroosy/baileys-lite 0.0.4 → 0.3.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 (116) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +658 -10
  3. package/WAProto/index.js +2 -2558
  4. package/engine-requirements.js +3 -4
  5. package/package.json +8 -3
  6. package/src/binary/wa-binary.js +3 -25
  7. package/src/constants.js +7 -15
  8. package/src/defaults.js +2 -5
  9. package/src/foundation/ai-rich.js +530 -0
  10. package/src/foundation/audio-duration.js +43 -103
  11. package/src/foundation/audio-samples.js +19 -37
  12. package/src/foundation/boom.js +0 -7
  13. package/src/foundation/cache.js +4 -26
  14. package/src/foundation/concurrency.js +1 -19
  15. package/src/foundation/curve25519.js +7 -39
  16. package/src/foundation/link-preview.js +15 -57
  17. package/src/foundation/logger.js +0 -11
  18. package/src/foundation/long.js +4 -14
  19. package/src/foundation/protobuf-minimal.js +21 -53
  20. package/src/foundation/qrcode-terminal.js +273 -0
  21. package/src/foundation/sql-database.js +702 -0
  22. package/src/foundation/wa-crypto.js +2 -31
  23. package/src/foundation/zip.js +25 -41
  24. package/src/index.js +8 -18
  25. package/src/signal/libsignal.js +23 -78
  26. package/src/signal/signal-group.js +0 -35
  27. package/src/signal/signal-repository.js +10 -29
  28. package/src/socket/business-communities.js +12 -31
  29. package/src/socket/chats.js +5 -8
  30. package/src/socket/groups-newsletter.js +18 -17
  31. package/src/socket/messages-recv.js +81 -127
  32. package/src/socket/messages-send.js +372 -139
  33. package/src/socket/socket-core.js +227 -157
  34. package/src/socket/usync.js +2 -6
  35. package/src/socket-client/native-websocket.js +344 -0
  36. package/src/socket-client/websocket-client.js +84 -38
  37. package/src/utils/auth-state-core.js +14 -56
  38. package/src/utils/auth-state-storage.js +7 -42
  39. package/src/utils/chat-sync.js +4 -26
  40. package/src/utils/media.js +15 -71
  41. package/src/utils/message-compose.js +208 -85
  42. package/src/utils/message-processing.js +10 -65
  43. package/src/utils/username.js +19 -0
  44. package/src/utils/wa-protocol-core.js +71 -127
  45. package/src/vendor/jpeg-js/decoder.js +75 -136
  46. package/src/vendor/jpeg-js/encoder.js +179 -264
  47. package/src/vendor/pngjs/bitmapper.js +5 -27
  48. package/src/vendor/pngjs/bitpacker.js +4 -12
  49. package/src/vendor/pngjs/constants.js +3 -11
  50. package/src/vendor/pngjs/crc.js +0 -6
  51. package/src/vendor/pngjs/filter-pack.js +1 -7
  52. package/src/vendor/pngjs/filter-parse-sync.js +0 -6
  53. package/src/vendor/pngjs/filter-parse.js +1 -11
  54. package/src/vendor/pngjs/format-normaliser.js +5 -11
  55. package/src/vendor/pngjs/interlace.js +7 -24
  56. package/src/vendor/pngjs/packer-sync.js +0 -11
  57. package/src/vendor/pngjs/packer.js +7 -15
  58. package/src/vendor/pngjs/paeth-predictor.js +0 -6
  59. package/src/vendor/pngjs/parser-sync.js +0 -8
  60. package/src/vendor/pngjs/parser.js +5 -29
  61. package/src/vendor/pngjs/png-sync.js +0 -7
  62. package/src/vendor/pngjs/sync-inflate.js +7 -16
  63. package/src/vendor/pngjs/sync-reader.js +4 -11
  64. package/src/voip/WaVoipCoordinator.js +158 -0
  65. package/src/voip/app-data/WaAppDataStream.js +193 -0
  66. package/src/voip/app-data/protocol.js +172 -0
  67. package/src/voip/bytes.js +63 -0
  68. package/src/voip/call/WaCallManager.js +442 -0
  69. package/src/voip/call/WaCallMediaSession.js +1705 -0
  70. package/src/voip/call/call-state.js +203 -0
  71. package/src/voip/crypto/encryption.js +13 -0
  72. package/src/voip/crypto/primitives.js +21 -0
  73. package/src/voip/crypto/rtcp.js +66 -0
  74. package/src/voip/crypto/srtp.js +180 -0
  75. package/src/voip/crypto/ssrc.js +15 -0
  76. package/src/voip/index.js +628 -0
  77. package/src/voip/media/WaAudioEngine.js +486 -0
  78. package/src/voip/media/WaVideoEngine.js +275 -0
  79. package/src/voip/media/audio-codec.js +0 -0
  80. package/src/voip/media/audio-reorder.js +107 -0
  81. package/src/voip/media/h264.js +246 -0
  82. package/src/voip/media/mlow-codec.js +465 -0
  83. package/src/voip/media/rtcp.js +68 -0
  84. package/src/voip/media/rtp.js +242 -0
  85. package/src/voip/protobuf.js +30 -0
  86. package/src/voip/relay/WaManualRelay.js +609 -0
  87. package/src/voip/relay/datachannel/pre-negotiated.js +25 -0
  88. package/src/voip/relay/dtls/aead.js +46 -0
  89. package/src/voip/relay/dtls/cert-builder.js +102 -0
  90. package/src/voip/relay/dtls/der.js +98 -0
  91. package/src/voip/relay/dtls/ecdhe.js +37 -0
  92. package/src/voip/relay/dtls/handshake-framing.js +100 -0
  93. package/src/voip/relay/dtls/handshake-messages.js +158 -0
  94. package/src/voip/relay/dtls/handshake.js +582 -0
  95. package/src/voip/relay/dtls/prf.js +39 -0
  96. package/src/voip/relay/dtls/record.js +56 -0
  97. package/src/voip/relay/relay-ack.js +141 -0
  98. package/src/voip/relay/sctp/association.js +434 -0
  99. package/src/voip/relay/sctp/crc32c.js +21 -0
  100. package/src/voip/relay/sctp/wire.js +226 -0
  101. package/src/voip/relay/stun.js +463 -0
  102. package/src/voip/shim/baileys-resolve.js +7 -0
  103. package/src/voip/shim/core.js +66 -0
  104. package/src/voip/shim/crypto.js +6 -0
  105. package/src/voip/shim/proto.js +10 -0
  106. package/src/voip/shim/protocol.js +130 -0
  107. package/src/voip/shim/transport.js +82 -0
  108. package/src/voip/shim/util.js +207 -0
  109. package/src/voip/signaling/bridge.js +102 -0
  110. package/src/voip/signaling/screen-share.js +60 -0
  111. package/src/voip/signaling/signaling.js +491 -0
  112. package/src/voip/types.js +69 -0
  113. package/src/voip/voip-deps.js +243 -0
  114. package/src/voip/voipClient.js +314 -0
  115. package/src/wam/wam-constants.js +0 -1
  116. package/src/wam/wam.js +2 -7
@@ -1,10 +1,3 @@
1
- /**
2
- * Auth-state and message-decode utilities. Combines what used to be:
3
- * auth-utils.js, pre-key-manager.js, identity-change-handler.js,
4
- * decode-wa-message.js, tc-token-utils.js
5
- *
6
- * `async_hooks` (AsyncLocalStorage) is Node built-in, kept as-is.
7
- */
8
1
  import { AsyncLocalStorage } from 'node:async_hooks'
9
2
  import { randomBytes } from 'node:crypto'
10
3
  import { Boom } from '../foundation/boom.js'
@@ -36,11 +29,6 @@ const DEFAULT_CACHE_TTLS = {
36
29
  USER_DEVICES: 5 * 60
37
30
  }
38
31
 
39
- /* ------------------------------------------------------------------ */
40
- /* PreKeyManager */
41
- /* ------------------------------------------------------------------ */
42
-
43
- /** Manages pre-key operations with proper concurrency control */
44
32
  export class PreKeyManager {
45
33
  constructor(store, logger) {
46
34
  this.store = store
@@ -94,7 +82,6 @@ export class PreKeyManager {
94
82
  }
95
83
  }
96
84
 
97
- /** Validate and process pre-key deletions outside transactions */
98
85
  async validateDeletions(data, keyType) {
99
86
  const keyData = data[keyType]
100
87
  if (!keyData) return
@@ -112,19 +99,11 @@ export class PreKeyManager {
112
99
  }
113
100
  }
114
101
 
115
- /* ------------------------------------------------------------------ */
116
- /* Signal key store caching + transaction capability */
117
- /* ------------------------------------------------------------------ */
118
-
119
- // One instance per process: a per-socket AsyncLocalStorage leaks the heap under Node's legacy
120
- // async-context propagation, where every live instance tags every pending async resource. The
121
- // value is keyed by store token so a store only ever sees its own context, even when another
122
- // wrapped store runs inside its transaction.
123
102
  const txStorage = new AsyncLocalStorage()
124
103
 
125
- /** Adds caching capability to a SignalKeyStore */
126
104
  export function makeCacheableSignalKeyStore(store, logger, _cache) {
127
- const cache = _cache || new Cache({ ttl: DEFAULT_CACHE_TTLS.SIGNAL_STORE * 1000 })
105
+
106
+ const cache = _cache || new Cache({ max: 8192, ttl: DEFAULT_CACHE_TTLS.SIGNAL_STORE * 1000 })
128
107
  const cacheMutex = makeMutex()
129
108
 
130
109
  function getUniqueId(type, id) {
@@ -175,9 +154,8 @@ export function makeCacheableSignalKeyStore(store, logger, _cache) {
175
154
  }
176
155
  }
177
156
 
178
- /** Adds DB-like transaction capability to the SignalKeyStore, via AsyncLocalStorage context. */
179
157
  export const addTransactionCapability = (state, logger, { maxCommitRetries, delayBetweenTriesMs }) => {
180
- const keyQueues = new Map() // concurrency control per signal data type
158
+ const keyQueues = new Map()
181
159
  const txMutexes = new Map()
182
160
  const txMutexRefCounts = new Map()
183
161
  const preKeyManager = new PreKeyManager(state, logger)
@@ -231,7 +209,7 @@ export const addTransactionCapability = (state, logger, { maxCommitRetries, dela
231
209
  return {
232
210
  get: async (type, ids) => {
233
211
  const ctx = txStorage.getStore()
234
- if (!ctx) return state.get(type, ids) // no transaction - direct read, no exclusive lock
212
+ if (!ctx) return state.get(type, ids)
235
213
 
236
214
  const cached = ctx.cache[type] || {}
237
215
  const missing = ids.filter(id => !(id in cached))
@@ -252,7 +230,7 @@ export const addTransactionCapability = (state, logger, { maxCommitRetries, dela
252
230
  set: async data => {
253
231
  const ctx = txStorage.getStore()
254
232
  if (!ctx) {
255
- // no transaction - direct write with per-type queue protection
233
+
256
234
  const types = Object.keys(data)
257
235
  for (const type of types) {
258
236
  if (type === 'pre-key') await preKeyManager.validateDeletions(data, type)
@@ -308,9 +286,6 @@ export const addTransactionCapability = (state, logger, { maxCommitRetries, dela
308
286
  }
309
287
  }
310
288
 
311
- /**
312
- * Returns the authenticated user's JID, or throws a Boom-401 if creds are not yet authenticated.
313
- */
314
289
  export const assertMeId = creds => {
315
290
  const id = creds.me?.id
316
291
  if (!id) throw new Boom('Cannot proceed: socket is not authenticated yet (creds.me.id is missing)', { statusCode: 401 })
@@ -339,10 +314,6 @@ export const initAuthCreds = () => {
339
314
  }
340
315
  }
341
316
 
342
- /* ------------------------------------------------------------------ */
343
- /* Identity change handling */
344
- /* ------------------------------------------------------------------ */
345
-
346
317
  export async function handleIdentityChange(node, ctx) {
347
318
  const from = node.attrs.from
348
319
  if (!from) return { action: 'invalid_notification' }
@@ -393,14 +364,10 @@ export async function handleIdentityChange(node, ctx) {
393
364
  }
394
365
 
395
366
  function isStringNullOrEmptyLocal(value) {
396
- // eslint-disable-next-line eqeqeq
367
+
397
368
  return value == null || value === ''
398
369
  }
399
370
 
400
- /* ------------------------------------------------------------------ */
401
- /* Message node decode / decrypt */
402
- /* ------------------------------------------------------------------ */
403
-
404
371
  export const getDecryptionJid = async (sender, repository) => {
405
372
  if (isLidUser(sender) || isHostedLidUser(sender)) return sender
406
373
  const mapped = await repository.lidMapping.getLIDForPN(sender)
@@ -430,7 +397,6 @@ export const DECRYPTION_RETRY_CONFIG = {
430
397
  sessionRecordErrors: ['No session record', 'SessionError: No session record']
431
398
  }
432
399
 
433
- /** NACK reason codes we send to the server (client → server) */
434
400
  export const NACK_REASONS = {
435
401
  SenderReachoutTimelocked: 463,
436
402
  ParsingError: 487,
@@ -448,7 +414,6 @@ export const NACK_REASONS = {
448
414
  DBOperationFailed: 552
449
415
  }
450
416
 
451
- /** Server-side error codes returned in ack stanzas (server → client) with dedicated handlers. */
452
417
  export const SERVER_ERROR_CODES = {
453
418
  MessageAccountRestriction: '463',
454
419
  SmaxInvalid: '479'
@@ -469,7 +434,6 @@ export const extractAddressingContext = stanza => {
469
434
  return { addressingMode, senderAlt, recipientAlt }
470
435
  }
471
436
 
472
- /** Decode the received node as a message. NOTE: this only parses the message, not decrypt. */
473
437
  export function decodeMessageNode(stanza, meId, meLid) {
474
438
  let msgType
475
439
  let chatId
@@ -493,8 +457,7 @@ export function decodeMessageNode(stanza, meId, meLid) {
493
457
  if (isMe(from) || isMeLid(from)) fromMe = true
494
458
  chatId = recipient
495
459
  } else {
496
- // Peer-routed self stanzas (history sync, app-state sync, etc.) arrive with `from` set to our
497
- // own device but no `recipient` attribute — still mark as fromMe so self-only handlers run.
460
+
498
461
  if (isMe(from) || isMeLid(from)) fromMe = true
499
462
  chatId = from
500
463
  }
@@ -574,7 +537,7 @@ export const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
574
537
  fullMessage.verifiedBizName = details.verifiedName
575
538
  }
576
539
  if (tag === 'unavailable' && attrs.type === 'view_once') {
577
- fullMessage.key.isViewOnce = true // TODO: remove from here and add a STUB TYPE
540
+ fullMessage.key.isViewOnce = true
578
541
  }
579
542
  if (attrs.count && tag === 'enc') fullMessage.retryCount = Number(attrs.count)
580
543
  if (tag !== 'enc' && tag !== 'plaintext') continue
@@ -638,25 +601,20 @@ export const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
638
601
  }
639
602
  }
640
603
 
641
- /* ------------------------------------------------------------------ */
642
- /* Trusted-contact ("tctoken") handling */
643
- /* ------------------------------------------------------------------ */
644
-
645
604
  const BOT_PHONE_REGEX = /^1313555\d{4}$|^131655500\d{2}$/
646
605
 
647
- /** Mirrors WA Web's `Wid.isRegularUser()` (user ∧ ¬PSA ∧ ¬Bot). */
648
606
  function isRegularUser(jid) {
649
607
  if (!jid) return false
650
608
  const user = jid.split('@')[0] ?? ''
651
- if (user === '0') return false // PSA
609
+ if (user === '0') return false
652
610
  if (BOT_PHONE_REGEX.test(user)) return false
653
611
  if (isJidMetaAI(jid)) return false
654
612
  return !!(isPnUser(jid) || isLidUser(jid) || isHostedPnUser(jid) || isHostedLidUser(jid) || jid.endsWith('@c.us'))
655
613
  }
656
614
 
657
- const TC_TOKEN_BUCKET_DURATION = 604800 // 7 days
658
- const TC_TOKEN_NUM_BUCKETS = 4 // ~28-day rolling window
659
- /** Sentinel key under `tctoken` store holding a JSON array of tracked storage JIDs. */
615
+ const TC_TOKEN_BUCKET_DURATION = 604800
616
+ const TC_TOKEN_NUM_BUCKETS = 4
617
+
660
618
  export const TC_TOKEN_INDEX_KEY = '__index'
661
619
 
662
620
  export async function readTcTokenIndex(keys) {
@@ -746,7 +704,7 @@ export async function storeTcTokensFromIqResult({ result, fallbackJid, keys, get
746
704
  const tokenNodes = getBinaryNodeChildren(tokensNode, 'token')
747
705
  for (const tokenNode of tokenNodes) {
748
706
  if (tokenNode.attrs.type !== 'trusted_contact' || !(tokenNode.content instanceof Uint8Array)) continue
749
- // In notifications tokenNode.attrs.jid is your own device JID, not the sender's
707
+
750
708
  const rawJid = jidNormalizedUser(fallbackJid || tokenNode.attrs.jid)
751
709
  if (!isRegularUser(rawJid)) continue
752
710
  const storageJid = await resolveTcTokenJid(rawJid, getLIDForPN)
@@ -754,7 +712,7 @@ export async function storeTcTokensFromIqResult({ result, fallbackJid, keys, get
754
712
  const existingEntry = existingTcData[storageJid]
755
713
  const existingTs = existingEntry?.timestamp ? Number(existingEntry.timestamp) : 0
756
714
  const incomingTs = tokenNode.attrs.t ? Number(tokenNode.attrs.t) : 0
757
- if (!incomingTs) continue // timestamp-less tokens would be immediately expired
715
+ if (!incomingTs) continue
758
716
  if (existingTs > 0 && existingTs > incomingTs) continue
759
717
  await keys.set({
760
718
  tctoken: { [storageJid]: { ...existingEntry, token: Buffer.from(tokenNode.content), timestamp: tokenNode.attrs.t } }
@@ -1,13 +1,3 @@
1
- /**
2
- * Auth-state persistence adapters. Combines what used to be:
3
- * use-multi-file-auth-state.js, use-single-file-auth-state.js, use-sqlite-auth-state.js
4
- *
5
- * SQLite backend is `node:sqlite` (built into Node, stable release-candidate as of Node 24; no
6
- * install needed). `opts.database` still accepts any object shaped like `better-sqlite3` (or
7
- * `node:sqlite`'s own DatabaseSync) if the app wants to bring its own connection/driver — see
8
- * DB_ADAPTER below for the two shims that bridge the small API differences.
9
- */
10
- import { DatabaseSync } from 'node:sqlite'
11
1
  import { mkdir, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises'
12
2
  import { join } from 'node:path'
13
3
  import { proto } from '../../WAProto/index.js'
@@ -15,19 +5,10 @@ import { initAuthCreds } from './auth-state-core.js'
15
5
  import { BufferJSON } from './wa-protocol-core.js'
16
6
  import { Cache } from '../foundation/cache.js'
17
7
  import { makeKeyedMutex } from '../foundation/concurrency.js'
8
+ import { SqlDatabase } from '../foundation/sql-database.js'
18
9
 
19
- /* ------------------------------------------------------------------ */
20
- /* Multi-file auth state (one JSON file per key) */
21
- /* ------------------------------------------------------------------ */
22
-
23
- /**
24
- * stores the full authentication state in a single folder.
25
- * Far more efficient than singlefileauthstate.
26
- *
27
- * Wouldn't endorse this for anything beyond a bot; use a proper DB for production.
28
- */
29
10
  export const useMultiFileAuthState = async folder => {
30
- const fileLock = makeKeyedMutex() // guards concurrent read/write of the same file path
11
+ const fileLock = makeKeyedMutex()
31
12
 
32
13
  const fixFileName = file => file?.replace(/\//g, '__')?.replace(/:/g, '-')
33
14
 
@@ -53,11 +34,11 @@ export const useMultiFileAuthState = async folder => {
53
34
  try {
54
35
  await unlink(filePath)
55
36
  } catch {
56
- // ignore
37
+
57
38
  }
58
39
  })
59
40
  } catch {
60
- // ignore
41
+
61
42
  }
62
43
  }
63
44
 
@@ -104,10 +85,6 @@ export const useMultiFileAuthState = async folder => {
104
85
  }
105
86
  }
106
87
 
107
- /* ------------------------------------------------------------------ */
108
- /* Single-file auth state (one JSON file, in-memory cached) */
109
- /* ------------------------------------------------------------------ */
110
-
111
88
  const SIGNAL_STORE_TTL_MS = 5 * 60 * 1000
112
89
  const FLUSH_TIMEOUT_MS = 3000
113
90
 
@@ -141,7 +118,7 @@ export const useSingleFileAuthState = async fileName => {
141
118
  await writeFile(tempFile, JSON.stringify(fileData, BufferJSON.replacer))
142
119
  await rename(tempFile, fileName)
143
120
  } catch {
144
- // ignore
121
+
145
122
  }
146
123
  })
147
124
  }, FLUSH_TIMEOUT_MS)
@@ -201,17 +178,6 @@ export const useSingleFileAuthState = async fileName => {
201
178
  }
202
179
  }
203
180
 
204
- /* ------------------------------------------------------------------ */
205
- /* SQLite auth state (built-in `node:sqlite`, no install required) */
206
- /* ------------------------------------------------------------------ */
207
-
208
- /**
209
- * `node:sqlite`'s DatabaseSync has no `.pragma()` and no `.transaction()` (the two things
210
- * `better-sqlite3` offers beyond plain `.exec()`/`.prepare()`). This adapter fills both in with
211
- * the same net effect, and passes through untouched when `opts.database` is a `better-sqlite3`
212
- * instance (or anything else that already has real `.pragma`/`.transaction` methods) so bring-
213
- * your-own-driver keeps working exactly as before.
214
- */
215
181
  function adaptDb(db) {
216
182
  const pragma = typeof db.pragma === 'function' ? stmt => db.pragma(stmt) : stmt => db.exec(`PRAGMA ${stmt}`)
217
183
  const transaction =
@@ -248,10 +214,9 @@ CREATE INDEX IF NOT EXISTS signal_keys_type_idx ON signal_keys(type);
248
214
  `
249
215
 
250
216
  export async function useSqliteAuthState(opts) {
251
- const rawDb = opts.database ?? new DatabaseSync(opts.dbPath)
217
+ const rawDb = opts.database ?? new SqlDatabase(opts.dbPath)
252
218
  const { db, pragma, transaction } = adaptDb(rawDb)
253
- // WAL mode allows concurrent reads alongside a single writer; matches
254
- // what SQLite recommends for read-heavy workloads with sporadic writes.
219
+
255
220
  pragma('journal_mode = WAL')
256
221
  pragma('synchronous = NORMAL')
257
222
  db.exec(CREATE_SCHEMA_SQL)
@@ -1,9 +1,3 @@
1
- /**
2
- * Chat/app-state sync utilities. Combines what used to be chat-utils.js,
3
- * event-buffer.js, and sync-action-utils.js.
4
- *
5
- * expandAppStateKeys comes from ../foundation/wa-crypto.js (native).
6
- */
7
1
  import { EventEmitter } from 'node:events'
8
2
  import { proto } from '../../WAProto/index.js'
9
3
  import { expandAppStateKeys } from '../foundation/wa-crypto.js'
@@ -15,10 +9,6 @@ import { downloadContentFromMessage } from './media.js'
15
9
  import { updateMessageWithReaction, updateMessageWithReceipt } from './message-compose.js'
16
10
  import { isRealMessage, shouldIncrementChatUnread } from './message-processing.js'
17
11
 
18
- /* ------------------------------------------------------------------ */
19
- /* App-state (chat-utils): LTHash / patch encode-decode */
20
- /* ------------------------------------------------------------------ */
21
-
22
12
  const mutationKeys = keydata => {
23
13
  const keys = expandAppStateKeys(keydata)
24
14
  return { indexKey: keys.indexKey, valueEncryptionKey: keys.valueEncryptionKey, valueMacKey: keys.valueMacKey, snapshotMacKey: keys.snapshotMacKey, patchMacKey: keys.patchMacKey }
@@ -55,7 +45,7 @@ export const makeLtHashGenerator = ({ indexValueMap, hash }) => {
55
45
  const indexMacBase64 = Buffer.from(indexMac).toString('base64')
56
46
  const prevOp = indexValueMap[indexMacBase64]
57
47
  if (operation === proto.SyncdMutation.SyncdOperation.REMOVE) {
58
- if (!prevOp) return // WA Web logs+skips; handled downstream by MAC validation / snapshot recovery
48
+ if (!prevOp) return
59
49
  delete indexValueMap[indexMacBase64]
60
50
  } else {
61
51
  addBuffs.push(valueMac)
@@ -81,10 +71,8 @@ export const ensureLTHashStateVersion = state => {
81
71
 
82
72
  export const MAX_SYNC_ATTEMPTS = 2
83
73
 
84
- /** WA Web treats missing app-state sync keys as "Blocked" (waits for key arrival), not fatal. */
85
74
  export const isMissingKeyError = error => error?.data?.isMissingKey === true
86
75
 
87
- /** TypeError indicates a WASM crash; otherwise give up after MAX_SYNC_ATTEMPTS. Missing keys handled separately. */
88
76
  export const isAppStateSyncIrrecoverable = (error, attempts) => attempts >= MAX_SYNC_ATTEMPTS || error?.name === 'TypeError'
89
77
 
90
78
  export const encodeSyncdPatch = async ({ type, index, syncAction, apiVersion, operation }, myAppStateKeyId, state, getAppStateSyncKey) => {
@@ -137,7 +125,7 @@ export const decodeSyncdMutations = async (msgMutations, initialState, getAppSta
137
125
  key = await getKey(record.keyId.id)
138
126
  } catch (err) {
139
127
  if (isMissingKeyError(err)) throw err
140
- continue // other errors -> individual record corruption, skip and keep going
128
+ continue
141
129
  }
142
130
  const content = record.value.blob
143
131
  const encContent = content.subarray(0, -32)
@@ -301,7 +289,7 @@ export const decodePatches = async (name, syncds, initial, getAppStateSyncKey, o
301
289
  break
302
290
  }
303
291
  }
304
- syncd.mutations = [] // clear memory used up by the mutations
292
+ syncd.mutations = []
305
293
  }
306
294
  return { state: newState, mutationMap }
307
295
  }
@@ -549,11 +537,6 @@ export const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) =
549
537
  }
550
538
  }
551
539
 
552
- /* ------------------------------------------------------------------ */
553
- /* Sync action -> event mapping (pure) */
554
- /* ------------------------------------------------------------------ */
555
-
556
- /** Process contactAction and return events to emit. Pure function - no side effects. */
557
540
  export const processContactAction = (action, id, logger) => {
558
541
  const results = []
559
542
  if (!id) {
@@ -562,7 +545,7 @@ export const processContactAction = (action, id, logger) => {
562
545
  }
563
546
  const lidJid = action.lidJid
564
547
  const idIsPn = isPnUser(id)
565
- const phoneNumber = idIsPn ? id : action.pnJid || undefined // PN is in index[1], not usually in contactAction.pnJid
548
+ const phoneNumber = idIsPn ? id : action.pnJid || undefined
566
549
  results.push({
567
550
  event: 'contacts.upsert',
568
551
  data: [{ id, name: action.fullName || action.firstName || action.username || undefined, username: action.username || undefined, lid: lidJid || undefined, phoneNumber }]
@@ -578,10 +561,6 @@ export const emitSyncActionResults = (ev, results) => {
578
561
  }
579
562
  }
580
563
 
581
- /* ------------------------------------------------------------------ */
582
- /* Event buffer */
583
- /* ------------------------------------------------------------------ */
584
-
585
564
  const BUFFERABLE_EVENT_SET = new Set([
586
565
  'messaging-history.set',
587
566
  'chats.upsert',
@@ -909,7 +888,6 @@ function append(data, historyCache, event, eventData, logger) {
909
888
  }
910
889
  }
911
890
 
912
- /** The event buffer logically consolidates different events into a single event, making data processing more efficient. */
913
891
  export const makeEventBuffer = logger => {
914
892
  const ev = new EventEmitter()
915
893
  const historyCache = new Set()
@@ -1,11 +1,3 @@
1
- /**
2
- * Media handling utilities. Combines what used to be messages-media.js and link-preview.js.
3
- *
4
- * Optional packages (`sharp`, `@napi-rs/image`, `jimp`) are NOT declared in package.json. They are dynamically
5
- * imported and used only if the application installs them itself; each call site degrades gracefully when one is
6
- * missing (see below). Audio durations, WAV/FLAC waveforms and link previews no longer need `music-metadata`,
7
- * `audio-decode` or `link-preview-js` — they're handled by the built-in modules in ../foundation.
8
- */
9
1
  import { spawn } from 'node:child_process'
10
2
  import { audioDuration } from '../foundation/audio-duration.js'
11
3
  import { decodeChannel0, waveformFromSamples } from '../foundation/audio-samples.js'
@@ -82,10 +74,6 @@ const NEWSLETTER_MEDIA_PATH_MAP = {
82
74
 
83
75
  const getTmpFilesDirectory = () => tmpdir()
84
76
 
85
- /* ------------------------------------------------------------------ */
86
- /* Image processing (sharp / @napi-rs/image / jimp — first available) */
87
- /* ------------------------------------------------------------------ */
88
-
89
77
  let imageProcessingLibrary
90
78
  export const getImageProcessingLibrary = async () => {
91
79
  if (imageProcessingLibrary) return imageProcessingLibrary
@@ -128,17 +116,16 @@ export const getRawMediaUploadData = async (media, mediaType, logger) => {
128
116
  try {
129
117
  await fs.unlink(filePath)
130
118
  } catch {
131
- // ignore
119
+
132
120
  }
133
121
  throw error
134
122
  }
135
123
  }
136
124
 
137
- /** generates all the keys required to encrypt/decrypt & sign a media message */
138
125
  export async function getMediaKeys(buffer, mediaType) {
139
126
  if (!buffer) throw new Boom('Cannot derive from empty media key')
140
127
  if (typeof buffer === 'string') buffer = Buffer.from(buffer.replace('data:;base64,', ''), 'base64')
141
- // expand using HKDF to 112 bytes, also pass in the relevant app info
128
+
142
129
  const expandedMediaKey = hkdf(buffer, 112, { info: hkdfInfoKey(mediaType) })
143
130
  return {
144
131
  iv: expandedMediaKey.slice(0, 16),
@@ -147,7 +134,6 @@ export async function getMediaKeys(buffer, mediaType) {
147
134
  }
148
135
  }
149
136
 
150
- /** Extracts video thumb using FFMPEG */
151
137
  export const extractVideoThumb = async (path, time, size) => {
152
138
  const ffmpeg = spawn(
153
139
  'ffmpeg',
@@ -238,24 +224,16 @@ export const generateProfilePicture = async (mediaUpload, dimensions) => {
238
224
  return { img: await img }
239
225
  }
240
226
 
241
- /** gets the SHA256 of the given media message */
242
227
  export const mediaMessageSHA256B64 = message => {
243
228
  const media = Object.values(message)[0]
244
229
  return media?.fileSha256 && Buffer.from(media.fileSha256).toString('base64')
245
230
  }
246
231
 
247
- /**
248
- * Duration of an audio file in seconds. Accepts a Buffer, a file path, or a Readable stream.
249
- *
250
- * Built-in parser: Ogg Opus/Vorbis, WAV, FLAC, MP4/M4A, MP3, ADTS-AAC, AIFF/AIFF-C, Matroska/WebM, AMR-NB/WB —
251
- * see src/foundation/audio-duration.js. Anything else (WMA, APE, WavPack, Musepack, DSD, ...) resolves
252
- * `undefined` rather than guessing.
253
- */
254
232
  export async function getAudioDuration(buffer) {
255
233
  if (!Buffer.isBuffer(buffer) && typeof buffer !== 'string') buffer = await toBuffer(buffer)
256
234
  const native = await audioDuration(buffer)
257
235
  if (typeof native === 'number' && Number.isFinite(native)) return native
258
- return ffprobeDuration(buffer) // containers the built-in parser doesn't cover (WMA, APE, ...)
236
+ return ffprobeDuration(buffer)
259
237
  }
260
238
 
261
239
  async function ffprobeDuration(input) {
@@ -271,15 +249,10 @@ async function ffprobeDuration(input) {
271
249
  const seconds = parseFloat(Buffer.concat(outChunks).toString('utf8').trim())
272
250
  return Number.isFinite(seconds) ? seconds : undefined
273
251
  } catch {
274
- return undefined // ffprobe not installed
252
+ return undefined
275
253
  }
276
254
  }
277
255
 
278
- /**
279
- * First channel of an audio file as float samples via the system `ffmpeg` binary (a program, not an npm package;
280
- * media.js already shells out to it for video thumbnails). Used only for containers the built-in decoder cannot
281
- * read (Ogg Opus/Vorbis, MP3, AAC/M4A, AMR, ...). Resolves `undefined` when ffmpeg is missing or fails.
282
- */
283
256
  const decodeChannel0WithFfmpeg = audioData =>
284
257
  new Promise(resolve => {
285
258
  let child
@@ -293,8 +266,8 @@ const decodeChannel0WithFfmpeg = audioData =>
293
266
  child.kill('SIGKILL')
294
267
  resolve(undefined)
295
268
  }, 60000)
296
- child.on('error', () => resolve(undefined)) // ENOENT: ffmpeg not installed
297
- child.stdin.on('error', () => {}) // ffmpeg may close its input early (EPIPE)
269
+ child.on('error', () => resolve(undefined))
270
+ child.stdin.on('error', () => {})
298
271
  child.stdout.on('data', c => out.push(c))
299
272
  child.on('close', code => {
300
273
  clearTimeout(timer)
@@ -307,11 +280,6 @@ const decodeChannel0WithFfmpeg = audioData =>
307
280
  child.stdin.end(audioData)
308
281
  })
309
282
 
310
- /**
311
- * 64-value voice-note waveform (0..100). WAV and FLAC are decoded by the built-in decoder; other formats need the
312
- * system `ffmpeg` binary. Without either, resolves `undefined` (the voice note is still sent, just without a waveform).
313
- * referenced from and modifying https://github.com/wppconnect-team/wa-js/blob/main/src/chat/functions/prepareAudioWaveform.ts
314
- */
315
283
  export async function getAudioWaveform(buffer, logger) {
316
284
  try {
317
285
  let audioData
@@ -355,7 +323,6 @@ export const getStream = async (item, opts) => {
355
323
  return { stream: createReadStream(item.url), type: 'file' }
356
324
  }
357
325
 
358
- /** generates a thumbnail for a given media, if required */
359
326
  export async function generateThumbnail(file, mediaType, options) {
360
327
  let thumbnail
361
328
  let originalImageDimensions
@@ -426,7 +393,7 @@ export const encryptedStream = async (media, mediaType, { logger, saveOriginalFi
426
393
  encFileWriteStream.end()
427
394
  originalFileStream?.end?.()
428
395
  stream.destroy()
429
- // Wait for write streams to fully flush to disk (reduces memory pressure).
396
+
430
397
  await encFinishPromise
431
398
  await originalFinishPromise
432
399
  logger?.debug('encrypted data successfully')
@@ -465,7 +432,7 @@ const extractHost = url => {
465
432
  }
466
433
 
467
434
  export const downloadContentFromMessage = async ({ mediaKey, directPath, url }, type, opts = {}) => {
468
- // Fallback host: explicit opt > host parsed from `url` > DEF_MEDIA_HOST.
435
+
469
436
  const fallbackHost = opts.host ?? extractHost(url)
470
437
  const downloadUrl = directPath ? getUrlFromDirectPath(directPath, fallbackHost) : url
471
438
  if (!downloadUrl) throw new Boom('No valid media URL or directPath present in message', { statusCode: 400 })
@@ -473,7 +440,6 @@ export const downloadContentFromMessage = async ({ mediaKey, directPath, url },
473
440
  return downloadEncryptedContent(downloadUrl, keys, opts)
474
441
  }
475
442
 
476
- /** Decrypts and downloads an AES256-CBC encrypted file; the plaintext's SHA256 is appended to the ciphertext. */
477
443
  export const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, { startByte, endByte, options } = {}) => {
478
444
  let bytesFetched = 0
479
445
  let startChunk = 0
@@ -524,7 +490,7 @@ export const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, {
524
490
  data = data.slice(AES_CHUNK_SIZE)
525
491
  }
526
492
  aes = Crypto.createDecipheriv('aes-256-cbc', cipherKey, ivValue)
527
- if (endByte) aes.setAutoPadding(false) // avoid PKCS7 errors when trimming to a byte range
493
+ if (endByte) aes.setAutoPadding(false)
528
494
  }
529
495
  try {
530
496
  pushBytes(aes.update(data), b => this.push(b))
@@ -542,10 +508,7 @@ export const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, {
542
508
  }
543
509
  }
544
510
  })
545
- // pipe() does not forward 'error' events from source to destination -- without this,
546
- // a dropped connection or malformed response on `fetched` crashes the process
547
- // (unhandled 'error' on the source) instead of surfacing as an error on the
548
- // returned stream that callers can catch.
511
+
549
512
  fetched.on('error', err => output.destroy(err))
550
513
  return fetched.pipe(output, { end: true })
551
514
  }
@@ -569,7 +532,7 @@ export const uploadWithNodeHttp = async ({ url, filePath, headers, timeoutMs, ag
569
532
  if (redirectCount > 5) throw new Error('Too many redirects')
570
533
  const parsedUrl = new URL(url)
571
534
  const httpModule = parsedUrl.protocol === 'https:' ? await import('node:https') : await import('node:http')
572
- const fileStats = await fs.stat(filePath) // Content-Length is required for Node.js streaming
535
+ const fileStats = await fs.stat(filePath)
573
536
  const fileSize = fileStats.size
574
537
  return new Promise((resolve, reject) => {
575
538
  const req = httpModule.request(
@@ -584,7 +547,7 @@ export const uploadWithNodeHttp = async ({ url, filePath, headers, timeoutMs, ag
584
547
  },
585
548
  res => {
586
549
  if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
587
- res.resume() // consume response to free resources
550
+ res.resume()
588
551
  const newUrl = new URL(res.headers.location, url).toString()
589
552
  resolve(uploadWithNodeHttp({ url: newUrl, filePath, headers, timeoutMs, agent }, redirectCount + 1))
590
553
  return
@@ -617,7 +580,7 @@ export const uploadWithNodeHttp = async ({ url, filePath, headers, timeoutMs, ag
617
580
  const uploadWithFetch = async ({ url, filePath, headers, timeoutMs, agent }) => {
618
581
  const nodeStream = createReadStream(filePath)
619
582
  const webStream = Readable.toWeb(nodeStream)
620
- // Native fetch only accepts Undici-style dispatchers, not generic https Agents.
583
+
621
584
  const dispatcher = typeof agent?.dispatch === 'function' ? agent : undefined
622
585
  const response = await fetch(url, {
623
586
  ...(dispatcher ? { dispatcher } : {}),
@@ -634,14 +597,6 @@ const uploadWithFetch = async ({ url, filePath, headers, timeoutMs, agent }) =>
634
597
  }
635
598
  }
636
599
 
637
- /**
638
- * Uploads media to WhatsApp servers.
639
- *
640
- * Two implementations: Node's native `fetch` (undici) buffers the whole request body in
641
- * memory even when streaming, causing high memory use on large files
642
- * (see https://github.com/nodejs/undici/issues/4058) — so on Node we use `node:http(s)`
643
- * directly. Other runtimes (Bun, Deno, browsers) stream correctly, so they use fetch.
644
- */
645
600
  const uploadMedia = async (params, logger) => {
646
601
  if (isNodeRuntime()) {
647
602
  logger?.debug('Using Node.js https module for upload (avoids undici buffering bug)')
@@ -701,7 +656,6 @@ export const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, opt
701
656
 
702
657
  const getMediaRetryKey = mediaKey => hkdf(mediaKey, 32, { info: 'WhatsApp Media Retry Notification' })
703
658
 
704
- /** Generate a binary node that will request the phone to re-upload the media & return the newly uploaded URL */
705
659
  export const encryptMediaRetryRequest = (key, mediaKey, meId) => {
706
660
  const recp = { stanzaId: key.id }
707
661
  const recpBuffer = proto.ServerErrorReceipt.encode(recp).finish()
@@ -712,8 +666,7 @@ export const encryptMediaRetryRequest = (key, mediaKey, meId) => {
712
666
  tag: 'receipt',
713
667
  attrs: { id: key.id, to: jidNormalizedUser(meId), type: 'server-error' },
714
668
  content: [
715
- // this encrypt node is actually pretty useless — media returns even without it —
716
- // kept here to maintain parity with WA Web
669
+
717
670
  {
718
671
  tag: 'encrypt',
719
672
  attrs: {},
@@ -765,22 +718,13 @@ const MEDIA_RETRY_STATUS_MAP = {
765
718
  }
766
719
  export const getStatusCodeForMediaRetry = code => MEDIA_RETRY_STATUS_MAP[code]
767
720
 
768
- /* ------------------------------------------------------------------ */
769
- /* Link preview */
770
- /* ------------------------------------------------------------------ */
771
-
772
721
  const THUMBNAIL_WIDTH_PX = 192
773
722
 
774
- /** Fetches an image and generates a thumbnail for it */
775
723
  const getCompressedJpegThumbnail = async (url, { thumbnailWidth, fetchOpts }) => {
776
724
  const stream = await getHttpStream(url, fetchOpts)
777
725
  return extractImageThumb(stream, thumbnailWidth)
778
726
  }
779
727
 
780
- /**
781
- * Given a piece of text, checks for any URL present, generates link preview for the same and returns it.
782
- * Returns undefined if the fetch failed or no URL was found.
783
- */
784
728
  export const getUrlInfo = async (text, opts = { thumbnailWidth: THUMBNAIL_WIDTH_PX, fetchOpts: { timeout: 3000 } }) => {
785
729
  try {
786
730
  let retries = 0
@@ -818,7 +762,7 @@ export const getUrlInfo = async (text, opts = { thumbnailWidth: THUMBNAIL_WIDTH_
818
762
  originalThumbnailUrl: image
819
763
  }
820
764
  if (opts.uploadImage) {
821
- // imported lazily to avoid a hard circular dependency with the message-composition module
765
+
822
766
  const { prepareWAMessageMedia } = await import('./message-compose.js')
823
767
  const { imageMessage } = await prepareWAMessageMedia(
824
768
  { image: { url: image } },