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