@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,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
@@ -0,0 +1,129 @@
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
+ /**
13
+ * The content keys that carry almost every message on a live socket, settled by
14
+ * identity before the structural predicate runs. Every name here already
15
+ * satisfies that predicate, so this only shortcuts the substring scan; it never
16
+ * changes which key wins.
17
+ */
18
+ const isCommonContentKey = (key) => {
19
+ switch (key) {
20
+ case 'conversation':
21
+ case 'extendedTextMessage':
22
+ case 'imageMessage':
23
+ case 'videoMessage':
24
+ case 'audioMessage':
25
+ case 'stickerMessage':
26
+ case 'documentMessage':
27
+ case 'reactionMessage':
28
+ case 'protocolMessage':
29
+ case 'pollCreationMessage':
30
+ return true;
31
+ default:
32
+ return false;
33
+ }
34
+ };
35
+ /** Get the key to access the true type of content */
36
+ export const getContentType = (content) => {
37
+ if (!content) {
38
+ return undefined;
39
+ }
40
+ // The answer stays positional (the first own key naming content wins), but
41
+ // the scan is an indexed loop with an early return instead of `Array.find`,
42
+ // so no closure is allocated and the common keys never reach `includes`.
43
+ //
44
+ // Deliberately still `Object.keys` and not `for..in`: a decoded
45
+ // `WAProto.Message` inherits a default for every field of the schema, so
46
+ // `for..in` would enumerate ~100 prototype keys per call (and would have to
47
+ // filter them back out with `hasOwn` to stay positional) where `Object.keys`
48
+ // yields only the handful that were actually set.
49
+ const keys = Object.keys(content);
50
+ for (let i = 0; i < keys.length; i++) {
51
+ const key = keys[i];
52
+ if (isCommonContentKey(key)) {
53
+ return key;
54
+ }
55
+ if (key.includes('Message') && key !== 'senderKeyDistributionMessage') {
56
+ return key;
57
+ }
58
+ }
59
+ return undefined;
60
+ };
61
+ const getFutureProofMessage = (message) => message?.ephemeralMessage ||
62
+ message?.viewOnceMessage ||
63
+ message?.documentWithCaptionMessage ||
64
+ message?.viewOnceMessageV2 ||
65
+ message?.viewOnceMessageV2Extension ||
66
+ message?.editedMessage ||
67
+ message?.associatedChildMessage ||
68
+ message?.groupStatusMessage ||
69
+ message?.groupStatusMessageV2;
70
+ const extractFromTemplateMessage = (msg) => {
71
+ if (msg.imageMessage) {
72
+ return { imageMessage: msg.imageMessage };
73
+ }
74
+ else if (msg.documentMessage) {
75
+ return { documentMessage: msg.documentMessage };
76
+ }
77
+ else if (msg.videoMessage) {
78
+ return { videoMessage: msg.videoMessage };
79
+ }
80
+ else if (msg.locationMessage) {
81
+ return { locationMessage: msg.locationMessage };
82
+ }
83
+ else {
84
+ return {
85
+ conversation: 'contentText' in msg ? msg.contentText : 'hydratedContentText' in msg ? msg.hydratedContentText : ''
86
+ };
87
+ }
88
+ };
89
+ /**
90
+ * Normalizes ephemeral, view once messages to regular message content
91
+ * Eg. image messages in ephemeral messages, in view once messages etc.
92
+ * @param content
93
+ * @returns
94
+ */
95
+ export const normalizeMessageContent = (content) => {
96
+ if (!content) {
97
+ return undefined;
98
+ }
99
+ // set max iterations to prevent an infinite loop
100
+ for (let i = 0; i < 5; i++) {
101
+ const inner = getFutureProofMessage(content);
102
+ if (!inner) {
103
+ break;
104
+ }
105
+ content = inner.message;
106
+ }
107
+ return content;
108
+ };
109
+ /**
110
+ * Extract the true message content from a message
111
+ * Eg. extracts the inner message from a disappearing message/view once message
112
+ */
113
+ export const extractMessageContent = (content) => {
114
+ content = normalizeMessageContent(content);
115
+ if (content?.buttonsMessage) {
116
+ return extractFromTemplateMessage(content.buttonsMessage);
117
+ }
118
+ if (content?.templateMessage?.hydratedFourRowTemplate) {
119
+ return extractFromTemplateMessage(content?.templateMessage?.hydratedFourRowTemplate);
120
+ }
121
+ if (content?.templateMessage?.hydratedTemplate) {
122
+ return extractFromTemplateMessage(content?.templateMessage?.hydratedTemplate);
123
+ }
124
+ if (content?.templateMessage?.fourRowTemplate) {
125
+ return extractFromTemplateMessage(content?.templateMessage?.fourRowTemplate);
126
+ }
127
+ return content;
128
+ };
129
+ //# sourceMappingURL=content.js.map
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Portable media core: retry crypto, direct-path helpers, HKDF key
3
+ * derivation, extension/base64 helpers and the retry-node codec.
4
+ *
5
+ * No filesystem, no child processes, no image/audio libraries, no Node
6
+ * streams: every input and output is `Uint8Array` (or a string), randomness
7
+ * comes from `Runtime/bytes.ts`, AES-GCM goes through the bridge-exposed
8
+ * primitives in `Utils/crypto.ts` (OpenSSL on Node, WASM fallback on
9
+ * hosts), and HKDF/SHA-256 come from the bridge + portable bytes.
10
+ * Anything needing `fs`, `ffmpeg`, `sharp`/`jimp`, `music-metadata`,
11
+ * `audio-decode` or Node `Readable` lives in `Utils/messages-media.ts`
12
+ * (the Node half) and stays there.
13
+ */
14
+ import type { MediaType } from '../Defaults/index.js';
15
+ import type { BaileysEventMap, BinaryNode, MediaDecryptionKeyInfo, WAMessageContent, WAMessageKey } from '../Types/index.js';
16
+ import { proto } from '../WAProto/runtime.js';
17
+ import type { MediaCryptoRuntime } from '../Runtime/types.js';
18
+ export declare const hkdfInfoKey: (type: MediaType) => string;
19
+ /** Derive the IV + cipher + MAC keys for a media decryption. Accepts raw bytes or base64. */
20
+ export declare function getMediaKeys(buffer: Uint8Array | string | null | undefined, mediaType: MediaType, runtime?: MediaCryptoRuntime): Promise<MediaDecryptionKeyInfo>;
21
+ /** URL-safe base64 without padding, for upload query params. */
22
+ export declare const encodeBase64EncodedStringForUpload: (b64: string) => string;
23
+ export declare const mediaMessageSHA256B64: (message: WAMessageContent) => string | null | undefined;
24
+ export declare const DEF_MEDIA_HOST = "mmg.whatsapp.net";
25
+ export declare const getUrlFromDirectPath: (directPath: string, host?: string) => string;
26
+ export declare function extensionForMediaMessage(message: WAMessageContent): string;
27
+ export declare const encryptMediaRetryRequest: (key: WAMessageKey, mediaKey: Uint8Array, meId: string, runtime?: MediaCryptoRuntime) => BinaryNode;
28
+ export declare const getStatusCodeForMediaRetry: (code: number) => 200 | 412 | 404 | 418;
29
+ export declare const decodeMediaRetryNode: (node: BinaryNode) => BaileysEventMap['messages.media-update'][number];
30
+ export declare const decryptMediaRetryData: ({ ciphertext, iv }: {
31
+ ciphertext: Uint8Array;
32
+ iv: Uint8Array;
33
+ }, mediaKey: Uint8Array, msgId: string, runtime?: MediaCryptoRuntime) => proto.MediaRetryNotification;
34
+ //# sourceMappingURL=core.d.ts.map
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Portable media core: retry crypto, direct-path helpers, HKDF key
3
+ * derivation, extension/base64 helpers and the retry-node codec.
4
+ *
5
+ * No filesystem, no child processes, no image/audio libraries, no Node
6
+ * streams: every input and output is `Uint8Array` (or a string), randomness
7
+ * comes from `Runtime/bytes.ts`, AES-GCM goes through the bridge-exposed
8
+ * primitives in `Utils/crypto.ts` (OpenSSL on Node, WASM fallback on
9
+ * hosts), and HKDF/SHA-256 come from the bridge + portable bytes.
10
+ * Anything needing `fs`, `ffmpeg`, `sharp`/`jimp`, `music-metadata`,
11
+ * `audio-decode` or Node `Readable` lives in `Utils/messages-media.ts`
12
+ * (the Node half) and stays there.
13
+ */
14
+ import { MEDIA_HKDF_KEY_MAPPING } from '../Defaults/index.js';
15
+ import { proto } from '../WAProto/runtime.js';
16
+ import { base64Decode, base64Encode, utf8Encode } from '../Runtime/bytes.js';
17
+ import { hostRuntime } from '../Runtime/host.js';
18
+ import { makeMediaCryptoRuntime } from '../Runtime/bridge.js';
19
+ import { getBinaryNodeChild, getBinaryNodeChildBuffer } from '../WABinary/generic-utils.js';
20
+ import { jidNormalizedUser } from '../WABinary/jid-utils.js';
21
+ import { Boom } from '../Utils/boom.js';
22
+ export const hkdfInfoKey = (type) => `WhatsApp ${MEDIA_HKDF_KEY_MAPPING[type]} Keys`;
23
+ const defaultCryptoRuntime = makeMediaCryptoRuntime(hostRuntime);
24
+ const stripDataPrefix = (value) => value.replace('data:;base64,', '');
25
+ /** Derive the IV + cipher + MAC keys for a media decryption. Accepts raw bytes or base64. */
26
+ export async function getMediaKeys(buffer, mediaType, runtime = defaultCryptoRuntime) {
27
+ if (!buffer)
28
+ throw new Boom('Cannot derive from empty media key');
29
+ const keyBytes = typeof buffer === 'string' ? base64Decode(stripDataPrefix(buffer)) : buffer;
30
+ const expandedMediaKey = runtime.hkdf(keyBytes, 112, { info: hkdfInfoKey(mediaType) });
31
+ return {
32
+ iv: expandedMediaKey.slice(0, 16),
33
+ cipherKey: expandedMediaKey.slice(16, 48),
34
+ macKey: expandedMediaKey.slice(48, 80)
35
+ };
36
+ }
37
+ /** URL-safe base64 without padding, for upload query params. */
38
+ export const encodeBase64EncodedStringForUpload = (b64) => encodeURIComponent(b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''));
39
+ export const mediaMessageSHA256B64 = (message) => {
40
+ const media = Object.values(message)[0];
41
+ const digest = media?.fileSha256;
42
+ if (digest == null)
43
+ return digest;
44
+ return typeof digest === 'string' ? digest : base64Encode(digest);
45
+ };
46
+ export const DEF_MEDIA_HOST = 'mmg.whatsapp.net';
47
+ export const getUrlFromDirectPath = (directPath, host = DEF_MEDIA_HOST) => `https://${host}${directPath}`;
48
+ export function extensionForMediaMessage(message) {
49
+ const getExtension = (mimetype) => mimetype.split(';')[0]?.split('/')[1];
50
+ const type = Object.keys(message)[0];
51
+ if (type === 'locationMessage' || type === 'liveLocationMessage' || type === 'productMessage')
52
+ return '.jpeg';
53
+ return getExtension(message[type].mimetype);
54
+ }
55
+ const getMediaRetryKey = (mediaKey, runtime) => runtime.hkdf(mediaKey, 32, { info: 'WhatsApp Media Retry Notification' });
56
+ export const encryptMediaRetryRequest = (key, mediaKey, meId, runtime = defaultCryptoRuntime) => {
57
+ const receiptBuffer = proto.ServerErrorReceipt.encode({ stanzaId: key.id }).finish();
58
+ const iv = runtime.randomBytes(12);
59
+ const ciphertext = runtime.aesGcm256Encrypt(getMediaRetryKey(mediaKey, runtime), iv, utf8Encode(key.id), receiptBuffer);
60
+ return {
61
+ tag: 'receipt',
62
+ attrs: { id: key.id, to: jidNormalizedUser(meId), type: 'server-error' },
63
+ content: [
64
+ {
65
+ tag: 'encrypt',
66
+ attrs: {},
67
+ content: [
68
+ { tag: 'enc_p', attrs: {}, content: ciphertext },
69
+ { tag: 'enc_iv', attrs: {}, content: iv }
70
+ ]
71
+ },
72
+ {
73
+ tag: 'rmr',
74
+ attrs: {
75
+ jid: key.remoteJid,
76
+ from_me: (!!key.fromMe).toString(),
77
+ ...(key.participant ? { participant: key.participant } : {})
78
+ }
79
+ }
80
+ ]
81
+ };
82
+ };
83
+ const MEDIA_RETRY_STATUS_MAP = {
84
+ [proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
85
+ [proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
86
+ [proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
87
+ [proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418
88
+ };
89
+ export const getStatusCodeForMediaRetry = (code) => MEDIA_RETRY_STATUS_MAP[code];
90
+ export const decodeMediaRetryNode = (node) => {
91
+ const retryNode = getBinaryNodeChild(node, 'rmr');
92
+ const event = {
93
+ key: {
94
+ id: node.attrs.id,
95
+ remoteJid: retryNode.attrs.jid,
96
+ fromMe: retryNode.attrs.from_me === 'true',
97
+ participant: retryNode.attrs.participant
98
+ }
99
+ };
100
+ const errorNode = getBinaryNodeChild(node, 'error');
101
+ if (errorNode) {
102
+ const errorCode = +errorNode.attrs.code;
103
+ event.error = new Boom(`Failed to re-upload media (${errorCode})`, {
104
+ data: errorNode.attrs,
105
+ statusCode: getStatusCodeForMediaRetry(errorCode)
106
+ });
107
+ }
108
+ else {
109
+ const encryptedInfoNode = getBinaryNodeChild(node, 'encrypt');
110
+ const ciphertext = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_p');
111
+ const iv = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_iv');
112
+ if (ciphertext && iv)
113
+ event.media = { ciphertext, iv };
114
+ else
115
+ event.error = new Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 });
116
+ }
117
+ return event;
118
+ };
119
+ export const decryptMediaRetryData = ({ ciphertext, iv }, mediaKey, msgId, runtime = defaultCryptoRuntime) => proto.MediaRetryNotification.decode(runtime.aesGcm256Decrypt(getMediaRetryKey(mediaKey, runtime), iv, utf8Encode(msgId), ciphertext));
120
+ //# sourceMappingURL=core.js.map
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Portable message-mutation helpers for the event buffer.
3
+ *
4
+ * `updateMessageWithReceipt` / `updateMessageWithReaction` move verbatim
5
+ * from `Utils/messages.ts` so `Utils/event-buffer.ts` (in the host graph)
6
+ * no longer pulls the send path, the media pipeline, or any `node:`
7
+ * import. `getKeyAuthor` is a two-line pure helper, duplicated here rather
8
+ * than importing `Utils/generics.ts` (which is Node-bound).
9
+ */
10
+ import type { WAMessage, MessageUserReceipt } from '../Types/index.js';
11
+ import type { proto } from '../WAProto/runtime.js';
12
+ /** Resolve the upstream-visible author identity, preferring alternate addressing fields. */
13
+ export declare const getKeyAuthor: (key: WAMessage['key'] | undefined | null, meId?: string) => string;
14
+ /** Remove undefined own properties in place, matching upstream Baileys. */
15
+ export declare function trimUndefined(obj: {
16
+ [key: string]: any;
17
+ }): {
18
+ [key: string]: any;
19
+ };
20
+ /** Upsert one receipt into a message's `userReceipt` collection. */
21
+ export declare const updateMessageWithReceipt: (msg: Pick<WAMessage, 'userReceipt'>, receipt: MessageUserReceipt) => void;
22
+ /** Replace the previous reaction from the same author, then append the latest. */
23
+ export declare const updateMessageWithReaction: (msg: Pick<WAMessage, 'reactions'>, reaction: proto.IReaction) => void;
24
+ //# sourceMappingURL=mutations.d.ts.map
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Portable message-mutation helpers for the event buffer.
3
+ *
4
+ * `updateMessageWithReceipt` / `updateMessageWithReaction` move verbatim
5
+ * from `Utils/messages.ts` so `Utils/event-buffer.ts` (in the host graph)
6
+ * no longer pulls the send path, the media pipeline, or any `node:`
7
+ * import. `getKeyAuthor` is a two-line pure helper, duplicated here rather
8
+ * than importing `Utils/generics.ts` (which is Node-bound).
9
+ */
10
+ /** Resolve the upstream-visible author identity, preferring alternate addressing fields. */
11
+ export const getKeyAuthor = (key, meId = 'me') => (key?.fromMe ? meId : key?.participantAlt || key?.remoteJidAlt || key?.participant || key?.remoteJid) || '';
12
+ /** Remove undefined own properties in place, matching upstream Baileys. */
13
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
14
+ export function trimUndefined(obj) {
15
+ for (const key in obj) {
16
+ if (obj[key] === undefined)
17
+ delete obj[key];
18
+ }
19
+ return obj;
20
+ }
21
+ /** Upsert one receipt into a message's `userReceipt` collection. */
22
+ export const updateMessageWithReceipt = (msg, receipt) => {
23
+ msg.userReceipt = msg.userReceipt || [];
24
+ const existing = msg.userReceipt.find(item => item.userJid === receipt.userJid);
25
+ if (existing)
26
+ Object.assign(existing, receipt);
27
+ else
28
+ msg.userReceipt.push(receipt);
29
+ };
30
+ /** Replace the previous reaction from the same author, then append the latest. */
31
+ export const updateMessageWithReaction = (msg, reaction) => {
32
+ const author = getKeyAuthor(reaction.key || {});
33
+ const reactions = (msg.reactions || []).filter(item => getKeyAuthor(item.key || {}) !== author);
34
+ reaction.text = reaction.text || '';
35
+ reactions.push(reaction);
36
+ msg.reactions = reactions;
37
+ };
38
+ //# sourceMappingURL=mutations.js.map