@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
@@ -0,0 +1,270 @@
1
+ /**
2
+ * Portable byte helpers for the runtime-neutral graph.
3
+ *
4
+ * Everything here runs on `Uint8Array` + globals available in every host
5
+ * (TextEncoder/TextDecoder, base64 via btoa/atob-free manual codec). Node
6
+ * `Buffer` conveniences stay at the compat boundary (`Utils/*`), never in
7
+ * `Socket/core.ts`, `Runtime/*` or the host entrypoint.
8
+ */
9
+ import { sha256 as bridgeSha256 } from '@oxidezap/whatsapp-rust-bridge/host';
10
+ const HEX_DIGITS = '0123456789abcdef';
11
+ const BASE64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
12
+ /** Preserve Node's historical Buffer shape when that optional global exists. */
13
+ export const publicBytes = (bytes) => {
14
+ const BufferCtor = globalThis.Buffer;
15
+ return BufferCtor ? BufferCtor.from(bytes) : bytes;
16
+ };
17
+ /** Concatenate byte views without copying through Buffer. */
18
+ export const concatBytes = (parts) => {
19
+ let total = 0;
20
+ for (const part of parts)
21
+ total += part.length;
22
+ const out = new Uint8Array(total);
23
+ let offset = 0;
24
+ for (const part of parts) {
25
+ out.set(part, offset);
26
+ offset += part.length;
27
+ }
28
+ return out;
29
+ };
30
+ /** Constant-shape equality (length check first, then byte compare). */
31
+ export const unixTimestampSeconds = (timestamp = Date.now()) => Math.floor((timestamp instanceof Date ? timestamp.getTime() : timestamp) / 1000);
32
+ export const getKeyAuthorPortable = (key, meId = 'me') => (key?.fromMe ? meId : key?.participantAlt || key?.remoteJidAlt || key?.participant || key?.remoteJid) || '';
33
+ export const toNumber = (t) => {
34
+ if (t == null)
35
+ return 0;
36
+ if (typeof t === 'number')
37
+ return t;
38
+ if (typeof t.toNumber === 'function')
39
+ return t.toNumber();
40
+ if (typeof t.low === 'number')
41
+ return (t.high ?? 0) * 0x100000000 + (t.low >>> 0);
42
+ return 0;
43
+ };
44
+ export const isBytes = (value) => value instanceof Uint8Array;
45
+ export const bytesEqual = (a, b) => {
46
+ if (a.length !== b.length)
47
+ return false;
48
+ for (let i = 0; i < a.length; i++) {
49
+ if (a[i] !== b[i])
50
+ return false;
51
+ }
52
+ return true;
53
+ };
54
+ export const utf8Encode = (text) => new TextEncoder().encode(text);
55
+ export const utf8Decode = (bytes) => new TextDecoder('utf-8', { fatal: false }).decode(bytes);
56
+ export const hexEncode = (bytes) => {
57
+ let out = '';
58
+ for (let i = 0; i < bytes.length; i++) {
59
+ const byte = bytes[i];
60
+ out += HEX_DIGITS[byte >> 4] + HEX_DIGITS[byte & 0x0f];
61
+ }
62
+ return out;
63
+ };
64
+ export const hexDecode = (text) => {
65
+ if (text.length % 2 !== 0)
66
+ throw new RangeError('hex string has odd length');
67
+ const out = new Uint8Array(text.length / 2);
68
+ for (let i = 0; i < out.length; i++) {
69
+ const hi = HEX_DIGITS.indexOf(text[2 * i].toLowerCase());
70
+ const lo = HEX_DIGITS.indexOf(text[2 * i + 1].toLowerCase());
71
+ if (hi < 0 || lo < 0)
72
+ throw new RangeError(`invalid hex at offset ${2 * i}`);
73
+ out[i] = (hi << 4) | lo;
74
+ }
75
+ return out;
76
+ };
77
+ export const base64Encode = (bytes) => {
78
+ let out = '';
79
+ for (let i = 0; i < bytes.length; i += 3) {
80
+ const a = bytes[i];
81
+ const b = bytes[i + 1] ?? 0;
82
+ const c = bytes[i + 2] ?? 0;
83
+ const triple = (a << 16) | (b << 8) | c;
84
+ out += BASE64_ALPHABET[(triple >> 18) & 0x3f];
85
+ out += BASE64_ALPHABET[(triple >> 12) & 0x3f];
86
+ out += i + 1 < bytes.length ? BASE64_ALPHABET[(triple >> 6) & 0x3f] : '=';
87
+ out += i + 2 < bytes.length ? BASE64_ALPHABET[triple & 0x3f] : '=';
88
+ }
89
+ return out;
90
+ };
91
+ const base64Value = (char) => {
92
+ if (char === '=')
93
+ return 0;
94
+ const index = BASE64_ALPHABET.indexOf(char);
95
+ if (index < 0)
96
+ throw new RangeError(`invalid base64 character: ${char}`);
97
+ return index;
98
+ };
99
+ export const base64Decode = (text) => {
100
+ let clean = text.replace(/[\s]/g, '').replace(/-/g, '+').replace(/_/g, '/');
101
+ const firstPadding = clean.indexOf('=');
102
+ if (firstPadding >= 0) {
103
+ const padding = clean.length - firstPadding;
104
+ if (padding > 2 ||
105
+ clean
106
+ .slice(firstPadding)
107
+ .split('')
108
+ .some(char => char !== '='))
109
+ throw new RangeError('invalid base64 padding');
110
+ if (clean.length % 4 !== 0 || firstPadding % 4 < 2)
111
+ throw new RangeError('invalid base64 padding');
112
+ }
113
+ else if (clean.length % 4 === 1) {
114
+ throw new RangeError('invalid base64 length');
115
+ }
116
+ // Tolerate valid unpadded input the way Buffer.from(…, 'base64') does.
117
+ while (clean.length % 4 !== 0)
118
+ clean += '=';
119
+ const pad = clean.endsWith('==') ? 2 : clean.endsWith('=') ? 1 : 0;
120
+ const out = new Uint8Array((clean.length / 4) * 3 - pad);
121
+ let offset = 0;
122
+ for (let i = 0; i < clean.length; i += 4) {
123
+ const quad = (base64Value(clean[i]) << 18) |
124
+ (base64Value(clean[i + 1]) << 12) |
125
+ (base64Value(clean[i + 2]) << 6) |
126
+ base64Value(clean[i + 3]);
127
+ if (offset < out.length)
128
+ out[offset++] = (quad >> 16) & 0xff;
129
+ if (offset < out.length)
130
+ out[offset++] = (quad >> 8) & 0xff;
131
+ if (offset < out.length)
132
+ out[offset++] = quad & 0xff;
133
+ }
134
+ return out;
135
+ };
136
+ /** URL-safe base64 without padding (tag prefixes, key ids). */
137
+ export const base64UrlEncode = (bytes) => base64Encode(bytes).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
138
+ export const base64UrlDecode = (text) => {
139
+ let padded = text.replace(/-/g, '+').replace(/_/g, '/');
140
+ while (padded.length % 4 !== 0)
141
+ padded += '=';
142
+ return base64Decode(padded);
143
+ };
144
+ export const readU16BE = (bytes, offset = 0) => ((bytes[offset] << 8) | bytes[offset + 1]) >>> 0;
145
+ export const writeU16BE = (value) => new Uint8Array([(value >>> 8) & 0xff, value & 0xff]);
146
+ /** Big-endian 64-bit write as two 32-bit words (registration ids stay numeric). */
147
+ export const writeU64BE = (high, low) => new Uint8Array([
148
+ (high >>> 24) & 0xff,
149
+ (high >>> 16) & 0xff,
150
+ (high >>> 8) & 0xff,
151
+ high & 0xff,
152
+ (low >>> 24) & 0xff,
153
+ (low >>> 16) & 0xff,
154
+ (low >>> 8) & 0xff,
155
+ low & 0xff
156
+ ]);
157
+ /** WebCrypto-backed random bytes — identical cost to node:crypto (measured). */
158
+ export const randomBytes = (length) => {
159
+ const out = new Uint8Array(length);
160
+ if (length > 0)
161
+ globalThis.crypto.getRandomValues(out);
162
+ return out;
163
+ };
164
+ /**
165
+ * Synchronous SHA-256, allocation-shaped as a fresh 32-byte digest.
166
+ *
167
+ * `node:crypto` stays the Node implementation (measured ~2.5x faster);
168
+ * this self-contained compression function serves hosts without it and
169
+ * the two synchronous call sites that cannot await `subtle.digest`
170
+ * (message IDs, poll vote hashes). Stays non-Promise either way.
171
+ * Pinned byte-for-byte against `node:crypto` by the crypto differential.
172
+ */
173
+ const SHA256_K = new Uint32Array([
174
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98,
175
+ 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
176
+ 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8,
177
+ 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
178
+ 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819,
179
+ 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
180
+ 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
181
+ ]);
182
+ const sha256SyncPortable = (data) => {
183
+ let h0 = 0x6a09e667, h1 = 0xbb67ae85, h2 = 0x3c6ef372, h3 = 0xa54ff53a, h4 = 0x510e527f, h5 = 0x9b05688c, h6 = 0x1f83d9ab, h7 = 0x5be0cd19;
184
+ const bytes = data.length;
185
+ const bitLength = bytes * 8;
186
+ const paddedLength = (((bytes + 8) >> 6) + 1) << 6;
187
+ const padded = new Uint8Array(paddedLength);
188
+ padded.set(data);
189
+ padded[bytes] = 0x80;
190
+ const view = new DataView(padded.buffer, padded.byteOffset, padded.byteLength);
191
+ view.setUint32(paddedLength - 4, bitLength >>> 0);
192
+ view.setUint32(paddedLength - 8, Math.floor(bitLength / 0x100000000));
193
+ const w = new Uint32Array(64);
194
+ for (let offset = 0; offset < paddedLength; offset += 64) {
195
+ for (let i = 0; i < 16; i++)
196
+ w[i] = view.getUint32(offset + i * 4);
197
+ for (let i = 16; i < 64; i++) {
198
+ const s0 = ((w[i - 15] >>> 7) | (w[i - 15] << 25)) ^ ((w[i - 15] >>> 18) | (w[i - 15] << 14)) ^ (w[i - 15] >>> 3);
199
+ const s1 = ((w[i - 2] >>> 17) | (w[i - 2] << 15)) ^ ((w[i - 2] >>> 19) | (w[i - 2] << 13)) ^ (w[i - 2] >>> 10);
200
+ w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0;
201
+ }
202
+ let [a, b, c, d, e, f, g, h] = [h0, h1, h2, h3, h4, h5, h6, h7];
203
+ for (let i = 0; i < 64; i++) {
204
+ const s1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7));
205
+ const ch = (e & f) ^ (~e & g);
206
+ const t1 = (h + s1 + ch + SHA256_K[i] + w[i]) | 0;
207
+ const s0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10));
208
+ const maj = (a & b) ^ (a & c) ^ (b & c);
209
+ const t2 = (s0 + maj) | 0;
210
+ h = g;
211
+ g = f;
212
+ f = e;
213
+ e = (d + t1) | 0;
214
+ d = c;
215
+ c = b;
216
+ b = a;
217
+ a = (t1 + t2) | 0;
218
+ }
219
+ h0 = (h0 + a) | 0;
220
+ h1 = (h1 + b) | 0;
221
+ h2 = (h2 + c) | 0;
222
+ h3 = (h3 + d) | 0;
223
+ h4 = (h4 + e) | 0;
224
+ h5 = (h5 + f) | 0;
225
+ h6 = (h6 + g) | 0;
226
+ h7 = (h7 + h) | 0;
227
+ }
228
+ const out = new Uint8Array(32);
229
+ const outView = new DataView(out.buffer);
230
+ outView.setUint32(0, h0 >>> 0);
231
+ outView.setUint32(4, h1 >>> 0);
232
+ outView.setUint32(8, h2 >>> 0);
233
+ outView.setUint32(12, h3 >>> 0);
234
+ outView.setUint32(16, h4 >>> 0);
235
+ outView.setUint32(20, h5 >>> 0);
236
+ outView.setUint32(24, h6 >>> 0);
237
+ outView.setUint32(28, h7 >>> 0);
238
+ return out;
239
+ };
240
+ /** The pinned host bridge exposes this wasm-bindgen failure before initSync. */
241
+ export const isBridgeWasmUnavailableError = (error) => error instanceof TypeError && error.message.includes('__wbindgen_add_to_stack_pointer');
242
+ /** Alias kept for call sites migrating off `node:crypto`. */
243
+ export const sha256Sync = (data) => {
244
+ try {
245
+ return bridgeSha256(data);
246
+ }
247
+ catch (error) {
248
+ if (isBridgeWasmUnavailableError(error))
249
+ return sha256SyncPortable(data);
250
+ throw error;
251
+ }
252
+ };
253
+ export const bytesToUtf8 = utf8Decode;
254
+ export const utf8ToBytes = utf8Encode;
255
+ /**
256
+ * Arm a one-shot timer, unref'ing on runtimes that support it so a pending
257
+ * timeout never keeps the process alive past its last socket. Host timers
258
+ * without `unref` simply stay referenced for their (short) duration.
259
+ */
260
+ export const unrefTimer = (timer) => {
261
+ try {
262
+ ;
263
+ timer?.unref?.();
264
+ }
265
+ catch {
266
+ /* a throwing unref must not break the arming call site */
267
+ }
268
+ return timer;
269
+ };
270
+ //# sourceMappingURL=bytes.js.map
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Host-neutral runtime capabilities for `createWASocketFactory`.
3
+ *
4
+ * No `node:` imports, no filesystem, no Node streams: the bridge comes from
5
+ * the host-loaded entrypoint (`initSync({ module })` before first use),
6
+ * randomness is WebCrypto, timers are duck-typed (no `unref` contract),
7
+ * platform identity is the stable Ubuntu fallback, crypto stays in
8
+ * Rust/WASM, and log lines go to `console.log`.
9
+ */
10
+ import type { BaileysRuntime } from './types.js';
11
+ /** Stable fallback: Ubuntu 22.04, matching `Browsers.ubuntu()` output shape. */
12
+ export declare const HOST_PLATFORM_FALLBACK: {
13
+ readonly os: 'Ubuntu';
14
+ readonly release: '22.04.4';
15
+ };
16
+ export declare const hostPlatformInfo: () => {
17
+ os: 'Ubuntu';
18
+ release: '22.04.4';
19
+ };
20
+ export declare const hostLoggerSink: (line: string, delivered?: () => void) => void;
21
+ export declare const hostRuntime: BaileysRuntime;
22
+ //# sourceMappingURL=host.d.ts.map
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Host-neutral runtime capabilities for `createWASocketFactory`.
3
+ *
4
+ * No `node:` imports, no filesystem, no Node streams: the bridge comes from
5
+ * the host-loaded entrypoint (`initSync({ module })` before first use),
6
+ * randomness is WebCrypto, timers are duck-typed (no `unref` contract),
7
+ * platform identity is the stable Ubuntu fallback, crypto stays in
8
+ * Rust/WASM, and log lines go to `console.log`.
9
+ */
10
+ import EventEmitter from 'events';
11
+ import * as bridge from '@oxidezap/whatsapp-rust-bridge/host';
12
+ import Long from 'long';
13
+ import { randomBytes } from './bytes.js';
14
+ /** Stable fallback: Ubuntu 22.04, matching `Browsers.ubuntu()` output shape. */
15
+ export const HOST_PLATFORM_FALLBACK = { os: 'Ubuntu', release: '22.04.4' };
16
+ export const hostPlatformInfo = () => ({ ...HOST_PLATFORM_FALLBACK });
17
+ export const hostLoggerSink = (line, delivered) => {
18
+ try {
19
+ console.log(line);
20
+ }
21
+ catch {
22
+ /* logging must not crash the host it observes */
23
+ }
24
+ finally {
25
+ delivered?.();
26
+ }
27
+ };
28
+ export const hostRuntime = {
29
+ bridge: bridge,
30
+ randomBytes,
31
+ setTimeout: (callback, ms) => setTimeout(callback, ms),
32
+ clearTimeout: handle => clearTimeout(handle),
33
+ queueMicrotask: callback => queueMicrotask(callback),
34
+ events: {
35
+ createEmitter: () => new EventEmitter()
36
+ },
37
+ platformInfo: hostPlatformInfo,
38
+ nativeCrypto: undefined,
39
+ loggerSink: hostLoggerSink,
40
+ logLevel: () => undefined,
41
+ Long
42
+ };
43
+ //# sourceMappingURL=host.js.map
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Which `long` constructor the compatibility facade builds.
3
+ *
4
+ * Upstream Baileys and the protobufjs it bundles resolve `long` through
5
+ * `require('long')` — the package's CommonJS entry (`umd/index.js`). An ESM
6
+ * `import Long from 'long'` resolves to a *different* module instance
7
+ * (`index.js`) whose constructor has its own prototype, so values it builds
8
+ * fail `deepStrictEqual` against upstream's even when every word matches
9
+ * ("same structure but not reference-equal" in
10
+ * `proto-frompartial-long.test.ts` / `proto-runtime-compatibility.test.ts`).
11
+ *
12
+ * The base revision loaded that same export with a static
13
+ * `createRequire(import.meta.url)('long')` from `node:module`. A static
14
+ * `node:module` import would drag `node:` into the host-neutral graph
15
+ * (workerd without `nodejs_compat` has no `node:` at all), so this resolves
16
+ * it lazily through `process.getBuiltinModule('module')` — available on
17
+ * every supported Node (`engines: >=22.3.0`) with no static import, the same
18
+ * lazy-builtin shape `Utils/browser-utils.ts` uses for `node:os`. Node 22.0–22.2
19
+ * lack this API; keeping the minimum at 22.3 preserves Long constructor identity
20
+ * rather than silently falling back to a different ESM constructor. Hosts fall
21
+ * back to the ESM build, where there is no upstream-constructor constraint.
22
+ */
23
+ import LongESM from 'long';
24
+ type LongConstructor = typeof LongESM;
25
+ /** The `require('long')` constructor on Node; the ESM build everywhere else. */
26
+ export declare const getLongConstructor: () => LongConstructor;
27
+ /**
28
+ * What the facade materializes every 64-bit word as. A module-level const
29
+ * (not per call) so every Long in the process shares one prototype.
30
+ */
31
+ declare const LongRuntime: LongConstructor;
32
+ export default LongRuntime;
33
+ //# sourceMappingURL=long.d.ts.map
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Which `long` constructor the compatibility facade builds.
3
+ *
4
+ * Upstream Baileys and the protobufjs it bundles resolve `long` through
5
+ * `require('long')` — the package's CommonJS entry (`umd/index.js`). An ESM
6
+ * `import Long from 'long'` resolves to a *different* module instance
7
+ * (`index.js`) whose constructor has its own prototype, so values it builds
8
+ * fail `deepStrictEqual` against upstream's even when every word matches
9
+ * ("same structure but not reference-equal" in
10
+ * `proto-frompartial-long.test.ts` / `proto-runtime-compatibility.test.ts`).
11
+ *
12
+ * The base revision loaded that same export with a static
13
+ * `createRequire(import.meta.url)('long')` from `node:module`. A static
14
+ * `node:module` import would drag `node:` into the host-neutral graph
15
+ * (workerd without `nodejs_compat` has no `node:` at all), so this resolves
16
+ * it lazily through `process.getBuiltinModule('module')` — available on
17
+ * every supported Node (`engines: >=22.3.0`) with no static import, the same
18
+ * lazy-builtin shape `Utils/browser-utils.ts` uses for `node:os`. Node 22.0–22.2
19
+ * lack this API; keeping the minimum at 22.3 preserves Long constructor identity
20
+ * rather than silently falling back to a different ESM constructor. Hosts fall
21
+ * back to the ESM build, where there is no upstream-constructor constraint.
22
+ */
23
+ import LongESM from 'long';
24
+ const loadCjsLongConstructor = () => {
25
+ try {
26
+ const proc = globalThis.process;
27
+ const getBuiltinModule = proc?.getBuiltinModule;
28
+ if (typeof getBuiltinModule !== 'function')
29
+ return undefined;
30
+ const nodeModule = getBuiltinModule('module');
31
+ const createRequire = nodeModule?.createRequire;
32
+ if (typeof createRequire !== 'function')
33
+ return undefined;
34
+ const loadModule = createRequire(import.meta.url);
35
+ const loaded = loadModule('long');
36
+ if (typeof loaded === 'function')
37
+ return loaded;
38
+ const namespaced = loaded?.default;
39
+ if (typeof namespaced === 'function')
40
+ return namespaced;
41
+ }
42
+ catch {
43
+ // Hosts without process.getBuiltinModule (workerd without
44
+ // nodejs_compat, browsers, Deno): fall through to the ESM build.
45
+ }
46
+ return undefined;
47
+ };
48
+ let cached;
49
+ let settled = false;
50
+ /** The `require('long')` constructor on Node; the ESM build everywhere else. */
51
+ export const getLongConstructor = () => {
52
+ if (!settled) {
53
+ settled = true;
54
+ cached = loadCjsLongConstructor() ?? LongESM;
55
+ }
56
+ return cached;
57
+ };
58
+ /**
59
+ * What the facade materializes every 64-bit word as. A module-level const
60
+ * (not per call) so every Long in the process shares one prototype.
61
+ */
62
+ const LongRuntime = getLongConstructor();
63
+ export default LongRuntime;
64
+ //# sourceMappingURL=long.js.map
@@ -0,0 +1,4 @@
1
+ /** Node-only optional media processors. This module is never imported by /host. */
2
+ export declare const loadImageProcessingLibrary: () => Promise<unknown>;
3
+ export declare const getAudioDuration: (input: unknown) => Promise<number | undefined>;
4
+ //# sourceMappingURL=node-media-processors.d.ts.map
@@ -0,0 +1,29 @@
1
+ /** Node-only optional media processors. This module is never imported by /host. */
2
+ export const loadImageProcessingLibrary = async () => {
3
+ // @ts-ignore Optional peer dependencies are intentionally runtime-discovered.
4
+ const [jimp, sharp] = await Promise.all([import('jimp').catch(() => { }), import('sharp').catch(() => { })]);
5
+ if (sharp)
6
+ return { sharp };
7
+ if (jimp)
8
+ return { jimp };
9
+ return {};
10
+ };
11
+ export const getAudioDuration = async (input) => {
12
+ let musicMetadata;
13
+ try {
14
+ musicMetadata = await import('music-metadata');
15
+ }
16
+ catch {
17
+ return undefined;
18
+ }
19
+ const options = { duration: true };
20
+ let metadata;
21
+ if (input instanceof Uint8Array)
22
+ metadata = await musicMetadata.parseBuffer(input, undefined, options);
23
+ else if (typeof input === 'string')
24
+ metadata = await musicMetadata.parseFile(input, options);
25
+ else
26
+ metadata = await musicMetadata.parseStream(input, undefined, options);
27
+ return metadata.format.duration;
28
+ };
29
+ //# sourceMappingURL=node-media-processors.js.map
@@ -0,0 +1,28 @@
1
+ import type { Readable } from 'node:stream';
2
+ type FileBytes = {
3
+ toString: (encoding?: string) => string;
4
+ };
5
+ /** Optional filesystem/process media capabilities. Node installs these; hosts never do. */
6
+ export declare const nodeMedia: {
7
+ getImageProcessingLibrary: () => Promise<unknown>;
8
+ decodeAudio: (input: Uint8Array) => Promise<{
9
+ getChannelData(channel: number): Float32Array;
10
+ }>;
11
+ getAudioDuration: (input: unknown) => Promise<number | undefined>;
12
+ hkdf: (input: Uint8Array, length: number, options: {
13
+ salt?: Uint8Array;
14
+ info?: string;
15
+ }) => Uint8Array;
16
+ aesGcm256Encrypt: (key: Uint8Array, nonce: Uint8Array, aad: Uint8Array, plaintext: Uint8Array) => Uint8Array;
17
+ aesGcm256Decrypt: (key: Uint8Array, nonce: Uint8Array, aad: Uint8Array, ciphertext: Uint8Array) => Uint8Array;
18
+ tempDir: () => string;
19
+ execFile: (command: string, args: string[], callback: (error: unknown) => void) => void;
20
+ createReadStream: (path: string | URL) => Readable;
21
+ fs: {
22
+ writeFile: (path: string, data: unknown) => Promise<void>;
23
+ readFile: (path: string) => Promise<FileBytes>;
24
+ unlink: (path: string) => Promise<void>;
25
+ };
26
+ };
27
+ export {};
28
+ //# sourceMappingURL=node-media.d.ts.map
@@ -0,0 +1,115 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ /** Optional filesystem/process media capabilities. Node installs these; hosts never do. */
10
+ export const nodeMedia = {
11
+ getImageProcessingLibrary: async () => ({}),
12
+ decodeAudio: async () => {
13
+ throw new Error('audio decoding is unavailable on this host');
14
+ },
15
+ getAudioDuration: async () => undefined,
16
+ hkdf: () => {
17
+ throw new Error('HKDF bridge capability is unavailable');
18
+ },
19
+ aesGcm256Encrypt: () => {
20
+ throw new Error('AES-GCM bridge capability is unavailable');
21
+ },
22
+ aesGcm256Decrypt: () => {
23
+ throw new Error('AES-GCM bridge capability is unavailable');
24
+ },
25
+ tempDir: () => '/tmp',
26
+ execFile: () => {
27
+ throw new Error('ffmpeg is unavailable on this host');
28
+ },
29
+ createReadStream: () => {
30
+ throw new Error('file media is unavailable on this host');
31
+ },
32
+ fs: {
33
+ writeFile: async () => {
34
+ throw new Error('file media is unavailable on this host');
35
+ },
36
+ readFile: async () => {
37
+ throw new Error('file media is unavailable on this host');
38
+ },
39
+ unlink: async () => {
40
+ throw new Error('file media is unavailable on this host');
41
+ }
42
+ }
43
+ };
44
+ const nodeProcess = globalThis.process;
45
+ if (nodeProcess) {
46
+ try {
47
+ const bridgePackage = ['@oxidezap', 'whatsapp-rust-bridge'].join('/');
48
+ const nodeBridge = await import(__rewriteRelativeImportExtension(bridgePackage));
49
+ const isCryptoEngineUnavailable = (error) => {
50
+ if (!(error instanceof Error))
51
+ return false;
52
+ const details = error;
53
+ return (details.kind === 'invalid-argument' &&
54
+ details.field === 'initWasmEngine' &&
55
+ details.reason === 'must be called before AES-GCM operations');
56
+ };
57
+ const withMediaCryptoInitialized = (operation) => {
58
+ try {
59
+ return operation();
60
+ }
61
+ catch (error) {
62
+ if (!isCryptoEngineUnavailable(error))
63
+ throw error;
64
+ nodeBridge.initWasmEngine();
65
+ return operation();
66
+ }
67
+ };
68
+ nodeMedia.aesGcm256Encrypt = (key, nonce, aad, plaintext) => withMediaCryptoInitialized(() => nodeBridge.aesGcm256Encrypt(key, nonce, aad, plaintext));
69
+ nodeMedia.aesGcm256Decrypt = (key, nonce, aad, ciphertext) => withMediaCryptoInitialized(() => nodeBridge.aesGcm256Decrypt(key, nonce, aad, ciphertext));
70
+ nodeMedia.hkdf = (input, length, options) => {
71
+ try {
72
+ return nodeBridge.hkdf(input, length, options);
73
+ }
74
+ catch {
75
+ nodeBridge.initWasmEngine();
76
+ return nodeBridge.hkdf(input, length, options);
77
+ }
78
+ };
79
+ nodeMedia.getImageProcessingLibrary = async () => {
80
+ const jimpPackage = ['ji', 'mp'].join('');
81
+ const sharpPackage = ['sha', 'rp'].join('');
82
+ const [jimp, sharp] = await Promise.all([
83
+ import(__rewriteRelativeImportExtension(jimpPackage)).catch(() => undefined),
84
+ import(__rewriteRelativeImportExtension(sharpPackage)).catch(() => undefined)
85
+ ]);
86
+ return sharp ? { sharp } : jimp ? { jimp } : {};
87
+ };
88
+ nodeMedia.decodeAudio = async (input) => {
89
+ const audioPackage = ['audio', 'decode'].join('-');
90
+ const loaded = (await import(__rewriteRelativeImportExtension(audioPackage)));
91
+ return loaded.default(input);
92
+ };
93
+ nodeMedia.getAudioDuration = async (input) => {
94
+ const metadataPackage = ['music', 'metadata'].join('-');
95
+ let loaded;
96
+ try {
97
+ loaded = (await import(__rewriteRelativeImportExtension(metadataPackage)));
98
+ }
99
+ catch {
100
+ return undefined;
101
+ }
102
+ const options = { duration: true };
103
+ const metadata = input instanceof Uint8Array
104
+ ? await loaded.parseBuffer(input, undefined, options)
105
+ : typeof input === 'string'
106
+ ? await loaded.parseFile(input, options)
107
+ : await loaded.parseStream(input, undefined, options);
108
+ return metadata.format.duration;
109
+ };
110
+ }
111
+ catch {
112
+ /* A host has no Node bridge loader; its runtime installs this capability. */
113
+ }
114
+ }
115
+ //# sourceMappingURL=node-media.js.map
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Node runtime capabilities for `createWASocketFactory`.
3
+ *
4
+ * The Node runtime keeps current behavior exactly: bare bridge entrypoint
5
+ * (reads the wasm off disk), WebCrypto-backed randomness (measured at parity
6
+ * with `node:crypto`), `node:events` emitter, `platform()`/`release()`
7
+ * identity, OpenSSL native crypto fast path, and the stdout logger sink with
8
+ * `BAILEYRS_LOG_LEVEL`.
9
+ */
10
+ import type { BaileysRuntime } from './types.js';
11
+ export declare const nodeRandomBytes: (length: number) => Uint8Array;
12
+ export declare const nodeLoggerSink: (line: string, delivered: () => void) => void;
13
+ export declare const nodeRuntime: BaileysRuntime;
14
+ //# sourceMappingURL=node.d.ts.map