@oxidezap/baileyrs 0.3.7 → 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 (129) hide show
  1. package/README.md +48 -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 -29
  11. package/lib/Compatibility/encode-proto.js +3 -50
  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.js +33 -11
  24. package/lib/Compatibility/socket-results.d.ts +1 -1
  25. package/lib/Compatibility/tagged-message-waiter.d.ts +5 -2
  26. package/lib/Compatibility/tagged-message-waiter.js +5 -5
  27. package/lib/Compatibility/usync/adapter.d.ts +1 -1
  28. package/lib/Compatibility/websocket-client.d.ts +11 -3
  29. package/lib/Compatibility/websocket-client.js +84 -11
  30. package/lib/Defaults/index.d.ts +8 -8
  31. package/lib/Defaults/index.js +8 -8
  32. package/lib/Media/content.d.ts +28 -0
  33. package/lib/Media/content.js +129 -0
  34. package/lib/Media/core.d.ts +34 -0
  35. package/lib/Media/core.js +120 -0
  36. package/lib/Media/mutations.d.ts +24 -0
  37. package/lib/Media/mutations.js +38 -0
  38. package/lib/Runtime/aes-gcm.d.ts +4 -0
  39. package/lib/Runtime/aes-gcm.js +11 -0
  40. package/lib/Runtime/bridge.d.ts +44 -0
  41. package/lib/Runtime/bridge.js +76 -0
  42. package/lib/Runtime/buffer.d.ts +9 -0
  43. package/lib/Runtime/buffer.js +22 -0
  44. package/lib/Runtime/bytes.d.ts +61 -0
  45. package/lib/Runtime/bytes.js +270 -0
  46. package/lib/Runtime/host.d.ts +22 -0
  47. package/lib/Runtime/host.js +43 -0
  48. package/lib/Runtime/long.d.ts +33 -0
  49. package/lib/Runtime/long.js +64 -0
  50. package/lib/Runtime/node-media-processors.d.ts +4 -0
  51. package/lib/Runtime/node-media-processors.js +29 -0
  52. package/lib/Runtime/node-media.d.ts +28 -0
  53. package/lib/Runtime/node-media.js +115 -0
  54. package/lib/Runtime/node.d.ts +14 -0
  55. package/lib/Runtime/node.js +81 -0
  56. package/lib/Runtime/paths.d.ts +4 -0
  57. package/lib/Runtime/paths.js +7 -0
  58. package/lib/Runtime/stream.d.ts +11 -0
  59. package/lib/Runtime/stream.js +25 -0
  60. package/lib/Runtime/types.d.ts +98 -0
  61. package/lib/Runtime/types.js +13 -0
  62. package/lib/Socket/core.d.ts +312 -0
  63. package/lib/Socket/core.js +1122 -0
  64. package/lib/Socket/events-core.d.ts +75 -0
  65. package/lib/Socket/events-core.js +1058 -0
  66. package/lib/Socket/events.d.ts +1 -63
  67. package/lib/Socket/events.js +4 -1047
  68. package/lib/Socket/groups.js +4 -3
  69. package/lib/Socket/index.d.ts +521 -103
  70. package/lib/Socket/index.js +10 -1007
  71. package/lib/Socket/messages-core.d.ts +41 -0
  72. package/lib/Socket/messages-core.js +270 -0
  73. package/lib/Socket/messages.d.ts +9 -36
  74. package/lib/Socket/messages.js +3 -260
  75. package/lib/Socket/newsletter.js +3 -3
  76. package/lib/Socket/profile.js +1 -1
  77. package/lib/Socket/terminal-close-reporter.d.ts +2 -0
  78. package/lib/Socket/terminal-close-reporter.js +3 -3
  79. package/lib/Socket/transport.d.ts +2 -0
  80. package/lib/Socket/transport.js +16 -1
  81. package/lib/Socket/types.d.ts +2 -0
  82. package/lib/Types/Auth.d.ts +11 -0
  83. package/lib/Types/Message.d.ts +1 -1
  84. package/lib/Types/Socket.d.ts +2 -2
  85. package/lib/Types/index.d.ts +6 -1
  86. package/lib/Utils/browser-utils.d.ts +4 -0
  87. package/lib/Utils/browser-utils.js +53 -2
  88. package/lib/Utils/crypto.d.ts +1 -0
  89. package/lib/Utils/crypto.js +1 -0
  90. package/lib/Utils/event-buffer.d.ts +6 -1
  91. package/lib/Utils/event-buffer.js +28 -27
  92. package/lib/Utils/link-preview.d.ts +4 -3
  93. package/lib/Utils/logger.d.ts +3 -0
  94. package/lib/Utils/logger.js +35 -6
  95. package/lib/Utils/messages-core.d.ts +174 -0
  96. package/lib/Utils/messages-core.js +1042 -0
  97. package/lib/Utils/messages-media-core.d.ts +73 -0
  98. package/lib/Utils/messages-media-core.js +319 -0
  99. package/lib/Utils/messages-media.d.ts +1 -72
  100. package/lib/Utils/messages-media.js +9 -358
  101. package/lib/Utils/messages.d.ts +1 -166
  102. package/lib/Utils/messages.js +7 -1040
  103. package/lib/Utils/optional-peer.js +14 -5
  104. package/lib/Utils/process-history-message-core.d.ts +36 -0
  105. package/lib/Utils/process-history-message-core.js +187 -0
  106. package/lib/Utils/process-history-message.d.ts +5 -43
  107. package/lib/Utils/process-history-message.js +11 -197
  108. package/lib/Utils/process-message-core.d.ts +29 -0
  109. package/lib/Utils/process-message-core.js +112 -0
  110. package/lib/Utils/process-message.d.ts +4 -24
  111. package/lib/Utils/process-message.js +6 -111
  112. package/lib/WABinary/generic-utils.js +7 -5
  113. package/lib/host-shared.d.ts +74 -0
  114. package/lib/host-shared.js +15 -0
  115. package/lib/host-socket-operations.d.ts +3 -0
  116. package/lib/host-socket-operations.js +2 -0
  117. package/lib/host-surface.d.ts +21 -0
  118. package/lib/host-surface.js +35 -0
  119. package/lib/host-types.d.ts +356 -0
  120. package/lib/host-types.js +2 -0
  121. package/lib/host.d.ts +33 -0
  122. package/lib/host.js +31 -0
  123. package/lib/node-surface.d.ts +9 -0
  124. package/lib/node-surface.js +15 -0
  125. package/lib/surface.d.ts +5 -0
  126. package/lib/surface.js +6 -0
  127. package/lib/wasm.d.ts +27 -0
  128. package/lib/wasm.js +27 -0
  129. package/package.json +18 -6
@@ -1,5 +1,29 @@
1
+ import { Buffer } from 'node:buffer';
1
2
  import { initAuthCreds } from '../../Utils/generics.js';
3
+ import { hydrateHostAuthCreds } from '../host-auth-state.js';
2
4
  import { projectNativeStore } from '../legacy-store/native-projection.js';
5
+ const hydrationByState = new WeakMap();
6
+ const preserveNodeCredentialBytes = (creds) => {
7
+ for (const pair of [
8
+ creds.noiseKey,
9
+ creds.pairingEphemeralKeyPair,
10
+ creds.signedIdentityKey,
11
+ creds.signedPreKey.keyPair
12
+ ]) {
13
+ pair.private = Buffer.from(pair.private);
14
+ pair.public = Buffer.from(pair.public);
15
+ }
16
+ creds.signedPreKey.signature = Buffer.from(creds.signedPreKey.signature);
17
+ if (creds.routingInfo)
18
+ creds.routingInfo = Buffer.from(creds.routingInfo);
19
+ };
20
+ export const refreshSocketAuthenticationState = async (state) => {
21
+ if (!state.store)
22
+ return;
23
+ await hydrateHostAuthCreds(state.store, state.creds);
24
+ preserveNodeCredentialBytes(state.creds);
25
+ };
26
+ export const waitForSocketAuthenticationState = (state) => hydrationByState.get(state) ?? Promise.resolve();
3
27
  /**
4
28
  * Complete the public authentication view used by the socket when callers use
5
29
  * the native byte-store path. The byte store remains authoritative: the key
@@ -16,6 +40,15 @@ export const normalizeSocketAuthenticationState = (input) => {
16
40
  if (!creds || !keys) {
17
41
  throw new TypeError('auth must provide both creds and keys when no native store is configured');
18
42
  }
19
- return { creds, keys, ...(store ? { store } : {}) };
43
+ const state = { creds, keys, ...(store ? { store } : {}) };
44
+ if (store && !input.creds) {
45
+ const hydration = refreshSocketAuthenticationState(state);
46
+ // The socket initialization awaits the original promise. Attach a
47
+ // rejection observer immediately so a synchronously rejecting store does
48
+ // not become an unhandled rejection before init reaches its first await.
49
+ void hydration.catch(() => undefined);
50
+ hydrationByState.set(state, hydration);
51
+ }
52
+ return state;
20
53
  };
21
54
  //# sourceMappingURL=auth-state.js.map
@@ -0,0 +1,4 @@
1
+ import type { AuthenticationState, NativeAuthenticationState } from '../../Types/index.js';
2
+ /** Host normalization: native stores remain Rust-owned and expose no legacy key facade. */
3
+ export declare const normalizeHostAuthenticationState: (input: AuthenticationState | NativeAuthenticationState) => AuthenticationState;
4
+ //# sourceMappingURL=host-auth-state.d.ts.map
@@ -0,0 +1,14 @@
1
+ /** Host normalization: native stores remain Rust-owned and expose no legacy key facade. */
2
+ export const normalizeHostAuthenticationState = (input) => {
3
+ if (!input || typeof input !== 'object')
4
+ throw new TypeError('auth must provide either { creds, keys } or a native store');
5
+ if (input.creds && input.keys)
6
+ return input;
7
+ if (input.store && input.creds)
8
+ return input;
9
+ if (input.store) {
10
+ throw new TypeError('host auth with a native store must be created with await createAuthenticationState(store)');
11
+ }
12
+ throw new TypeError('auth must provide both creds and keys when no native store is configured');
13
+ };
14
+ //# sourceMappingURL=host-auth-state.js.map
@@ -1,9 +1,9 @@
1
1
  // Device credential projection for legacy Baileys authentication states.
2
- import { Buffer } from 'node:buffer';
3
2
  import { proto } from '@oxidezap/whatsapp-rust-bridge/proto-types';
3
+ import { base64Decode, base64Encode, publicBytes } from '../../Runtime/bytes.js';
4
4
  import { WA_DEFAULT_VERSION } from '../../Defaults/index.js';
5
5
  import { jidDecode, jidEncode } from '../../WABinary/jid-utils.js';
6
- import { DeviceRecordKey, JsonByteEncoding, SignalDomain, SignalKeyLength, TimeValue } from './constants.js';
6
+ import { DeviceRecordKey, SignalDomain, SignalKeyLength, TimeValue } from './constants.js';
7
7
  import { bytesToNumbers, fromJsonBytes, toJsonBytes } from './common.js';
8
8
  import { isAllZero, requireByteArray, requireSafeUnsignedInteger } from './validation.js';
9
9
  const signedDeviceIdentityCodec = proto.ADVSignedDeviceIdentity;
@@ -73,7 +73,7 @@ function deviceFromCreds(creds) {
73
73
  ? bytesToNumbers(creds.signedPreKey.signature)
74
74
  : Array(SignalKeyLength.SIGNATURE).fill(0),
75
75
  adv_secret_key: creds.advSecretKey
76
- ? bytesToNumbers(Buffer.from(creds.advSecretKey, JsonByteEncoding.BASE64))
76
+ ? bytesToNumbers(base64Decode(creds.advSecretKey))
77
77
  : Array(SignalKeyLength.ADV_SECRET).fill(0),
78
78
  account: null,
79
79
  push_name: creds.me.name ?? '',
@@ -159,12 +159,12 @@ function prepareNativeDevice(payload) {
159
159
  };
160
160
  }
161
161
  if (advSecret?.some(byte => byte !== 0)) {
162
- creds.advSecretKey = Buffer.from(advSecret).toString(JsonByteEncoding.BASE64);
162
+ creds.advSecretKey = base64Encode(new Uint8Array(advSecret));
163
163
  }
164
164
  if (routingInfo === null)
165
165
  creds.routingInfo = undefined;
166
166
  else if (routingInfo)
167
- creds.routingInfo = Buffer.from(routingInfo);
167
+ creds.routingInfo = publicBytes(new Uint8Array(routingInfo));
168
168
  };
169
169
  }
170
170
  export function parseDeviceRecordKey(value) {
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Portable message-identity helpers for the runtime-neutral graph.
3
+ *
4
+ * `generateMessageIDV2` is the one place every send path resolves a stanza
5
+ * id through (`Compatibility/message-relay.ts:resolveMessageId`, group
6
+ * invite stubs). The bytes are identical to `Utils/generics.ts` — 8-byte
7
+ * big-endian unix seconds, user JID + `@c.us`, 16 random bytes, SHA-256 hex,
8
+ * `3EB0` prefix — but built on `Runtime/bytes.ts` (portable SHA-256,
9
+ * WebCrypto randomness) instead of `node:crypto` + `Buffer`, so hosts get
10
+ * the same ids without a Node import.
11
+ */
12
+ export declare const generateMessageIDV2Portable: (userId?: string, randomSource?: (length: number) => Uint8Array) => string;
13
+ /** `3EB0` + 36 uppercase hex chars from 18 random bytes (matches `generateMessageID`). */
14
+ export declare const generateMessageIDPortable: (randomSource?: (length: number) => Uint8Array) => string;
15
+ /** Concatenate without Buffer (pad helper for the portable graph). */
16
+ export declare const concatMessageBytes: (parts: ReadonlyArray<Uint8Array>) => Uint8Array;
17
+ //# sourceMappingURL=message-ids.d.ts.map
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Portable message-identity helpers for the runtime-neutral graph.
3
+ *
4
+ * `generateMessageIDV2` is the one place every send path resolves a stanza
5
+ * id through (`Compatibility/message-relay.ts:resolveMessageId`, group
6
+ * invite stubs). The bytes are identical to `Utils/generics.ts` — 8-byte
7
+ * big-endian unix seconds, user JID + `@c.us`, 16 random bytes, SHA-256 hex,
8
+ * `3EB0` prefix — but built on `Runtime/bytes.ts` (portable SHA-256,
9
+ * WebCrypto randomness) instead of `node:crypto` + `Buffer`, so hosts get
10
+ * the same ids without a Node import.
11
+ */
12
+ import { concatBytes, hexEncode, randomBytes, sha256Sync, utf8Encode, writeU64BE } from '../Runtime/bytes.js';
13
+ const MESSAGE_ID_PREFIX = '3EB0';
14
+ const MESSAGE_ID_BYTES = 44;
15
+ const RANDOM_OFFSET = 28;
16
+ const writeAsciiInto = (target, text, offset) => {
17
+ const bytes = utf8Encode(text);
18
+ const length = Math.min(bytes.length, target.length - offset);
19
+ for (let i = 0; i < length; i++)
20
+ target[offset + i] = bytes[i];
21
+ };
22
+ /** Extract the user part of a JID without importing the JID utils (cycle-safe). */
23
+ const jidUser = (jid) => {
24
+ const at = jid.indexOf('@');
25
+ const user = at < 0 ? jid : jid.slice(0, at);
26
+ // Baileys hashes the bare user, not the device/agent suffix of a
27
+ // multi-device JID (`user:device` or `user_agent`).
28
+ const bareUser = user.split('_', 1)[0].split(':', 1)[0];
29
+ return bareUser.length > 0 ? bareUser : undefined;
30
+ };
31
+ export const generateMessageIDV2Portable = (userId, randomSource = randomBytes) => {
32
+ const data = new Uint8Array(MESSAGE_ID_BYTES);
33
+ const seconds = Math.floor(Date.now() / 1000);
34
+ data.set(writeU64BE(0, seconds >>> 0), 0);
35
+ const user = userId ? jidUser(userId) : undefined;
36
+ if (user) {
37
+ writeAsciiInto(data, user, 8);
38
+ writeAsciiInto(data, '@c.us', 8 + utf8Encode(user).length);
39
+ }
40
+ data.set(randomSource(16), RANDOM_OFFSET);
41
+ return `${MESSAGE_ID_PREFIX}${hexEncode(sha256Sync(data)).toUpperCase().slice(0, 18)}`;
42
+ };
43
+ /** `3EB0` + 36 uppercase hex chars from 18 random bytes (matches `generateMessageID`). */
44
+ export const generateMessageIDPortable = (randomSource = randomBytes) => `3EB0${hexEncode(randomSource(18)).toUpperCase()}`;
45
+ /** Concatenate without Buffer (pad helper for the portable graph). */
46
+ export const concatMessageBytes = (parts) => concatBytes(parts);
47
+ //# sourceMappingURL=message-ids.js.map
@@ -10,7 +10,7 @@ export type OwnRelayIdentity = {
10
10
  * Every send path resolves through here, so `messageId` means the same thing
11
11
  * on `sendMessage` and on `relayMessage`.
12
12
  */
13
- export declare const resolveMessageId: (own: OwnRelayIdentity, messageId?: string) => string;
13
+ export declare const resolveMessageId: (own: OwnRelayIdentity, messageId?: string, randomBytes?: (length: number) => Uint8Array) => string;
14
14
  export type MessageRelayPlan = {
15
15
  kind: 'message';
16
16
  messageId: string;
@@ -28,5 +28,5 @@ export type MessageRelayPlan = {
28
28
  messageId: string;
29
29
  input: MessageRetransmissionInput;
30
30
  };
31
- export declare const planMessageRelay: (jid: string, options: MessageRelayOptions, own: OwnRelayIdentity) => MessageRelayPlan;
31
+ export declare const planMessageRelay: (jid: string, options: MessageRelayOptions, own: OwnRelayIdentity, randomBytes?: (length: number) => Uint8Array) => MessageRelayPlan;
32
32
  //# sourceMappingURL=message-relay.d.ts.map
@@ -1,5 +1,5 @@
1
1
  import { Boom } from '../Utils/boom.js';
2
- import { generateMessageIDV2 } from '../Utils/generics.js';
2
+ import { generateMessageIDV2Portable as generateMessageIDV2 } from './message-ids.js';
3
3
  import { areJidsSameUser, isJidBroadcast, isJidGroup, isJidNewsletter } from '../WABinary/index.js';
4
4
  export const EMPTY_RELAY_NODES = [];
5
5
  /**
@@ -7,7 +7,7 @@ export const EMPTY_RELAY_NODES = [];
7
7
  * Every send path resolves through here, so `messageId` means the same thing
8
8
  * on `sendMessage` and on `relayMessage`.
9
9
  */
10
- export const resolveMessageId = (own, messageId) => messageId || generateMessageIDV2(own?.id);
10
+ export const resolveMessageId = (own, messageId, randomBytes) => messageId || generateMessageIDV2(own?.id, randomBytes);
11
11
  const assertSupportedAttributes = (attributes) => {
12
12
  if (!attributes)
13
13
  return;
@@ -21,7 +21,7 @@ const assertSupportedAttributes = (attributes) => {
21
21
  };
22
22
  const isDirectConversation = (jid) => !isJidGroup(jid) && !isJidBroadcast(jid) && !isJidNewsletter(jid);
23
23
  const isOwnDevice = (jid, own) => (own?.id !== undefined && areJidsSameUser(jid, own.id)) || (own?.lid !== undefined && areJidsSameUser(jid, own.lid));
24
- export const planMessageRelay = (jid, options, own) => {
24
+ export const planMessageRelay = (jid, options, own, randomBytes) => {
25
25
  const { messageId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList } = options;
26
26
  assertSupportedAttributes(additionalAttributes);
27
27
  const nodes = additionalNodes ?? EMPTY_RELAY_NODES;
@@ -30,7 +30,7 @@ export const planMessageRelay = (jid, options, own) => {
30
30
  statusCode: 400
31
31
  });
32
32
  }
33
- const id = resolveMessageId(own, messageId);
33
+ const id = resolveMessageId(own, messageId, randomBytes);
34
34
  const refreshGroupMetadata = useCachedGroupMetadata === false;
35
35
  if (participant) {
36
36
  const requesterIsOwnDevice = isDirectConversation(jid) && isOwnDevice(participant.jid, own);
@@ -1,16 +1,12 @@
1
- import { Buffer } from 'node:buffer';
2
- import { createRequire } from 'node:module';
3
- import { BinaryReader } from '@oxidezap/whatsapp-rust-bridge';
1
+ import LongRuntime from '../Runtime/long.js';
2
+ import { BinaryReader } from '@oxidezap/whatsapp-rust-bridge/host';
3
+ import { base64Decode, base64Encode, publicBytes } from '../Runtime/bytes.js';
4
4
  import { PROTO_ENUM_SCHEMAS, PROTO_FIELD_FLAG, PROTO_FIELD_KIND, PROTO_MESSAGE_SCHEMAS } from '../WAProto/compatibility-schema.js';
5
5
  const INSTANCE_SCHEMA = Symbol('proto compatibility schema');
6
6
  const EMPTY_ARRAY = Object.freeze([]);
7
7
  const EMPTY_OBJECT = Object.freeze({});
8
8
  const JSON_OPTIONS = Object.freeze({ longs: String, enums: String, bytes: String, json: true });
9
9
  const WORD_BASE = 1n << 32n;
10
- // protobufjs resolves the CommonJS Long constructor internally. Loading that
11
- // same export keeps `instanceof` and prototype identity aligned without
12
- // loading protobufjs itself or adding a second wire runtime.
13
- const LongRuntime = createRequire(import.meta.url)('long');
14
10
  const hasOwn = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
15
11
  const isObject = (value) => typeof value === 'object' && value !== null;
16
12
  const isReaderLike = (value) => isObject(value) && value.buf instanceof Uint8Array && typeof value.pos === 'number' && typeof value.len === 'number';
@@ -205,19 +201,45 @@ const longToNumber = (value, unsigned) => {
205
201
  };
206
202
  const bytesToBase64 = (value) => {
207
203
  if (value instanceof Uint8Array) {
208
- return Buffer.from(value.buffer, value.byteOffset, value.byteLength).toString('base64');
204
+ return base64Encode(value);
209
205
  }
210
- return Buffer.from(value).toString('base64');
206
+ return base64Encode(Uint8Array.from(value));
211
207
  };
212
208
  const bytesFromObject = (value) => {
213
209
  if (typeof value === 'string')
214
- return Buffer.from(value, 'base64');
210
+ return nodeBytesFromBase64(value);
215
211
  if (isObject(value) && typeof value.length === 'number')
216
212
  return value;
217
213
  if (Array.isArray(value))
218
214
  return value;
219
215
  return undefined;
220
216
  };
217
+ /**
218
+ * Upstream protobufjs materializes `bytes` fields as Node `Buffer` on Node
219
+ * (`protobuf.util.Buffer`), and the compatibility contract asserts
220
+ * `deepStrictEqual` against that — `Buffer` vs `Uint8Array` fails even with
221
+ * identical contents. The host-neutral graph cannot import `node:buffer`,
222
+ * so the base64 decode stays portable and only the wrapping is Node-only,
223
+ * resolved lazily through `process.getBuiltinModule('buffer')` (same
224
+ * lazy-builtin shape `Utils/browser-utils.ts` uses for `node:os`): no
225
+ * static `node:` import, `Buffer.from(u8)` on Node, the plain `Uint8Array`
226
+ * on hosts where there is no upstream-Buffer constraint to keep.
227
+ */
228
+ const nodeBytesFromBase64 = (value) => {
229
+ try {
230
+ const proc = globalThis.process;
231
+ const bufferModule = proc?.getBuiltinModule?.('buffer');
232
+ // protobufjs delegates string coercion to Buffer.from(), including its
233
+ // permissive handling of excess padding and ignored non-alphabet bytes.
234
+ const nodeBytes = bufferModule?.Buffer?.from?.(value, 'base64');
235
+ if (nodeBytes !== undefined)
236
+ return nodeBytes;
237
+ }
238
+ catch {
239
+ /* host runtimes use the strict portable decoder below */
240
+ }
241
+ return base64Decode(value);
242
+ };
221
243
  const oneofName = (field) => {
222
244
  const flags = field[3];
223
245
  if (flags & PROTO_FIELD_FLAG.proto3Optional)
@@ -871,7 +893,7 @@ class ProtoCompatibilityRuntime {
871
893
  case PROTO_FIELD_KIND.bool:
872
894
  return false;
873
895
  case PROTO_FIELD_KIND.bytes:
874
- return options.bytes === String ? '' : options.bytes === Array ? [] : Buffer.alloc(0);
896
+ return options.bytes === String ? '' : options.bytes === Array ? [] : publicBytes(new Uint8Array(0));
875
897
  case PROTO_FIELD_KIND.signed64:
876
898
  case PROTO_FIELD_KIND.unsigned64:
877
899
  return options.longs === String
@@ -1,4 +1,4 @@
1
- import type { BlocklistEntryResult, BusinessProfileResult, MembershipRequestResult, ParticipantChangeResult } from '@oxidezap/whatsapp-rust-bridge';
1
+ import type { BlocklistEntryResult, BusinessProfileResult, MembershipRequestResult, ParticipantChangeResult } from '@oxidezap/whatsapp-rust-bridge/host';
2
2
  import type { BinaryNode, WABusinessProfile } from '../Types/index.js';
3
3
  export type ParticipantUpdateResult = {
4
4
  status: string;
@@ -1,5 +1,8 @@
1
- import type { EventEmitter } from 'node:events';
1
+ import type { EventEmitter } from 'events';
2
2
  import type { ILogger } from '../Utils/logger.js';
3
3
  /** Build the low-level tagged-response waiter with upstream timeout semantics. */
4
- export declare const makeTaggedMessageWaiter: (ws: EventEmitter, logger: ILogger, defaultTimeoutMs?: number) => <T>(msgId: string, timeoutMs?: number | undefined) => Promise<T | undefined>;
4
+ export declare const makeTaggedMessageWaiter: (ws: EventEmitter, logger: ILogger, defaultTimeoutMs: number | undefined, timers: {
5
+ setTimeout: (callback: () => void, ms: number) => unknown;
6
+ clearTimeout: (handle: unknown) => void;
7
+ }) => <T>(msgId: string, timeoutMs?: number | undefined) => Promise<T | undefined>;
5
8
  //# sourceMappingURL=tagged-message-waiter.d.ts.map
@@ -1,7 +1,8 @@
1
+ import { unrefTimer } from '../Runtime/bytes.js';
1
2
  import { DisconnectReason } from '../Types/index.js';
2
3
  import { Boom } from '../Utils/boom.js';
3
4
  /** Build the low-level tagged-response waiter with upstream timeout semantics. */
4
- export const makeTaggedMessageWaiter = (ws, logger, defaultTimeoutMs) => async function waitForMessage(msgId, timeoutMs = defaultTimeoutMs) {
5
+ export const makeTaggedMessageWaiter = (ws, logger, defaultTimeoutMs, timers) => async function waitForMessage(msgId, timeoutMs = defaultTimeoutMs) {
5
6
  const tag = `TAG:${msgId}`;
6
7
  let timer;
7
8
  let onRecv;
@@ -16,8 +17,7 @@ export const makeTaggedMessageWaiter = (ws, logger, defaultTimeoutMs) => async f
16
17
  ws.on('close', onError);
17
18
  ws.on('error', onError);
18
19
  if (timeoutMs) {
19
- timer = setTimeout(() => reject(new Boom('Timed out waiting for message', { statusCode: DisconnectReason.timedOut })), timeoutMs);
20
- timer.unref();
20
+ timer = unrefTimer(timers.setTimeout(() => reject(new Boom('Timed out waiting for message', { statusCode: DisconnectReason.timedOut })), timeoutMs));
21
21
  }
22
22
  });
23
23
  }
@@ -29,8 +29,8 @@ export const makeTaggedMessageWaiter = (ws, logger, defaultTimeoutMs) => async f
29
29
  throw error;
30
30
  }
31
31
  finally {
32
- if (timer)
33
- clearTimeout(timer);
32
+ if (timer !== undefined)
33
+ timers.clearTimeout(timer);
34
34
  if (onRecv)
35
35
  ws.off(tag, onRecv);
36
36
  if (onError) {
@@ -1,4 +1,4 @@
1
- import type { UsyncQuery as NativeUsyncQuery, UsyncResponse as NativeUsyncResponse } from '@oxidezap/whatsapp-rust-bridge';
1
+ import type { UsyncQuery as NativeUsyncQuery, UsyncResponse as NativeUsyncResponse } from '@oxidezap/whatsapp-rust-bridge/host';
2
2
  import type { BinaryNode } from '../../Types/index.js';
3
3
  import { type USyncQuery, type USyncQueryResult } from '../../WAUSync/USyncQuery.js';
4
4
  export type RawUSyncQuery = (node: BinaryNode, timeoutMs?: number) => Promise<BinaryNode>;
@@ -1,7 +1,7 @@
1
- import { EventEmitter } from 'node:events';
2
- import { URL } from 'node:url';
1
+ import { EventEmitter } from 'events';
3
2
  import type { WasmWhatsAppClient } from '@oxidezap/whatsapp-rust-bridge';
4
3
  import type { SocketConfig } from '../Types/index.js';
4
+ import type { RuntimeEventEmitter } from '../Runtime/types.js';
5
5
  type ReadyState = 0 | 1 | 2 | 3;
6
6
  type EventListener = Parameters<EventEmitter['on']>[1];
7
7
  export declare const isRawNodeForwardingEnabled: (client: WebSocketClient) => boolean;
@@ -19,9 +19,10 @@ export declare class WebSocketClient extends EventEmitter {
19
19
  * still running — which is how teardown reached `free()` on a busy client.
20
20
  */
21
21
  private closeState;
22
+ private readonly emitter?;
22
23
  private readonly getClient;
23
24
  private listenerMutationDepth;
24
- constructor(url: string | URL, config: SocketConfig, getClient: () => WasmWhatsAppClient | undefined);
25
+ constructor(url: string | URL, config: SocketConfig, getClient: () => WasmWhatsAppClient | undefined, emitter?: RuntimeEventEmitter);
25
26
  get isOpen(): boolean;
26
27
  get isClosed(): boolean;
27
28
  get isClosing(): boolean;
@@ -36,6 +37,13 @@ export declare class WebSocketClient extends EventEmitter {
36
37
  removeListener(eventName: string | symbol, listener: EventListener): this;
37
38
  off(eventName: string | symbol, listener: EventListener): this;
38
39
  removeAllListeners(eventName?: string | symbol): this;
40
+ emit(eventName: string | symbol, ...args: unknown[]): boolean;
41
+ eventNames(): (string | symbol)[];
42
+ rawListeners(eventName: string | symbol): EventListener[];
43
+ listeners(eventName: string | symbol): EventListener[];
44
+ listenerCount(eventName: string | symbol, listener?: EventListener): number;
45
+ setMaxListeners(count: number): this;
46
+ getMaxListeners(): number;
39
47
  connect(): void;
40
48
  /**
41
49
  * Idempotent, and a second caller joins the first rather than returning
@@ -1,11 +1,10 @@
1
- import { EventEmitter } from 'node:events';
2
- import { URL } from 'node:url';
1
+ import { EventEmitter } from 'events';
3
2
  import { DEF_CALLBACK_PREFIX, DEF_TAG_PREFIX } from '../Defaults/index.js';
4
3
  const isRawNodeEventName = (eventName) => typeof eventName === 'string' && (eventName.startsWith(DEF_CALLBACK_PREFIX) || eventName.startsWith(DEF_TAG_PREFIX));
5
4
  export const isRawNodeForwardingEnabled = (client) => client.hasRawNodeListeners;
6
5
  /** Public WebSocket-compatible facade over the socket owned by the native client. */
7
6
  export class WebSocketClient extends EventEmitter {
8
- constructor(url, config, getClient) {
7
+ constructor(url, config, getClient, emitter) {
9
8
  super();
10
9
  /**
11
10
  * One value rather than a pair of booleans plus a promise that could
@@ -18,6 +17,7 @@ export class WebSocketClient extends EventEmitter {
18
17
  this.url = url instanceof URL ? url : new URL(url);
19
18
  this.config = config;
20
19
  this.getClient = getClient;
20
+ this.emitter = emitter;
21
21
  this.setMaxListeners(0);
22
22
  this.socket = {};
23
23
  Object.defineProperty(this.socket, 'readyState', {
@@ -62,28 +62,101 @@ export class WebSocketClient extends EventEmitter {
62
62
  }
63
63
  }
64
64
  on(eventName, listener) {
65
- return this.mutateListeners(() => super.on(eventName, listener));
65
+ return this.mutateListeners(() => {
66
+ if (!this.emitter)
67
+ return super.on(eventName, listener);
68
+ this.emitter.on(eventName, listener);
69
+ return this;
70
+ });
66
71
  }
67
72
  addListener(eventName, listener) {
68
- return this.mutateListeners(() => super.addListener(eventName, listener));
73
+ return this.mutateListeners(() => {
74
+ if (!this.emitter)
75
+ return super.addListener(eventName, listener);
76
+ this.emitter.on(eventName, listener);
77
+ return this;
78
+ });
69
79
  }
70
80
  once(eventName, listener) {
71
- return this.mutateListeners(() => super.once(eventName, listener));
81
+ return this.mutateListeners(() => {
82
+ if (!this.emitter)
83
+ return super.once(eventName, listener);
84
+ this.emitter.once(eventName, listener);
85
+ return this;
86
+ });
72
87
  }
73
88
  prependListener(eventName, listener) {
74
- return this.mutateListeners(() => super.prependListener(eventName, listener));
89
+ return this.mutateListeners(() => {
90
+ if (!this.emitter)
91
+ return super.prependListener(eventName, listener);
92
+ this.emitter.prependListener(eventName, listener);
93
+ return this;
94
+ });
75
95
  }
76
96
  prependOnceListener(eventName, listener) {
77
- return this.mutateListeners(() => super.prependOnceListener(eventName, listener));
97
+ return this.mutateListeners(() => {
98
+ if (!this.emitter)
99
+ return super.prependOnceListener(eventName, listener);
100
+ this.emitter.prependOnceListener(eventName, listener);
101
+ return this;
102
+ });
78
103
  }
79
104
  removeListener(eventName, listener) {
80
- return this.mutateListeners(() => super.removeListener(eventName, listener));
105
+ return this.mutateListeners(() => {
106
+ if (!this.emitter)
107
+ return super.removeListener(eventName, listener);
108
+ this.emitter.removeListener(eventName, listener);
109
+ return this;
110
+ });
81
111
  }
82
112
  off(eventName, listener) {
83
- return this.mutateListeners(() => super.off(eventName, listener));
113
+ return this.mutateListeners(() => {
114
+ if (!this.emitter)
115
+ return super.off(eventName, listener);
116
+ this.emitter.off(eventName, listener);
117
+ return this;
118
+ });
84
119
  }
85
120
  removeAllListeners(eventName) {
86
- return this.mutateListeners(() => eventName === undefined ? super.removeAllListeners() : super.removeAllListeners(eventName));
121
+ return this.mutateListeners(() => {
122
+ if (!this.emitter)
123
+ return eventName === undefined ? super.removeAllListeners() : super.removeAllListeners(eventName);
124
+ if (eventName === undefined)
125
+ this.emitter.removeAllListeners();
126
+ else
127
+ this.emitter.removeAllListeners(eventName);
128
+ return this;
129
+ });
130
+ }
131
+ emit(eventName, ...args) {
132
+ return this.emitter
133
+ ? this.mutateListeners(() => this.emitter.emit(eventName, ...args))
134
+ : super.emit(eventName, ...args);
135
+ }
136
+ eventNames() {
137
+ return this.emitter ? this.emitter.eventNames() : super.eventNames();
138
+ }
139
+ rawListeners(eventName) {
140
+ return this.emitter ? this.emitter.rawListeners(eventName) : super.rawListeners(eventName);
141
+ }
142
+ listeners(eventName) {
143
+ return this.emitter ? this.emitter.listeners(eventName) : super.listeners(eventName);
144
+ }
145
+ listenerCount(eventName, listener) {
146
+ return this.emitter
147
+ ? listener === undefined
148
+ ? this.emitter.listenerCount(eventName)
149
+ : this.emitter.listenerCount(eventName, listener)
150
+ : super.listenerCount(eventName, listener);
151
+ }
152
+ setMaxListeners(count) {
153
+ if (!this.emitter)
154
+ return super.setMaxListeners(count);
155
+ this.emitter.setMaxListeners(count);
156
+ return this;
157
+ }
158
+ getMaxListeners() {
159
+ return this.emitter ? this.emitter.getMaxListeners() : super.getMaxListeners();
87
160
  }
88
161
  connect() {
89
162
  const client = this.getClient();
@@ -1,4 +1,4 @@
1
- import { Buffer } from 'node:buffer';
1
+ import type { Buffer } from 'node:buffer';
2
2
  import { proto } from '../WAProto/runtime.js';
3
3
  import type { SocketConfig, WAVersion } from '../Types/index.js';
4
4
  export declare const WA_DEFAULT_VERSION: WAVersion;
@@ -9,10 +9,10 @@ export declare const CALL_AUDIO_PREFIX = "https://call.whatsapp.com/voice/";
9
9
  export declare const DEF_CALLBACK_PREFIX = "CB:";
10
10
  export declare const DEF_TAG_PREFIX = "TAG:";
11
11
  export declare const PHONE_CONNECTION_CB = "CB:Pong";
12
- export declare const WA_ADV_ACCOUNT_SIG_PREFIX: Buffer<ArrayBuffer>;
13
- export declare const WA_ADV_DEVICE_SIG_PREFIX: Buffer<ArrayBuffer>;
14
- export declare const WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX: Buffer<ArrayBuffer>;
15
- export declare const WA_ADV_HOSTED_DEVICE_SIG_PREFIX: Buffer<ArrayBuffer>;
12
+ export declare const WA_ADV_ACCOUNT_SIG_PREFIX: Buffer;
13
+ export declare const WA_ADV_DEVICE_SIG_PREFIX: Buffer;
14
+ export declare const WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX: Buffer;
15
+ export declare const WA_ADV_HOSTED_DEVICE_SIG_PREFIX: Buffer;
16
16
  export declare const WA_DEFAULT_EPHEMERAL: number;
17
17
  /** Status messages older than 24 hours are considered expired. */
18
18
  export declare const STATUS_EXPIRY_SECONDS: number;
@@ -20,13 +20,13 @@ export declare const STATUS_EXPIRY_SECONDS: number;
20
20
  export declare const PLACEHOLDER_MAX_AGE_SECONDS: number;
21
21
  export declare const NOISE_MODE = "Noise_XX_25519_AESGCM_SHA256\0\0\0\0";
22
22
  export declare const DICT_VERSION = 3;
23
- export declare const KEY_BUNDLE_TYPE: Buffer<ArrayBuffer>;
24
- export declare const NOISE_WA_HEADER: Buffer<ArrayBuffer>;
23
+ export declare const KEY_BUNDLE_TYPE: Buffer;
24
+ export declare const NOISE_WA_HEADER: Buffer;
25
25
  export declare const URL_REGEX: RegExp;
26
26
  export declare const WA_CERT_DETAILS: {
27
27
  SERIAL: number;
28
28
  ISSUER: string;
29
- PUBLIC_KEY: Buffer<ArrayBuffer>;
29
+ PUBLIC_KEY: Buffer;
30
30
  };
31
31
  export declare const PROCESSABLE_HISTORY_TYPES: proto.HistorySync.HistorySyncType[];
32
32
  export declare const DEFAULT_CACHE_TTLS: {
@@ -1,4 +1,4 @@
1
- import { Buffer } from 'node:buffer';
1
+ import { hexDecode, publicBytes } from '../Runtime/bytes.js';
2
2
  import { makeDefaultSignalRepository } from '../Compatibility/signal-repository.js';
3
3
  import { proto } from '../WAProto/runtime.js';
4
4
  import { Browsers } from '../Utils/browser-utils.js';
@@ -11,10 +11,10 @@ export const CALL_AUDIO_PREFIX = 'https://call.whatsapp.com/voice/';
11
11
  export const DEF_CALLBACK_PREFIX = 'CB:';
12
12
  export const DEF_TAG_PREFIX = 'TAG:';
13
13
  export const PHONE_CONNECTION_CB = 'CB:Pong';
14
- export const WA_ADV_ACCOUNT_SIG_PREFIX = Buffer.from([6, 0]);
15
- export const WA_ADV_DEVICE_SIG_PREFIX = Buffer.from([6, 1]);
16
- export const WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX = Buffer.from([6, 5]);
17
- export const WA_ADV_HOSTED_DEVICE_SIG_PREFIX = Buffer.from([6, 6]);
14
+ export const WA_ADV_ACCOUNT_SIG_PREFIX = publicBytes(new Uint8Array([6, 0]));
15
+ export const WA_ADV_DEVICE_SIG_PREFIX = publicBytes(new Uint8Array([6, 1]));
16
+ export const WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX = publicBytes(new Uint8Array([6, 5]));
17
+ export const WA_ADV_HOSTED_DEVICE_SIG_PREFIX = publicBytes(new Uint8Array([6, 6]));
18
18
  export const WA_DEFAULT_EPHEMERAL = 7 * 24 * 60 * 60;
19
19
  /** Status messages older than 24 hours are considered expired. */
20
20
  export const STATUS_EXPIRY_SECONDS = 24 * 60 * 60;
@@ -22,13 +22,13 @@ export const STATUS_EXPIRY_SECONDS = 24 * 60 * 60;
22
22
  export const PLACEHOLDER_MAX_AGE_SECONDS = 14 * 24 * 60 * 60;
23
23
  export const NOISE_MODE = 'Noise_XX_25519_AESGCM_SHA256\0\0\0\0';
24
24
  export const DICT_VERSION = 3;
25
- export const KEY_BUNDLE_TYPE = Buffer.from([5]);
26
- export const NOISE_WA_HEADER = Buffer.from([87, 65, 6, DICT_VERSION]);
25
+ export const KEY_BUNDLE_TYPE = publicBytes(new Uint8Array([5]));
26
+ export const NOISE_WA_HEADER = publicBytes(new Uint8Array([87, 65, 6, DICT_VERSION]));
27
27
  export const URL_REGEX = /https:\/\/(?![^:@/\s]+:[^:@/\s]+@)[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(:\d+)?(\/[^\s]*)?/g;
28
28
  export const WA_CERT_DETAILS = {
29
29
  SERIAL: 0,
30
30
  ISSUER: 'WhatsAppLongTerm1',
31
- PUBLIC_KEY: Buffer.from('142375574d0a587166aae71ebe516437c4a28b73e3695c6ce1f7f9545da8ee6b', 'hex')
31
+ PUBLIC_KEY: publicBytes(hexDecode('142375574d0a587166aae71ebe516437c4a28b73e3695c6ce1f7f9545da8ee6b'))
32
32
  };
33
33
  export const PROCESSABLE_HISTORY_TYPES = [
34
34
  proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP,
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Portable message-content helpers: content-type detection and envelope
3
+ * normalization (ephemeral / view-once / template unwrapping).
4
+ *
5
+ * Extracted verbatim from `Utils/messages.ts` (`getContentType`,
6
+ * `normalizeMessageContent` + its private helpers) so the event pipeline
7
+ * (`Utils/process-message.ts`, `Socket/events.ts`) can run on hosts without
8
+ * pulling the send path, the media pipeline, or any `node:` import. No
9
+ * behavioral change: the differential suite pins both functions against
10
+ * the originals.
11
+ */
12
+ import type { WAMessageContent } from '../Types/index.js';
13
+ import type { proto } from '../WAProto/runtime.js';
14
+ /** Get the key to access the true type of content */
15
+ export declare const getContentType: (content: proto.IMessage | undefined) => keyof proto.IMessage | undefined;
16
+ /**
17
+ * Normalizes ephemeral, view once messages to regular message content
18
+ * Eg. image messages in ephemeral messages, in view once messages etc.
19
+ * @param content
20
+ * @returns
21
+ */
22
+ export declare const normalizeMessageContent: (content: WAMessageContent | null | undefined) => WAMessageContent | undefined;
23
+ /**
24
+ * Extract the true message content from a message
25
+ * Eg. extracts the inner message from a disappearing message/view once message
26
+ */
27
+ export declare const extractMessageContent: (content: WAMessageContent | undefined | null) => WAMessageContent | undefined;
28
+ //# sourceMappingURL=content.d.ts.map