@oxidezap/baileyrs 0.3.6 → 0.3.8

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 (130) hide show
  1. package/README.md +67 -8
  2. package/lib/Bridge/history-sync-wire.d.ts +2 -2
  3. package/lib/Bridge/history-sync-wire.js +4 -4
  4. package/lib/Bridge/schema.js +7 -1
  5. package/lib/Bridge/types.d.ts +7 -1
  6. package/lib/Compatibility/auth-state.d.ts +30 -0
  7. package/lib/Compatibility/auth-state.js +96 -0
  8. package/lib/Compatibility/encode-proto-core.d.ts +31 -0
  9. package/lib/Compatibility/encode-proto-core.js +51 -0
  10. package/lib/Compatibility/encode-proto.d.ts +0 -19
  11. package/lib/Compatibility/encode-proto.js +3 -35
  12. package/lib/Compatibility/host-auth-state.d.ts +6 -0
  13. package/lib/Compatibility/host-auth-state.js +162 -0
  14. package/lib/Compatibility/internal/auth-state.d.ts +3 -7
  15. package/lib/Compatibility/internal/auth-state.js +34 -1
  16. package/lib/Compatibility/internal/host-auth-state.d.ts +4 -0
  17. package/lib/Compatibility/internal/host-auth-state.js +14 -0
  18. package/lib/Compatibility/legacy-store/device.js +5 -5
  19. package/lib/Compatibility/message-ids.d.ts +17 -0
  20. package/lib/Compatibility/message-ids.js +47 -0
  21. package/lib/Compatibility/message-relay.d.ts +2 -2
  22. package/lib/Compatibility/message-relay.js +4 -4
  23. package/lib/Compatibility/proto-runtime.d.ts +5 -0
  24. package/lib/Compatibility/proto-runtime.js +214 -32
  25. package/lib/Compatibility/socket-results.d.ts +1 -1
  26. package/lib/Compatibility/tagged-message-waiter.d.ts +5 -2
  27. package/lib/Compatibility/tagged-message-waiter.js +5 -5
  28. package/lib/Compatibility/usync/adapter.d.ts +1 -1
  29. package/lib/Compatibility/websocket-client.d.ts +11 -3
  30. package/lib/Compatibility/websocket-client.js +84 -11
  31. package/lib/Defaults/index.d.ts +8 -8
  32. package/lib/Defaults/index.js +8 -8
  33. package/lib/Media/content.d.ts +28 -0
  34. package/lib/Media/content.js +129 -0
  35. package/lib/Media/core.d.ts +34 -0
  36. package/lib/Media/core.js +120 -0
  37. package/lib/Media/mutations.d.ts +24 -0
  38. package/lib/Media/mutations.js +38 -0
  39. package/lib/Runtime/aes-gcm.d.ts +4 -0
  40. package/lib/Runtime/aes-gcm.js +11 -0
  41. package/lib/Runtime/bridge.d.ts +44 -0
  42. package/lib/Runtime/bridge.js +76 -0
  43. package/lib/Runtime/buffer.d.ts +9 -0
  44. package/lib/Runtime/buffer.js +22 -0
  45. package/lib/Runtime/bytes.d.ts +61 -0
  46. package/lib/Runtime/bytes.js +270 -0
  47. package/lib/Runtime/host.d.ts +22 -0
  48. package/lib/Runtime/host.js +43 -0
  49. package/lib/Runtime/long.d.ts +33 -0
  50. package/lib/Runtime/long.js +64 -0
  51. package/lib/Runtime/node-media-processors.d.ts +4 -0
  52. package/lib/Runtime/node-media-processors.js +29 -0
  53. package/lib/Runtime/node-media.d.ts +28 -0
  54. package/lib/Runtime/node-media.js +115 -0
  55. package/lib/Runtime/node.d.ts +14 -0
  56. package/lib/Runtime/node.js +81 -0
  57. package/lib/Runtime/paths.d.ts +4 -0
  58. package/lib/Runtime/paths.js +7 -0
  59. package/lib/Runtime/stream.d.ts +11 -0
  60. package/lib/Runtime/stream.js +25 -0
  61. package/lib/Runtime/types.d.ts +98 -0
  62. package/lib/Runtime/types.js +13 -0
  63. package/lib/Socket/core.d.ts +312 -0
  64. package/lib/Socket/core.js +1122 -0
  65. package/lib/Socket/events-core.d.ts +75 -0
  66. package/lib/Socket/events-core.js +1058 -0
  67. package/lib/Socket/events.d.ts +1 -63
  68. package/lib/Socket/events.js +4 -1047
  69. package/lib/Socket/groups.js +4 -3
  70. package/lib/Socket/index.d.ts +521 -103
  71. package/lib/Socket/index.js +10 -1007
  72. package/lib/Socket/messages-core.d.ts +41 -0
  73. package/lib/Socket/messages-core.js +270 -0
  74. package/lib/Socket/messages.d.ts +9 -36
  75. package/lib/Socket/messages.js +3 -260
  76. package/lib/Socket/newsletter.js +3 -3
  77. package/lib/Socket/profile.js +1 -1
  78. package/lib/Socket/terminal-close-reporter.d.ts +2 -0
  79. package/lib/Socket/terminal-close-reporter.js +3 -3
  80. package/lib/Socket/transport.d.ts +2 -0
  81. package/lib/Socket/transport.js +16 -1
  82. package/lib/Socket/types.d.ts +2 -0
  83. package/lib/Types/Auth.d.ts +11 -0
  84. package/lib/Types/Message.d.ts +1 -1
  85. package/lib/Types/Socket.d.ts +2 -2
  86. package/lib/Types/index.d.ts +6 -1
  87. package/lib/Utils/browser-utils.d.ts +4 -0
  88. package/lib/Utils/browser-utils.js +53 -2
  89. package/lib/Utils/crypto.d.ts +1 -0
  90. package/lib/Utils/crypto.js +1 -0
  91. package/lib/Utils/event-buffer.d.ts +6 -1
  92. package/lib/Utils/event-buffer.js +28 -27
  93. package/lib/Utils/link-preview.d.ts +4 -3
  94. package/lib/Utils/logger.d.ts +3 -0
  95. package/lib/Utils/logger.js +35 -6
  96. package/lib/Utils/messages-core.d.ts +174 -0
  97. package/lib/Utils/messages-core.js +1042 -0
  98. package/lib/Utils/messages-media-core.d.ts +73 -0
  99. package/lib/Utils/messages-media-core.js +319 -0
  100. package/lib/Utils/messages-media.d.ts +1 -72
  101. package/lib/Utils/messages-media.js +9 -358
  102. package/lib/Utils/messages.d.ts +1 -166
  103. package/lib/Utils/messages.js +7 -1040
  104. package/lib/Utils/optional-peer.js +14 -5
  105. package/lib/Utils/process-history-message-core.d.ts +36 -0
  106. package/lib/Utils/process-history-message-core.js +187 -0
  107. package/lib/Utils/process-history-message.d.ts +5 -43
  108. package/lib/Utils/process-history-message.js +11 -197
  109. package/lib/Utils/process-message-core.d.ts +29 -0
  110. package/lib/Utils/process-message-core.js +112 -0
  111. package/lib/Utils/process-message.d.ts +4 -24
  112. package/lib/Utils/process-message.js +6 -111
  113. package/lib/WABinary/generic-utils.js +7 -5
  114. package/lib/host-shared.d.ts +74 -0
  115. package/lib/host-shared.js +15 -0
  116. package/lib/host-socket-operations.d.ts +3 -0
  117. package/lib/host-socket-operations.js +2 -0
  118. package/lib/host-surface.d.ts +21 -0
  119. package/lib/host-surface.js +35 -0
  120. package/lib/host-types.d.ts +356 -0
  121. package/lib/host-types.js +2 -0
  122. package/lib/host.d.ts +33 -0
  123. package/lib/host.js +31 -0
  124. package/lib/node-surface.d.ts +9 -0
  125. package/lib/node-surface.js +15 -0
  126. package/lib/surface.d.ts +5 -0
  127. package/lib/surface.js +6 -0
  128. package/lib/wasm.d.ts +27 -0
  129. package/lib/wasm.js +27 -0
  130. package/package.json +18 -6
@@ -0,0 +1,1122 @@
1
+ import { base64UrlEncode, unrefTimer } from '../Runtime/bytes.js';
2
+ import { encodeProtoCompat as encodeProtoCompatCore } from '../Compatibility/encode-proto-core.js';
3
+ import { normalizeHostAuthenticationState } from '../Compatibility/internal/host-auth-state.js';
4
+ import { hydrateHostAuthCreds } from '../Compatibility/host-auth-state.js';
5
+ import { makeHistoryRuntime } from '../Runtime/bridge.js';
6
+ import { makeMutex } from '../Compatibility/internal/make-mutex.js';
7
+ import { isNativeMemoryStore } from '../Compatibility/internal/native-memory-store.js';
8
+ import { toBridgeMediaType } from '../Compatibility/media-type.js';
9
+ import { bindSignalRepositoryContext, makeDefaultSignalRepository } from '../Compatibility/signal-repository.js';
10
+ import { bridgeBusinessProfileToBaileys } from '../Compatibility/socket-results.js';
11
+ import { makeStanzaResponseMethods } from '../Compatibility/stanza-responses.js';
12
+ import { makeParticipatingRefreshHandler } from '../Compatibility/participating-refresh.js';
13
+ import { makeTaggedMessageWaiter } from '../Compatibility/tagged-message-waiter.js';
14
+ import { isRawNodeForwardingEnabled, WebSocketClient } from '../Compatibility/websocket-client.js';
15
+ import { DEFAULT_CONNECTION_CONFIG, MEDIA_TYPES } from '../Defaults/index.js';
16
+ import { DisconnectReason, WA_PRESENCES } from '../Types/index.js';
17
+ import { assertArgumentDomain } from '../Utils/argument-domain.js';
18
+ import { Boom } from '../Utils/boom.js';
19
+ import { makeEventBuffer } from '../Utils/event-buffer.js';
20
+ import { _registerActiveBridgeClient, _unregisterActiveBridgeClient, downloadMediaMessage, MEDIA_DOWNLOAD_TYPES } from '../Utils/messages-core.js';
21
+ import { makeHistorySyncAdmission, resolveHistorySyncPolicy, isHistorySyncFullyDisabled } from '../Compatibility/history-sync-admission.js';
22
+ import { assertNodeErrorFree } from '../WABinary/generic-utils.js';
23
+ import { makeBlockingMethods } from './blocking.js';
24
+ import { makeBusinessMethods } from './business.js';
25
+ import { makeChatActionMethods } from './chat-actions.js';
26
+ import { makeContactMethods } from './contacts.js';
27
+ import { makeCommunityMethods } from './communities.js';
28
+ import { makeBridgeClientOwner } from './bridge-client-owner.js';
29
+ import { warnUnsupportedConfig } from './unsupported-config.js';
30
+ import { wrapBridgeClient } from './bridge-error-boundary.js';
31
+ import { makeTerminalCloseReporter } from './terminal-close-reporter.js';
32
+ import { mapConnectFailureToDisconnect } from './terminal-close.js';
33
+ import { makeEventHandlers } from './events-core.js';
34
+ import { makeGroupMethods } from './groups.js';
35
+ import { makeInternalMethods, makeUnexpectedErrorReporter } from './internals.js';
36
+ import { makeMessageMethodsCore } from './messages-core.js';
37
+ import { makeNewsletterMethods } from './newsletter.js';
38
+ import { makePreKeyMethods } from './prekeys.js';
39
+ import { makePresenceMethods } from './presence.js';
40
+ import { makePrivacyMethods } from './privacy.js';
41
+ import { makeServerQueryMethods } from './server-queries.js';
42
+ import { makeProfileMethods } from './profile.js';
43
+ import { mapReachoutTimelock } from './reachout.js';
44
+ import { makeHttpClient, makeTransport } from './transport.js';
45
+ import { makeWithClient } from './client-operations.js';
46
+ import { makeUSyncMethods } from './usync.js';
47
+ import { createRuntimeLogger } from '../Utils/logger.js';
48
+ /**
49
+ * Default mapping for the legacy `browser[1]` slot — preserved so users on the
50
+ * existing `Browsers.macOS('Chrome')` style get the same `DeviceProps.platformType`
51
+ * they always got. Anything outside this set falls back to `CHROME` (matching
52
+ * the prior bridge behavior). Override with the explicit `deviceProps` config.
53
+ */
54
+ const browserToPlatformType = (browser) => {
55
+ switch (browser) {
56
+ case 'Chrome':
57
+ return 'CHROME';
58
+ case 'Firefox':
59
+ return 'FIREFOX';
60
+ case 'Safari':
61
+ return 'SAFARI';
62
+ case 'Edge':
63
+ return 'EDGE';
64
+ case 'Opera':
65
+ return 'OPERA';
66
+ case 'Desktop':
67
+ return 'DESKTOP';
68
+ case 'Android':
69
+ return 'ANDROID_PHONE';
70
+ default:
71
+ return 'CHROME';
72
+ }
73
+ };
74
+ const COMPLETION_FAILURE_CODES = new Map([
75
+ ['Generic', 400],
76
+ ['LoggedOut', 401],
77
+ ['TempBanned', 402],
78
+ ['AccountLocked', 403],
79
+ ['UnknownLogout', 406],
80
+ ['ClientOutdated', 405],
81
+ ['BadUserAgent', 409],
82
+ ['CatExpired', 413],
83
+ ['CatInvalid', 414],
84
+ ['NotFound', 415],
85
+ ['ClientUnknown', 418],
86
+ ['InternalServerError', 500],
87
+ ['Experimental', 501],
88
+ ['ServiceUnavailable', 503]
89
+ ]);
90
+ const completionFailureCode = (reason) => {
91
+ const named = COMPLETION_FAILURE_CODES.get(reason);
92
+ if (named !== undefined)
93
+ return named;
94
+ const unknown = /^Unknown\((-?\d+)\)$/.exec(reason)?.[1];
95
+ return unknown === undefined ? undefined : Number(unknown);
96
+ };
97
+ /** Build the ws EventEmitter with auto-enable raw node forwarding */
98
+ export const createWASocketFactory = (runtime) => {
99
+ const runtimeLogger = createRuntimeLogger((line, delivered) => runtime.loggerSink(line, delivered), runtime.logLevel());
100
+ let engineInitialized = false;
101
+ return (config) => createWASocketFactoryInner(runtime, config, () => {
102
+ if (engineInitialized)
103
+ return false;
104
+ engineInitialized = true;
105
+ return true;
106
+ }, () => {
107
+ engineInitialized = false;
108
+ }, runtimeLogger);
109
+ };
110
+ const createWASocketFactoryInner = (runtime, config, claimEngineInitialization, resetEngineInitialization, runtimeLogger) => {
111
+ const platform = config.browser === undefined ? runtime.platformInfo?.() : undefined;
112
+ const mergedConfig = {
113
+ ...DEFAULT_CONNECTION_CONFIG,
114
+ ...config,
115
+ ...(platform ? { browser: [platform.os, 'Chrome', platform.release] } : {}),
116
+ logger: config.logger ?? runtime.defaultLogger ?? runtimeLogger
117
+ };
118
+ const { logger } = mergedConfig;
119
+ // Against `config`, not `fullConfig`: only what this caller actually passed
120
+ // is worth naming. Merging the defaults first would report every unsupported
121
+ // option on every socket, including the ones nobody chose.
122
+ warnUnsupportedConfig(config, logger);
123
+ // `Partial<SocketConfig>` lets an explicit `undefined` overwrite the default
124
+ // in the shallow merge above; resolve against the raw config so the socket
125
+ // keeps the default policy instead of throwing on the first notification.
126
+ const shouldSyncHistoryMessage = resolveHistorySyncPolicy(config.shouldSyncHistoryMessage);
127
+ if (isHistorySyncFullyDisabled(shouldSyncHistoryMessage)) {
128
+ logger.warn('⚠️ DANGER: DISABLING ALL SYNC BY shouldSyncHistoryMsg PREVENTS BAILEYS FROM ACCESSING INITIAL LID MAPPINGS, LEADING TO INSTABILIY AND SESSION ERRORS');
129
+ }
130
+ const auth = (runtime.normalizeAuth ?? normalizeHostAuthenticationState)(mergedConfig.auth);
131
+ const fullConfig = { ...mergedConfig, auth };
132
+ const getExposedKeys = runtime.makeTransactionKeyStore
133
+ ? runtime.makeTransactionKeyStore(auth.keys, logger, fullConfig.transactionOpts)
134
+ : () => auth.keys;
135
+ const ev = makeEventBuffer(logger, {
136
+ setTimeout: runtime.setTimeout,
137
+ clearTimeout: runtime.clearTimeout
138
+ }, runtime.events.createEmitter());
139
+ // Upstream mutates authState.creds before notifying user listeners. Register
140
+ // this first so `ev.on('creds.update', saveCreds)` persists the merged state
141
+ // rather than the pre-pair placeholder.
142
+ ev.on('creds.update', update => Object.assign(auth.creds, update));
143
+ let user;
144
+ /** True once `init()` has finished wiring the client and started its read loop. */
145
+ let initialized = false;
146
+ /** True while the socket's end handlers run — see `end`. */
147
+ let runningEndHandlers = false;
148
+ /**
149
+ * Consumer teardown hooks, plus the socket's own. Declared here rather than
150
+ * beside their registrations so the owner below can close over the list
151
+ * before anything fills it.
152
+ */
153
+ const socketEndHandlers = [];
154
+ /**
155
+ * Drain both auth stores, returning the FIRST failure rather than throwing
156
+ * so the caller can finish the rest of its work and still report it.
157
+ *
158
+ * Called through their owners on purpose: collecting the two methods into
159
+ * an array and invoking them bare drops the receiver, so a consumer store
160
+ * whose `flush()` touches `this` throws on `undefined` and the teardown
161
+ * publishes a close with the auth writes unpersisted.
162
+ */
163
+ const flushStores = async () => {
164
+ let firstError;
165
+ try {
166
+ await auth.store?.flush?.();
167
+ }
168
+ catch (e) {
169
+ firstError ?? (firstError = e);
170
+ }
171
+ try {
172
+ await autoWrappedStore?.flush?.();
173
+ }
174
+ catch (e) {
175
+ firstError ?? (firstError = e);
176
+ }
177
+ return firstError;
178
+ };
179
+ /**
180
+ * Single home for the bridge client's lifetime. `ws` below reads the current
181
+ * client from it, and this teardown closes `ws` — the cycle is fine because
182
+ * both directions only run once the socket is live.
183
+ */
184
+ const owner = makeBridgeClientOwner({
185
+ logger,
186
+ /**
187
+ * Everything the socket owns beyond the client itself. Runs once, with
188
+ * the client still usable, whether or not one was ever adopted — a
189
+ * teardown that landed mid-init still has a transport to close and a
190
+ * store to drain.
191
+ */
192
+ teardown: async (client, error) => {
193
+ try {
194
+ await ws.close();
195
+ }
196
+ catch {
197
+ // The transport refused to close cleanly. Go straight at the
198
+ // client so the disconnect still happens *before* the barrier
199
+ // and flush below: `release` retries it, but that runs after the
200
+ // flush, and the closing-session ratchet writes a disconnect
201
+ // enqueues would then have nothing left to persist them.
202
+ try {
203
+ await client?.disconnect();
204
+ }
205
+ catch {
206
+ /* ignore */
207
+ }
208
+ }
209
+ if (client) {
210
+ // Barrier: bridge cleanup paths fired during `disconnect()` may
211
+ // emit `set()` calls that are still queued as microtasks /
212
+ // `setImmediate` callbacks at this point. Two yields to the
213
+ // event loop drain (1) the microtask queue and (2) the next
214
+ // macrotask tick where wasm-bindgen async callbacks land.
215
+ // Without this barrier the flushes below run before the bridge
216
+ // has finished writing — a race that loses the last few sets
217
+ // (typically the closing-session ratchet step).
218
+ await new Promise(resolve => {
219
+ if (runtime.setImmediate)
220
+ runtime.setImmediate(() => resolve());
221
+ else
222
+ runtime.setTimeout(() => resolve(), 0);
223
+ });
224
+ await new Promise(resolve => {
225
+ if (runtime.setImmediate)
226
+ runtime.setImmediate(() => resolve());
227
+ else
228
+ runtime.setTimeout(() => resolve(), 0);
229
+ });
230
+ }
231
+ const firstFlushError = await flushStores();
232
+ // End handlers run before the flush error is rethrown: they are the
233
+ // consumer's teardown hook, and a corrupt-on-shutdown auth store is
234
+ // exactly when they most need to run.
235
+ //
236
+ // The flag makes a re-entrant `end()` from inside one of them a
237
+ // no-op instead of a deadlock: shared cleanup used both directly and
238
+ // as an end hook would otherwise be handed the very promise that is
239
+ // waiting for it to return, and nothing would ever settle — no
240
+ // release, and no terminal close until the watchdog.
241
+ runningEndHandlers = true;
242
+ try {
243
+ for (const handler of socketEndHandlers) {
244
+ try {
245
+ await handler(error);
246
+ }
247
+ catch (handlerError) {
248
+ logger.error({ err: handlerError }, 'error in socket end handler');
249
+ }
250
+ }
251
+ }
252
+ finally {
253
+ runningEndHandlers = false;
254
+ }
255
+ if (firstFlushError)
256
+ throw firstFlushError;
257
+ },
258
+ release: async (client) => {
259
+ // `disconnect()` before `free()` drains exactly one shape: a
260
+ // `disconnect()` still in flight. Since bridge 0.21.1, freeing
261
+ // with ordinary calls pending (`fetchBlocklist()`, `logout()`) is
262
+ // safe — its `Drop` signals shutdown and aborts the background
263
+ // tasks — but freeing mid-`disconnect()` still aborts the process
264
+ // (recursively acquiring the teardown mutex). See
265
+ // `__tests__/bridge-free-safety.test.ts`.
266
+ //
267
+ // That shape is reachable: `WebSocketClient.close()` early-returns
268
+ // when `closing`/`closed` is already set without awaiting the
269
+ // disconnect it skipped, so `void sock.ws.close(); await sock.end()`
270
+ // could otherwise reach `free()` with the first disconnect still
271
+ // running. Awaiting it here is the belt to `ws.close()`'s braces.
272
+ let disconnected = true;
273
+ try {
274
+ await client.disconnect();
275
+ }
276
+ catch {
277
+ disconnected = false;
278
+ }
279
+ // Disconnect may schedule the final store callback on later ticks;
280
+ // drain those callbacks before the last durability flush.
281
+ if (disconnected) {
282
+ await new Promise(resolve => {
283
+ if (runtime.setImmediate)
284
+ runtime.setImmediate(() => resolve());
285
+ else
286
+ runtime.setTimeout(() => resolve(), 0);
287
+ });
288
+ await new Promise(resolve => {
289
+ if (runtime.setImmediate)
290
+ runtime.setImmediate(() => resolve());
291
+ else
292
+ runtime.setTimeout(() => resolve(), 0);
293
+ });
294
+ }
295
+ // Teardown already flushed, but only after its own disconnect
296
+ // attempts. If those all failed and this one succeeded, the
297
+ // closing-session ratchet writes it enqueues arrived after that
298
+ // flush — with nothing left to persist them. Cheap enough to just
299
+ // drain again.
300
+ if (disconnected) {
301
+ const lateFlushError = await flushStores();
302
+ if (lateFlushError)
303
+ logger.error({ err: lateFlushError }, 'failed to flush after the final disconnect');
304
+ }
305
+ // Unregister before freeing: `free()` is swallowed, so ordering it
306
+ // last would leave the module-level pointer aimed at a client that is
307
+ // already gone if anything between them threw.
308
+ _unregisterActiveBridgeClient(wrapBridgeClient(client));
309
+ try {
310
+ client.free();
311
+ }
312
+ catch {
313
+ /* ignore */
314
+ }
315
+ }
316
+ });
317
+ const ws = new WebSocketClient(fullConfig.waWebSocketUrl, fullConfig, () => owner.peek(), runtime.events.createEmitter());
318
+ let tagEpoch = 0;
319
+ // Per-socket random prefix avoids collisions between sockets created
320
+ // in the same millisecond. Date.now()-based prefixes (the previous
321
+ // implementation) collided in test loops and worker pools — every
322
+ // socket started at `tagEpoch=0` and a tagged message-id collision
323
+ // breaks waitForMessage routing.
324
+ const tagPrefix = `${base64UrlEncode(runtime.randomBytes(6))}.`;
325
+ const generateMessageTag = () => `${tagPrefix}${tagEpoch++}`;
326
+ let pairedAccount;
327
+ let cachedAccount;
328
+ // Holds the wrapped store created when the user passed legacy
329
+ // `auth: { creds, keys }` instead of `auth.store`. We need it in
330
+ // `end()` to drain the debounced `saveCreds` timer — `auth.store?.flush?.()`
331
+ // covers the explicit-store path but not this one.
332
+ let autoWrappedStore;
333
+ // Mirrors the engine's `enable_auto_reconnect`, which defaults to on. Only
334
+ // `sock.setAutoReconnect()` moves it, and the dispatcher reads it to tell a
335
+ // transient drop from a terminal one.
336
+ let autoReconnectEnabled = true;
337
+ /** Owns reporting the terminal close: once, after teardown, never not at all. */
338
+ const terminalClose = makeTerminalCloseReporter({
339
+ logger,
340
+ setTimeout: runtime.setTimeout,
341
+ clearTimeout: runtime.clearTimeout
342
+ });
343
+ const runCompletionError = (completion) => {
344
+ let statusCode = DisconnectReason.connectionClosed;
345
+ let message = 'Connection closed';
346
+ if (completion.reason === 'unknown') {
347
+ message = `Connection run ended: ${completion.detail}`;
348
+ }
349
+ else if (completion.reason === 'stopped') {
350
+ message = 'Connection run stopped';
351
+ }
352
+ else if (completion.reason === 'already-running') {
353
+ message = 'Connection run was already running';
354
+ }
355
+ else if (completion.reason === 'auto-reconnect-disabled') {
356
+ const protocol = completion.protocolError;
357
+ if (protocol?.kind === 'conflict') {
358
+ statusCode = DisconnectReason.connectionReplaced;
359
+ message = 'Connection replaced';
360
+ }
361
+ else if (protocol?.kind === 'stream-error') {
362
+ statusCode = mapConnectFailureToDisconnect(protocol.code);
363
+ }
364
+ else if (protocol?.kind === 'connect-failure') {
365
+ statusCode = mapConnectFailureToDisconnect(completionFailureCode(protocol.reason));
366
+ }
367
+ else if (completion.connection?.kind === 'server-close') {
368
+ message = completion.connection.reason;
369
+ }
370
+ }
371
+ return new Boom(message, { statusCode, data: { runCompletion: completion } });
372
+ };
373
+ const reportTerminalClose = (error, publish) => terminalClose.reportAfter(() => owner.close(error).finally(() => initPromise), publish);
374
+ /**
375
+ * Held in a reporter rather than captured, because `sock.onUnexpectedError`
376
+ * is an assignable property: a consumer that replaces it has to be the one
377
+ * the socket's own failure paths reach afterwards.
378
+ */
379
+ const unexpectedErrors = makeUnexpectedErrorReporter(logger);
380
+ const ctx = {
381
+ ev,
382
+ logger,
383
+ fullConfig,
384
+ encodeProto: (path, message) => encodeProtoCompatCore(path, message, runtime.bridge.encodeProto.bind(runtime.bridge)),
385
+ randomBytes: runtime.randomBytes,
386
+ ws,
387
+ reportUnexpectedError: unexpectedErrors.report,
388
+ getUser: () => user,
389
+ getMe: () => {
390
+ const me = auth.creds.me;
391
+ const id = user?.id ?? me?.id;
392
+ if (!id)
393
+ return undefined;
394
+ return { ...me, id, ...(user?.lid ? { lid: user.lid } : {}) };
395
+ },
396
+ setUser: u => {
397
+ user = u;
398
+ },
399
+ withClient: makeWithClient(getClient)
400
+ };
401
+ function getClient() {
402
+ // Teardown retains the client through closing to disconnect the transport.
403
+ // Ordinary operations must stop being admitted when close() is called.
404
+ if (owner.isClosing()) {
405
+ return Promise.reject(new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed }));
406
+ }
407
+ // Otherwise gated on `initialized`, not merely on the client
408
+ // existing. `adopt()` publishes it several awaits before
409
+ // `setDeviceProps`, the account lookups and `run()`, so keying off
410
+ // `peek()` alone would hand ordinary calls like `sendMessage()` a
411
+ // half-built client whose read loop has not started — and skip the
412
+ // `initError` check when startup later fails.
413
+ if (initialized) {
414
+ const ready = owner.peek();
415
+ if (ready)
416
+ return Promise.resolve(wrapBridgeClient(ready));
417
+ }
418
+ return initPromise.then(() => {
419
+ // Closing may have started while initialization was pending.
420
+ // This gate does not track admitted operations. Bridge 0.21.1 tolerates
421
+ // free() during ordinary calls, but not during disconnect(); release
422
+ // still awaits that drain before freeing the client.
423
+ if (owner.isClosing()) {
424
+ throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed });
425
+ }
426
+ if (initError) {
427
+ throw new Boom('Bridge client failed to initialize: ' + initError.message, { statusCode: 500 });
428
+ }
429
+ const built = owner.peek();
430
+ if (!built)
431
+ throw new Boom('Client not initialized', { statusCode: 500 });
432
+ return wrapBridgeClient(built);
433
+ });
434
+ }
435
+ // The native repository delegates Signal state directly to the core and does
436
+ // not need the standalone transaction facade. Keep that facade lazy for the
437
+ // public authState and custom repository contracts that can observe it.
438
+ const signalAuthState = {
439
+ creds: auth.creds,
440
+ keys: fullConfig.makeSignalRepository === makeDefaultSignalRepository ? auth.keys : getExposedKeys()
441
+ };
442
+ bindSignalRepositoryContext(signalAuthState, ctx);
443
+ const signalRepository = fullConfig.makeSignalRepository(signalAuthState, logger);
444
+ const devicesMutex = makeMutex();
445
+ const messageMutex = makeMutex();
446
+ const receiptMutex = makeMutex();
447
+ const appStatePatchMutex = makeMutex();
448
+ const notificationMutex = makeMutex();
449
+ const activeCallContexts = new Map();
450
+ socketEndHandlers.push(() => activeCallContexts.clear());
451
+ const groupMethods = makeGroupMethods(ctx);
452
+ const communityMethods = makeCommunityMethods(ctx, groupMethods);
453
+ const refreshParticipating = makeParticipatingRefreshHandler(ctx, {
454
+ groupFetchAllParticipating: groupMethods.groupFetchAllParticipating,
455
+ communityFetchAllParticipating: communityMethods.communityFetchAllParticipating
456
+ });
457
+ const eventHandlers = makeEventHandlers(ctx, {
458
+ onPairSuccess: data => {
459
+ pairedAccount = data;
460
+ owner
461
+ .peek()
462
+ ?.getAccount?.()
463
+ .then((acc) => {
464
+ cachedAccount = acc ?? undefined;
465
+ })
466
+ .catch(() => { });
467
+ if (auth.store) {
468
+ const refreshAuthState = runtime.refreshAuthState ?? (state => hydrateHostAuthCreds(state.store, state.creds).then(() => undefined));
469
+ void refreshAuthState(auth).then(() => ev.emit('creds.update', auth.creds), error => ctx.reportUnexpectedError(error, 'refreshing credentials after pairing'));
470
+ }
471
+ },
472
+ onIncomingCall: event => {
473
+ const { callId, callCreator, type } = event.action;
474
+ if (type === 'reject' || type === 'accept' || type === 'timeout' || type === 'terminate') {
475
+ activeCallContexts.delete(callId);
476
+ }
477
+ else if (callCreator) {
478
+ activeCallContexts.set(callId, { peer: event.from, callCreator });
479
+ }
480
+ },
481
+ onDirtyState: event => refreshParticipating(event.dirtyType),
482
+ /**
483
+ * The engine has stopped reconnecting, so this client is dead weight
484
+ * that only `free()` reclaims — `run()` returns `void`, so its loop
485
+ * exiting is otherwise invisible from here.
486
+ *
487
+ * Tearing down and reporting are both handed to the reporter: the close
488
+ * has to reach the consumer exactly once and only after this socket has
489
+ * released what it owns, or a replacement built in response overlaps it
490
+ * on the same auth folder.
491
+ */
492
+ onTerminalClose: (error, publish) => {
493
+ // `owner.close()`, not `end()`. `end()` short-circuits when called
494
+ // from inside an end handler — it has to, or the handler awaits the
495
+ // teardown waiting for it — and a terminal event raised from one of
496
+ // those would then publish against an already-resolved promise,
497
+ // letting a close listener build a replacement while the old client
498
+ // is still owned. This waits for the real teardown, and cannot
499
+ // deadlock because `reportAfter` runs it detached; nothing in the
500
+ // teardown is waiting on this.
501
+ reportTerminalClose(error, publish);
502
+ },
503
+ isAutoReconnectEnabled: () => autoReconnectEnabled,
504
+ // Timers the dispatcher armed outlive the events that armed them, and
505
+ // only the terminal-close path clears them. Ending the socket any other
506
+ // way — `sock.end()`, an `await using` scope exiting — has to as well,
507
+ // or one fires from a socket whose client is already freed.
508
+ onCleanup: cleanup => socketEndHandlers.push(cleanup)
509
+ }, {
510
+ ...makeHistoryRuntime(runtime),
511
+ BinaryReader: runtime.bridge.BinaryReader,
512
+ Long: runtime.Long,
513
+ setTimeout: runtime.setTimeout,
514
+ clearTimeout: runtime.clearTimeout
515
+ });
516
+ const init = async () => {
517
+ await runtime.waitForAuthState?.(auth);
518
+ // `initWasmEngine` reads `logger.level` synchronously while installing
519
+ // the Rust-side logger: a consumer logger without the pino shape
520
+ // (notably the throwing test double, which has no `level` at all)
521
+ // throws here, before any socket exists. That throw is inside `init()`,
522
+ // so without this guard it becomes an `initError` and `getClient()`
523
+ // reports "Bridge client failed to initialize" instead of connecting.
524
+ // The engine keeps its previous logger in that case, which is fine:
525
+ // Rust-side log routing is process-global and outlives any one socket.
526
+ // A throwing `logger.error` here would surface as an unhandled
527
+ // rejection on a chain the caller never sees, so the fallback call is
528
+ // guarded too.
529
+ try {
530
+ if (claimEngineInitialization()) {
531
+ const bridgeLogger = typeof logger.level === 'string'
532
+ ? logger
533
+ : {
534
+ level: 'silent',
535
+ trace: () => { },
536
+ debug: () => { },
537
+ info: () => { },
538
+ warn: () => { },
539
+ error: () => { }
540
+ };
541
+ runtime.bridge.initWasmEngine(bridgeLogger, runtime.nativeCrypto);
542
+ }
543
+ }
544
+ catch (err) {
545
+ resetEngineInitialization();
546
+ throw err;
547
+ }
548
+ // Defer to a microtask so callers have a turn to attach listeners
549
+ // after `makeWASocket()` returns. Without this the emit fires
550
+ // synchronously inside `init()` (before the function reaches its
551
+ // first `await`), which is also before the caller ever sees `conn.ev`,
552
+ // so any handler registered via `conn.ev.on('connection.update', …)`
553
+ // or `conn.ev.process(…)` silently misses the initial 'connecting'
554
+ // state. Bots like sung that drive UI off the lifecycle (spinners,
555
+ // reconnection counters) end up tracking a state machine they never
556
+ // got to enter, then crash when the next state ('open' / 'close')
557
+ // references prerequisites that the missed event was supposed to set
558
+ // up.
559
+ runtime.queueMicrotask(() => ev.emit('connection.update', {
560
+ connection: 'connecting',
561
+ receivedPendingNotifications: false,
562
+ qr: undefined
563
+ }));
564
+ // Auto-promote upstream-Baileys-style `auth: { creds, keys }` to a
565
+ // `JsStoreCallbacks`-shaped store via `wrapLegacyStore`. The synthetic
566
+ // `saveCreds` callback re-emits `creds.update` so the bot's existing
567
+ // `ev.on('creds.update', saveCreds)` listener handles persistence —
568
+ // matches the lifecycle hook every upstream-Baileys setup already
569
+ // wires, so migration needs zero changes to the auth block.
570
+ const useNativeMemory = auth.store ? isNativeMemoryStore(auth.store) : false;
571
+ let bridgeStore = useNativeMemory ? null : (auth.store ?? null);
572
+ if (!bridgeStore && !useNativeMemory && auth.creds && auth.keys) {
573
+ if (!runtime.wrapLegacyStore)
574
+ throw new Error('legacy auth requires the Node runtime');
575
+ const legacyState = { creds: auth.creds, keys: auth.keys };
576
+ const wrapped = await runtime.wrapLegacyStore(legacyState, async () => {
577
+ ev.emit('creds.update', auth.creds);
578
+ }, logger);
579
+ bridgeStore = wrapped;
580
+ // Stash on the closure so `end()` can drain the debounced
581
+ // `saveCreds` timer. `auth.store?.flush?.()` only runs when the
582
+ // caller passed an explicit store — this auto-wrap path needs
583
+ // its own hook.
584
+ autoWrappedStore = wrapped;
585
+ logger.debug('auth: auto-wrapped legacy {creds, keys} via wrapLegacyStore');
586
+ }
587
+ if (useNativeMemory)
588
+ logger.debug('auth: using socket-local native memory backend');
589
+ const created = await runtime.bridge.createWhatsAppClient(makeTransport({ ...fullConfig, setTimeout: runtime.setTimeout, clearTimeout: runtime.clearTimeout }), makeHttpClient(fullConfig), eventHandlers, bridgeStore, fullConfig.cache ?? null, fullConfig.version, fullConfig.wantedPreKeyCount ?? null,
590
+ // Passed through exactly as configured, never normalized by truthiness:
591
+ // the bridge only honours a literal `true` here and rejects any
592
+ // other truthy value at construction, so a `!!`/ternary-style
593
+ // coercion could promote a malformed opt-out into an opt-in.
594
+ // Absent stays strict.
595
+ fullConfig.dangerSkipCertChainVerify, makeHistorySyncAdmission(shouldSyncHistoryMessage));
596
+ // `end()` can land while the client is still being built — a `sock.end()`
597
+ // or `await using` right after `makeWASocket()` does exactly that. When
598
+ // it has, `adopt` frees this client and tells us to stop: nothing else
599
+ // would ever own it, and `run()` below would reconnect it forever
600
+ // against a socket the caller already disposed.
601
+ // `adopt` starts releasing the refused client; joining it here keeps
602
+ // that work inside `initPromise`, which `Symbol.asyncDispose` awaits.
603
+ // `adopt` also refuses when `discard()` already reset a half-built
604
+ // client to `starting` (init failure after adopt): the client is being
605
+ // released by that path, and `run()` below would reconnect a freed
606
+ // handle forever, so stop the same way.
607
+ // Bridge 0.23 can finish the constructor before its initial store
608
+ // enumeration has settled. If teardown won the race, wait on a normal
609
+ // client operation before releasing the refused client so that this
610
+ // initialization work cannot outlive async disposal.
611
+ if (owner.isClosing())
612
+ await created.getJid().catch(() => undefined);
613
+ if (!owner.adopt(created))
614
+ return owner.settled();
615
+ // Fallback for standalone helpers like `downloadContentFromMessage`
616
+ // that carry no socket reference. Registered wrapped so those helpers
617
+ // reject with a caller stack too; the memoized wrap keeps the
618
+ // unregister identity check working.
619
+ _registerActiveBridgeClient(wrapBridgeClient(created), logger);
620
+ // Replay a preference set before the client existed. `setAutoReconnect`
621
+ // forwards through `client?.`, so `makeWASocket(cfg).setAutoReconnect(false)`
622
+ // — the idiomatic first line — used to move only the JS mirror and leave
623
+ // the engine retrying.
624
+ if (!autoReconnectEnabled)
625
+ created.setAutoReconnect(false);
626
+ // Everything below talks to `created`, which stays valid for the whole
627
+ // body, and re-checks `isClosing()` between awaits: once teardown has
628
+ // started it owns this client, and issuing more bridge calls against it
629
+ // races the release.
630
+ if (fullConfig.pushName) {
631
+ await created.setInitialPushName(fullConfig.pushName);
632
+ }
633
+ if (owner.isClosing())
634
+ return;
635
+ const [osName, browserName] = fullConfig.browser;
636
+ const deviceOs = browserName === 'Android' ? 'Android' : osName;
637
+ await created.setDeviceProps({
638
+ os: deviceOs,
639
+ platformType: browserToPlatformType(browserName),
640
+ ...fullConfig.deviceProps
641
+ });
642
+ if (owner.isClosing())
643
+ return;
644
+ const [jid, lid, account] = await Promise.all([
645
+ created.getJid(),
646
+ created.getLid(),
647
+ created.getAccount().catch(() => undefined)
648
+ ]);
649
+ if (owner.isClosing())
650
+ return;
651
+ if (jid) {
652
+ user = { id: jid, lid: lid ?? undefined };
653
+ }
654
+ if (account) {
655
+ cachedAccount = account;
656
+ }
657
+ // Android browser slot flips the noise-handshake identity to
658
+ // `UserAgent.platform = ANDROID` (no `web_info`), mirroring upstream
659
+ // Baileys PR #2201. Required for the server to deliver view_once payloads.
660
+ if (browserName === 'Android') {
661
+ await created.setClientProfile({ preset: 'android', osVersion: osName });
662
+ if (owner.isClosing())
663
+ return;
664
+ }
665
+ if (isRawNodeForwardingEnabled(ws)) {
666
+ created.setRawNodeForwarding(true);
667
+ }
668
+ // Same race as above: teardown already owns and releases this client, so
669
+ // starting the read loop now would run against a handle about to go.
670
+ if (owner.isClosing())
671
+ return;
672
+ // `run()` deliberately returns immediately so callers can use the
673
+ // client while supervision owns its background task. Registering the
674
+ // completion observer after it is started is safe: bridge 0.21.0 admits
675
+ // late observers against the stored result for this run generation.
676
+ created.run();
677
+ const observedClient = created;
678
+ void created
679
+ .waitForRunCompletion()
680
+ .then(completion => {
681
+ // The owner identity is the socket generation fence. A completion
682
+ // from a client that teardown already released must never close a
683
+ // later socket using the same auth state.
684
+ if (owner.isClosing() || owner.peek() !== observedClient)
685
+ return;
686
+ const error = runCompletionError(completion);
687
+ reportTerminalClose(error, () => ev.emit('connection.update', {
688
+ connection: 'close',
689
+ lastDisconnect: { error, date: new Date() }
690
+ }));
691
+ }, error => {
692
+ if (owner.isClosing() || owner.peek() !== observedClient)
693
+ return;
694
+ const closeError = new Boom('Connection run ended without a completion result', {
695
+ statusCode: DisconnectReason.connectionClosed
696
+ });
697
+ reportTerminalClose(closeError, () => ev.emit('connection.update', {
698
+ connection: 'close',
699
+ lastDisconnect: { error: closeError, date: new Date() }
700
+ }));
701
+ try {
702
+ logger.error({ err: error }, 'bridge run completion observation failed');
703
+ }
704
+ catch {
705
+ // A consumer logger cannot prevent the terminal cleanup above.
706
+ }
707
+ })
708
+ .catch(() => {
709
+ // The reporter contains teardown and publish failures; this final guard
710
+ // also contains a consumer logger that throws from an observation path.
711
+ });
712
+ initialized = true;
713
+ };
714
+ /**
715
+ * Joins startup too, not just the teardown.
716
+ *
717
+ * `owner.close()` covers the client it can see. A close landing while
718
+ * `createWhatsAppClient()` is still pending sees none — the client arrives
719
+ * afterwards, `adopt()` refuses it, and the release runs detached. Without
720
+ * waiting for `init()` to finish, `await sock.end()` therefore returns while
721
+ * that client is still disconnecting and being freed, and the replacement
722
+ * socket the consumer builds next overlaps it on the same auth folder.
723
+ *
724
+ * `initPromise` is declared below and swallows its own failures, so this
725
+ * neither hits its TDZ (nothing can call `end` during the synchronous
726
+ * construction below) nor masks the teardown error.
727
+ */
728
+ const end = (error) => {
729
+ // Called from inside an end handler, the teardown is already running and
730
+ // is waiting for that handler to return. Handing back its promise would
731
+ // have the handler await itself.
732
+ if (runningEndHandlers)
733
+ return Promise.resolve();
734
+ return owner.close(error).finally(() => initPromise);
735
+ };
736
+ let initError;
737
+ // Started only once `end` exists. `init()`'s synchronous prefix reaches
738
+ // `await createWhatsAppClient(...)` before the bridge can dispatch anything,
739
+ // so today nothing can call `onTerminalClose` — and therefore `end` — that
740
+ // early. But that is an argument about the current shape of `init()`, not a
741
+ // rule the code enforces: dispatch a terminal close any sooner and line 401
742
+ // becomes a `ReferenceError` inside a bridge callback, where no `try/catch`
743
+ // of ours can reach it. Ordering it here makes the dependency structural.
744
+ const initPromise = init().catch(err => {
745
+ initError = err instanceof Error ? err : new Error(String(err));
746
+ try {
747
+ logger.error({ err }, 'failed to initialize bridge client');
748
+ }
749
+ catch {
750
+ // A consumer logger cannot prevent the half-built-client
751
+ // cleanup below — and an unguarded throw here surfaces as an
752
+ // unhandled rejection on a chain the caller never sees.
753
+ }
754
+ // A client adopted before the failure outlives a read loop that never
755
+ // started: `getClient()` correctly rejects, but the standalone
756
+ // helpers bypass it and would keep reaching the half-built client.
757
+ return owner.discard();
758
+ });
759
+ /**
760
+ * Idempotent shutdown that later callers can actually await — the socket
761
+ * now ends *itself* on a terminal disconnect, so a consumer's
762
+ * `await sock.end()` is usually the second call. Resolving it early while
763
+ * the first was still flushing turned
764
+ * `close` → `await sock.end()` → `makeWASocket()` into two writers on one
765
+ * auth folder.
766
+ */
767
+ const logout = async (msg) => {
768
+ user = undefined;
769
+ const logoutError = new Boom(msg || 'Logged out', { statusCode: DisconnectReason.loggedOut });
770
+ // `Client::logout()` dispatches `LoggedOut` itself, which the dispatcher
771
+ // turns into the terminal close. Reporting our own on top of that gave
772
+ // consumers two `close` events for one logout, and upstream guarantees
773
+ // at most one — so watch for the dispatcher's instead of assuming
774
+ // either way. Counting rather than flagging, because a terminal close
775
+ // may already have happened earlier in this socket's life.
776
+ // `Client::logout()` dispatches `LoggedOut` itself, which the dispatcher
777
+ // turns into the terminal close. Reporting our own on top of that gave
778
+ // consumers two closes for one logout, and upstream guarantees at most
779
+ // one — so watch for the dispatcher's instead of assuming either way.
780
+ const reportedBefore = terminalClose.hasReported();
781
+ const live = owner.peek();
782
+ if (live) {
783
+ try {
784
+ await live.logout();
785
+ }
786
+ catch {
787
+ /* ignore */
788
+ }
789
+ }
790
+ // Nothing announced it: no client at all, or `logout()` threw before the
791
+ // bridge got to it. Upstream always reports exactly one close for a
792
+ // logout, so emitting none would be worse than emitting one too many.
793
+ // Keyed on a close having been *reported*, not on the socket closing —
794
+ // a plain `end()` reports nothing, so keying off that would let a logout
795
+ // racing one finish with no close at all.
796
+ const mayNeedFallback = !reportedBefore && !terminalClose.hasReported();
797
+ try {
798
+ await end(logoutError);
799
+ }
800
+ finally {
801
+ // After the teardown, like the dispatcher's own close: doing it
802
+ // before would hand a logged-out handler a socket still flushing the
803
+ // auth folder it is about to delete. In a `finally` because `end()`
804
+ // rethrows the first flush failure and the owner releases the client
805
+ // regardless — on that path listeners would otherwise see no
806
+ // terminal close at all for a socket that has definitely ended.
807
+ // Rechecked here, not just before the await: a dispatcher close
808
+ // arriving while `end()` ran would otherwise be followed by this
809
+ // stale decision, giving consumers two closes for one logout.
810
+ if (mayNeedFallback && !terminalClose.hasReported()) {
811
+ terminalClose.reportNow(() => ev.emit('connection.update', {
812
+ connection: 'close',
813
+ lastDisconnect: {
814
+ error: logoutError,
815
+ date: new Date()
816
+ }
817
+ }));
818
+ }
819
+ }
820
+ // The close is published on a chain one hop further out than the
821
+ // teardown both paths await, so without this `await sock.logout()`
822
+ // returns just before the event it caused.
823
+ //
824
+ // Skipped when re-entered from an end handler, for the same reason
825
+ // `end()` short-circuits there: the publish waits for the teardown, the
826
+ // teardown waits for the handler, and the handler would be waiting here
827
+ // — stalled until the watchdog fires.
828
+ if (!runningEndHandlers)
829
+ await terminalClose.published();
830
+ };
831
+ const registerSocketEndHandler = (handler) => {
832
+ socketEndHandlers.push(handler);
833
+ };
834
+ const waitForConnectionUpdate = (check, timeoutMs) => {
835
+ return new Promise((resolve, reject) => {
836
+ let timeout;
837
+ const cleanup = () => {
838
+ ev.off('connection.update', listener);
839
+ if (timeout !== undefined)
840
+ runtime.clearTimeout(timeout);
841
+ };
842
+ const listener = async (update) => {
843
+ if (update.connection === 'close') {
844
+ cleanup();
845
+ reject(update.lastDisconnect?.error ??
846
+ new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed }));
847
+ return;
848
+ }
849
+ try {
850
+ if (!(await check(update)))
851
+ return;
852
+ cleanup();
853
+ resolve();
854
+ }
855
+ catch (error) {
856
+ cleanup();
857
+ reject(error);
858
+ }
859
+ };
860
+ ev.on('connection.update', listener);
861
+ if (timeoutMs) {
862
+ timeout = unrefTimer(runtime.setTimeout(() => {
863
+ cleanup();
864
+ reject(new Boom('Timed out waiting for connection update', { statusCode: 408 }));
865
+ }, timeoutMs)
866
+ // Don't keep the process alive if the caller has already stopped
867
+ // awaiting (e.g. sock.end() during shutdown with in-flight queries).
868
+ );
869
+ }
870
+ });
871
+ };
872
+ const fetchReachoutTimelock = async () => {
873
+ const payload = await ctx.withClient(client => client.fetchReachoutTimelock());
874
+ const state = mapReachoutTimelock(payload) ?? { isActive: false };
875
+ ev.emit('connection.update', { reachoutTimeLock: state });
876
+ return state;
877
+ };
878
+ const query = async (node, timeoutMs) => {
879
+ if (!node.attrs.id)
880
+ node.attrs.id = generateMessageTag();
881
+ const result = (await ctx.withClient(client => client.queryNode(node, timeoutMs)));
882
+ assertNodeErrorFree(result);
883
+ return result;
884
+ };
885
+ const waitForMessage = makeTaggedMessageWaiter(ws, logger, fullConfig.defaultQueryTimeoutMs, {
886
+ setTimeout: runtime.setTimeout,
887
+ clearTimeout: runtime.clearTimeout
888
+ });
889
+ const usyncMethods = makeUSyncMethods({
890
+ queryNode: query,
891
+ queryUsync: async (typedQuery) => ctx.withClient(client => client.queryUsync(typedQuery))
892
+ });
893
+ const sock = {
894
+ ev,
895
+ logger,
896
+ ws,
897
+ type: 'md',
898
+ /**
899
+ * `await using sock = makeWASocket(config)` — frees the wasm client on
900
+ * scope exit. Nothing else can: the bridge holds the JS event callbacks
901
+ * as wasm-bindgen externrefs and those callbacks reach back to this
902
+ * closure, so the reference cycle crosses the JS/wasm boundary and no
903
+ * `FinalizationRegistry` will ever fire for the client.
904
+ *
905
+ * Delegates to `end()`, so it flushes the auth store and is idempotent.
906
+ *
907
+ * Then awaits `initPromise`, because `end()` alone does not satisfy the
908
+ * async-disposal contract: called before `createWhatsAppClient()`
909
+ * settles, it sees `client === undefined`, frees nothing, and resolves
910
+ * while initialization is still running. What actually disposes that
911
+ * client is the `ended` guard inside `init()` — so code after the
912
+ * `await using` scope would otherwise overlap with bridge construction,
913
+ * event callbacks, and store access. `end()` runs first because it sets
914
+ * `ended` synchronously, which is what makes `init()` bail out early.
915
+ *
916
+ * The `finally` is load-bearing: `end()` rethrows the first auth-store
917
+ * flush failure, and letting that propagate directly would skip the wait
918
+ * and resolve the disposer with `init()` still in flight — losing the
919
+ * one guarantee it exists to provide, in exactly the situation where
920
+ * cleanup already went wrong. `initPromise` swallows its own failures,
921
+ * so awaiting it here cannot mask the flush error.
922
+ */
923
+ async [Symbol.asyncDispose]() {
924
+ try {
925
+ await end(undefined);
926
+ }
927
+ finally {
928
+ await initPromise;
929
+ }
930
+ },
931
+ // Upstream `socket.ts:1106-1108` returns `authState.creds.me`, which
932
+ // carries `{ id, lid, name, verifiedName, ... }` — full Contact
933
+ // shape. Returning the bare `{id, lid}` like before broke
934
+ // upstream-port code that read `sock.user.name` /
935
+ // `sock.user.verifiedName`. Build the same structure on the fly
936
+ // from the merged auth.creds + paired-account state.
937
+ get user() {
938
+ if (!user?.id)
939
+ return undefined;
940
+ return {
941
+ id: user.id,
942
+ lid: user.lid,
943
+ name: pairedAccount?.businessName ?? auth.creds?.me?.name,
944
+ verifiedName: auth.creds?.me?.verifiedName,
945
+ ...(auth.creds?.me?.phoneNumber ? { phoneNumber: auth.creds.me.phoneNumber } : {})
946
+ };
947
+ },
948
+ get waClient() {
949
+ const live = owner.peek();
950
+ return live && wrapBridgeClient(live);
951
+ },
952
+ get isConnected() {
953
+ return owner.peek()?.isConnected() ?? false;
954
+ },
955
+ get isLoggedIn() {
956
+ return owner.peek()?.isLoggedIn() ?? false;
957
+ },
958
+ get authState() {
959
+ return {
960
+ creds: {
961
+ ...auth.creds,
962
+ ...(user ? { me: { ...auth.creds.me, id: user.id, lid: user.lid } } : {}),
963
+ ...(cachedAccount ? { account: cachedAccount } : {}),
964
+ ...(pairedAccount?.platform ? { platform: pairedAccount.platform } : {})
965
+ },
966
+ keys: getExposedKeys()
967
+ };
968
+ },
969
+ devicesMutex,
970
+ messageMutex,
971
+ receiptMutex,
972
+ appStatePatchMutex,
973
+ notificationMutex,
974
+ generateMessageTag,
975
+ sendNode: async (frame) => {
976
+ return ctx.withClient(client => client.sendNode(frame));
977
+ },
978
+ assertSessions: async (jids, force) => {
979
+ return ctx.withClient(client => client.assertSessions(jids, force ?? false));
980
+ },
981
+ getUSyncDevices: async (jids, useCache, ignoreZeroDevices) => {
982
+ return ctx.withClient(client => client.getUSyncDevices(jids, useCache, ignoreZeroDevices));
983
+ },
984
+ waitForMessage,
985
+ query,
986
+ sendRawMessage: async (data) => {
987
+ return ctx.withClient(client => client.sendRawMessage(data instanceof Uint8Array ? data : new Uint8Array(data)));
988
+ },
989
+ /**
990
+ * `dsmMessage` is accepted so the signature matches upstream, and
991
+ * refused rather than ignored. Upstream uses it to encrypt a different
992
+ * plaintext for the caller's own other devices; the engine encrypts one
993
+ * payload for every recipient, so honouring it is not possible here and
994
+ * dropping it would send those devices the wrong message.
995
+ */
996
+ createParticipantNodes: async (jids, message, extraAttrs, dsmMessage) => {
997
+ if (dsmMessage) {
998
+ throw new Boom('createParticipantNodes: dsmMessage is not supported, the engine encrypts one payload for every recipient and cannot substitute a different one for your own devices', { statusCode: 501 });
999
+ }
1000
+ const bytes = ctx.encodeProto('Message', message);
1001
+ return ctx.withClient(client => client.createParticipantNodesBytes(jids, bytes, extraAttrs ?? {}));
1002
+ },
1003
+ signalRepository,
1004
+ ...makePreKeyMethods(ctx),
1005
+ end,
1006
+ logout,
1007
+ registerSocketEndHandler,
1008
+ waitForConnectionUpdate,
1009
+ setAutoReconnect: (enabled) => {
1010
+ // Mirrored locally because the dispatcher has to know: with this off,
1011
+ // a plain drop is terminal rather than the start of a backoff.
1012
+ autoReconnectEnabled = enabled;
1013
+ owner.peek()?.setAutoReconnect(enabled);
1014
+ },
1015
+ /**
1016
+ * Update presence either globally (`available`/`unavailable`) or per-chat
1017
+ * (`composing`/`recording`/`paused`), matching upstream Baileys' overload.
1018
+ * Chat-state updates require `toJid`; omitting it raises `Boom(400)` so the
1019
+ * caller hears about the protocol mistake instead of the bridge silently
1020
+ * sending nothing.
1021
+ */
1022
+ sendPresenceUpdate: async (type, toJid) => {
1023
+ // Ahead of the client: an off-union value used to fall through to the
1024
+ // chat-state branch and be reported as a missing jid.
1025
+ assertArgumentDomain('sendPresenceUpdate', 'type', type, WA_PRESENCES);
1026
+ return ctx.withClient(async (c) => {
1027
+ if (type === 'available' || type === 'unavailable') {
1028
+ return c.sendPresence(type);
1029
+ }
1030
+ if (!toJid) {
1031
+ throw new Boom(`sendPresenceUpdate('${type}') requires a target jid`, { statusCode: 400 });
1032
+ }
1033
+ return c.sendChatState(toJid, type);
1034
+ });
1035
+ },
1036
+ /**
1037
+ * Plaintext media upload helper, source-compatible with the upstream
1038
+ * Baileys `sock.waUploadToServer(buf, { mediaType })` shape so existing
1039
+ * callers (or `prepareWAMessageMedia(msg, { upload: sock.waUploadToServer })`)
1040
+ * keep working. Delegates to the bridge's encrypt + CDN-failover upload.
1041
+ */
1042
+ waUploadToServer: async (data, opts) => {
1043
+ // The upstream set, which is wider than what the bridge uploads:
1044
+ // `toBridgeMediaType` below still refuses the ones it cannot map.
1045
+ assertArgumentDomain('waUploadToServer', 'mediaType', opts?.mediaType, MEDIA_TYPES);
1046
+ const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
1047
+ return ctx.withClient(client => client.uploadMedia(bytes, toBridgeMediaType(opts.mediaType)));
1048
+ },
1049
+ ...makePrivacyMethods(ctx),
1050
+ updateDefaultDisappearingMode: async (duration) => {
1051
+ await ctx.withClient(client => client.updateDefaultDisappearingMode(duration));
1052
+ },
1053
+ rejectCall: async (callId, callFrom) => {
1054
+ const context = activeCallContexts.get(callId);
1055
+ await ctx.withClient(client => client.rejectCall(callId, context?.peer ?? callFrom, context?.callCreator ?? callFrom));
1056
+ activeCallContexts.delete(callId);
1057
+ },
1058
+ /**
1059
+ * Fetch the account's current reachout-timelock state from the server.
1060
+ *
1061
+ * The same state is also pushed proactively via the
1062
+ * `NotificationUserReachoutTimelockUpdate` MEX notification, which is
1063
+ * surfaced on `connection.update.reachoutTimeLock` automatically. Use
1064
+ * this method to query on demand (e.g. on app start, or after a 463
1065
+ * nack hints that the timelock just kicked in).
1066
+ *
1067
+ * Emits the result on `connection.update.reachoutTimeLock` as a side
1068
+ * effect for parity with the push path. Returns the same state for
1069
+ * callers that prefer awaiting.
1070
+ */
1071
+ fetchReachoutTimelock,
1072
+ /** Upstream Baileys-compatible name. */
1073
+ fetchAccountReachoutTimelock: fetchReachoutTimelock,
1074
+ getBusinessProfile: async (jid) => {
1075
+ return bridgeBusinessProfileToBaileys(await ctx.withClient(client => client.getBusinessProfile(jid)));
1076
+ },
1077
+ fetchMessageHistory: async (count, oldestMsgKey, oldestMsgTimestamp) => {
1078
+ return ctx.withClient(client => client.fetchMessageHistory(count, oldestMsgKey.remoteJid || '', oldestMsgKey.id || '', oldestMsgKey.fromMe || false, typeof oldestMsgTimestamp === 'number' ? oldestMsgTimestamp : oldestMsgTimestamp.toNumber()));
1079
+ },
1080
+ sendStatusMessage: async (message, recipients) => {
1081
+ const bytes = ctx.encodeProto('Message', message);
1082
+ return ctx.withClient(client => client.sendStatusMessageBytes(bytes, recipients));
1083
+ },
1084
+ ...makeMessageMethodsCore(ctx, ctx.encodeProto, runtime.Long),
1085
+ ...groupMethods,
1086
+ ...communityMethods,
1087
+ ...makeContactMethods(ctx),
1088
+ ...makeProfileMethods(ctx),
1089
+ ...makeChatActionMethods(ctx),
1090
+ ...makeInternalMethods(ctx),
1091
+ ...usyncMethods,
1092
+ ...makeStanzaResponseMethods(ctx),
1093
+ ...makePresenceMethods(ctx),
1094
+ ...makeBlockingMethods(ctx),
1095
+ ...makeNewsletterMethods(ctx),
1096
+ ...makeBusinessMethods(ctx),
1097
+ ...makeServerQueryMethods(ctx),
1098
+ downloadMedia: async (message, type, options = {}) => {
1099
+ // Checked here as well as in the helper: the client is awaited while
1100
+ // the context below is built, and a check past that await reports a
1101
+ // stack without the caller in it.
1102
+ assertArgumentDomain('downloadMedia', 'type', type, MEDIA_DOWNLOAD_TYPES);
1103
+ return ctx.withClient(client => downloadMediaMessage(message, type, options, {
1104
+ logger,
1105
+ reuploadRequest: (m) => sock.updateMediaMessage(m),
1106
+ waClient: client
1107
+ }));
1108
+ }
1109
+ };
1110
+ // Assigning replaces the handler the socket itself reports through, rather
1111
+ // than shadowing it with a second one only a consumer could reach.
1112
+ Object.defineProperty(sock, 'onUnexpectedError', {
1113
+ get: () => unexpectedErrors.handler,
1114
+ set: (handler) => {
1115
+ unexpectedErrors.handler = handler;
1116
+ },
1117
+ enumerable: true,
1118
+ configurable: true
1119
+ });
1120
+ return sock;
1121
+ };
1122
+ //# sourceMappingURL=core.js.map