@oxidezap/baileyrs 0.3.13 → 0.3.15

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.
@@ -1,4 +1,4 @@
1
- import { recordFlushFailure, settledFlushError, trackFlushFailures, withTrackedFailures } from './flush-deadline.js';
1
+ import { settleBeforeFlushDeadline, flushDeadlineError, recordFlushFailure, settledFlushError, trackFlushFailures, withTrackedFailures } from './flush-deadline.js';
2
2
  import { defaultSyncDir } from './durable-directory.js';
3
3
  import { transactionalFileStore } from './transactional-file-store.js';
4
4
  import { Buffer } from 'node:buffer';
@@ -312,7 +312,9 @@ async function usePerKeyBridgeStore(folder, options) {
312
312
  throw e;
313
313
  }
314
314
  uncertain.delete(cacheKey);
315
- rememberDurable(cacheKey, copyBytes(value));
315
+ // `value` is already a private copy (taken at admission in `doSet`) that
316
+ // nothing mutates and every read copies, so it is remembered as is.
317
+ rememberDurable(cacheKey, value);
316
318
  };
317
319
  // Flush one pending key. Runs under the key lock (not tracked in
318
320
  // `admitted`: the drain loop drives it, so tracking it would make
@@ -354,6 +356,7 @@ async function usePerKeyBridgeStore(folder, options) {
354
356
  const FLUSH_MAX_PASSES = 32;
355
357
  const newDrainScope = () => ({ failedEntries: new WeakSet() });
356
358
  const flushAll = (scope = newDrainScope()) => {
359
+ const deadline = Date.now() + 30000;
357
360
  const errors = new Map();
358
361
  const drain = async () => {
359
362
  if (scope.exhausted) {
@@ -379,17 +382,20 @@ async function usePerKeyBridgeStore(folder, options) {
379
382
  // guards a caller emitting writes in a tight loop —
380
383
  // `Socket/index.ts.end()` waits on this and must return.
381
384
  for (let i = 0; i < FLUSH_MAX_PASSES; i++) {
382
- const outstanding = [...admitted];
383
- if (outstanding.length > 0) {
384
- await Promise.all(outstanding.map(operation => operation.catch(error => {
385
- recordFlushFailure(errors, operation, error);
386
- })));
387
- }
388
- if (eligibleKeys().length === 0) {
389
- if (admitted.size === 0)
385
+ // Consecutive critical callbacks are already writing through. Join
386
+ // their admission barrier within this pass, under the same 30s
387
+ // deadline; only actual pending-write drains spend the 32 passes.
388
+ while (admitted.size > 0) {
389
+ // Cache hits can settle only through microtasks and starve the
390
+ // timeout callback, so enforce the wall clock before each batch.
391
+ if (Date.now() >= deadline)
392
+ throw flushDeadlineError('use-bridge-store flush', errors);
393
+ await settleBeforeFlushDeadline([...admitted], deadline, 'use-bridge-store flush', errors);
394
+ if (errors.size)
390
395
  break;
391
- continue;
392
396
  }
397
+ if (errors.size || eligibleKeys().length === 0)
398
+ break;
393
399
  const keys = eligibleKeys();
394
400
  let failed = false;
395
401
  await Promise.all(keys.map(key => {
@@ -496,10 +502,15 @@ async function usePerKeyBridgeStore(folder, options) {
496
502
  return null;
497
503
  throw e;
498
504
  }
499
- const arr = copyBytes(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
505
+ // `readFile` returns a fresh buffer this read owns, so the cache keeps a
506
+ // view of it and only the caller's array is copied. A buffer carved from
507
+ // a shared pool (sizes unknown up front) is copied instead, so the cache
508
+ // never pins a larger slab.
509
+ const read = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
510
+ const owned = data.byteOffset === 0 && data.buffer.byteLength === data.byteLength;
500
511
  if (!keyUncertain)
501
- rememberDurable(cacheKey, copyBytes(arr));
502
- return arr;
512
+ rememberDurable(cacheKey, owned ? read : copyBytes(read));
513
+ return copyBytes(read);
503
514
  };
504
515
  const doGet = (store, key) => {
505
516
  const cacheKey = `${store}\0${key}`;
@@ -616,8 +627,10 @@ async function usePerKeyBridgeStore(folder, options) {
616
627
  key = decodeURIComponent(encoded);
617
628
  }
618
629
  catch {
619
- continue; // skip a filename we can't decode rather than crash
630
+ throw new TypeError(`invalid native auth filename: ${file}`);
620
631
  }
632
+ if (encodeURIComponent(key) !== encoded)
633
+ throw new TypeError(`noncanonical native auth filename: ${file}`);
621
634
  if (prefix && !key.startsWith(prefix))
622
635
  continue;
623
636
  found.add(key);
@@ -1,4 +1,4 @@
1
- import { atomicCallbacks, rowKey } from './atomic-store.js';
1
+ import { atomicCallbacks } from './atomic-store.js';
2
2
  import { markNativeMemoryStore } from '../Compatibility/internal/native-memory-store.js';
3
3
  /**
4
4
  * Creates a purely in-memory authentication store.
@@ -24,15 +24,46 @@ export function useMemoryStore(options = {}) {
24
24
  };
25
25
  const memoryStore = {
26
26
  ...atomicCallbacks(async (change) => {
27
- const rows = new Map();
28
- for (const [namespace, bucket] of stores)
29
- for (const [key, value] of bucket)
30
- rows.set(rowKey(namespace, key), value);
27
+ // Reads go through to the buckets and writes are staged, so a change
28
+ // costs the rows it touches instead of a copy of every stored row (each
29
+ // key re-parsed) per transaction. Nothing is applied when `change`
30
+ // throws, and replaying the writes in order onto the buckets leaves the
31
+ // same rows in the same order as rebuilding them from a full copy.
32
+ const staged = new Map();
33
+ const writes = [];
34
+ const read = (rawKey) => {
35
+ if (staged.has(rawKey))
36
+ return staged.get(rawKey);
37
+ const [namespace, key] = JSON.parse(rawKey);
38
+ return stores.get(namespace)?.get(key);
39
+ };
40
+ const rows = {
41
+ get: read,
42
+ has: rawKey => read(rawKey) !== undefined,
43
+ set(rawKey, value) {
44
+ staged.set(rawKey, value);
45
+ writes.push([rawKey, value]);
46
+ return rows;
47
+ },
48
+ delete(rawKey) {
49
+ const existed = read(rawKey) !== undefined;
50
+ staged.set(rawKey, undefined);
51
+ writes.push([rawKey, undefined]);
52
+ return existed;
53
+ }
54
+ };
31
55
  change(rows);
32
- stores.clear();
33
- for (const [rawKey, value] of rows) {
56
+ for (const [rawKey, value] of writes) {
34
57
  const [namespace, key] = JSON.parse(rawKey);
35
- bucketForWrite(namespace).set(key, value);
58
+ if (value !== undefined) {
59
+ bucketForWrite(namespace).set(key, value);
60
+ continue;
61
+ }
62
+ const bucket = stores.get(namespace);
63
+ if (!bucket)
64
+ continue;
65
+ bucket.delete(key);
66
+ deleteEmptyBucket(namespace, bucket);
36
67
  }
37
68
  }),
38
69
  async get(store, key) {
@@ -1,5 +1,5 @@
1
1
  import { mkdir, stat } from 'node:fs/promises';
2
- import { createDeviceProjection } from '../Compatibility/legacy-store/device.js';
2
+ import { createDeviceProjection, hasInlineDeviceAccount } from '../Compatibility/legacy-store/device.js';
3
3
  import { projectNativeStore } from '../Compatibility/legacy-store/native-projection.js';
4
4
  import { initAuthCreds } from './generics.js';
5
5
  import { useBridgeStore } from './use-bridge-store.js';
@@ -27,11 +27,16 @@ const DEVICE_RECORDS = ['device', 'account'];
27
27
  */
28
28
  const hydrateFromStore = async (store, creds) => {
29
29
  const projection = createDeviceProjection(creds);
30
+ let inlineAccount = false;
30
31
  for (const record of DEVICE_RECORDS) {
32
+ if (record === 'account' && inlineAccount)
33
+ continue;
31
34
  const payload = await store.get(DEVICE_STORE, record);
32
35
  if (!payload)
33
36
  continue;
34
37
  try {
38
+ if (record === 'device')
39
+ inlineAccount = hasInlineDeviceAccount(payload);
35
40
  projection.prepare(record, payload)();
36
41
  }
37
42
  catch {
@@ -69,13 +69,26 @@ export const assertNodeErrorFree = (node) => {
69
69
  });
70
70
  }
71
71
  };
72
- export const reduceBinaryNodeToDictionary = (node, tag) => getBinaryNodeChildren(node, tag).reduce((dictionary, { attrs }) => {
73
- if (typeof attrs.name === 'string')
74
- dictionary[attrs.name] = attrs.value || attrs.config_value;
75
- else
76
- dictionary[attrs.config_code] = attrs.value || attrs.config_value;
72
+ export const reduceBinaryNodeToDictionary = (node, tag) => {
73
+ const dictionary = {};
74
+ const content = node?.content;
75
+ if (!Array.isArray(content))
76
+ return dictionary;
77
+ // One pass, without the intermediate child list.
78
+ for (let index = 0; index < content.length; index++) {
79
+ const item = content[index];
80
+ if (item === undefined && !(index in content))
81
+ continue;
82
+ if (item.tag !== tag)
83
+ continue;
84
+ const { attrs } = item;
85
+ if (typeof attrs.name === 'string')
86
+ dictionary[attrs.name] = attrs.value || attrs.config_value;
87
+ else
88
+ dictionary[attrs.config_code] = attrs.value || attrs.config_value;
89
+ }
77
90
  return dictionary;
78
- }, {});
91
+ };
79
92
  export const getBinaryNodeMessages = ({ content }) => {
80
93
  const messages = [];
81
94
  if (Array.isArray(content)) {
@@ -95,13 +108,33 @@ export function binaryNodeToString(node, i = 0) {
95
108
  return tabs(i) + node;
96
109
  if (node instanceof Uint8Array)
97
110
  return tabs(i) + hexEncode(node);
98
- if (Array.isArray(node))
99
- return node.map(child => tabs(i + 1) + binaryNodeToString(child, i + 1)).join('\n');
111
+ if (Array.isArray(node)) {
112
+ // Same text as `node.map(...).join('\n')`, a hole included (it renders
113
+ // empty), built in one pass without the intermediate array.
114
+ const indent = tabs(i + 1);
115
+ let out = '';
116
+ for (let index = 0; index < node.length; index++) {
117
+ if (index > 0)
118
+ out += '\n';
119
+ if (index in node)
120
+ out += indent + binaryNodeToString(node[index], i + 1);
121
+ }
122
+ return out;
123
+ }
100
124
  const children = binaryNodeToString(node.content, i + 1);
101
- const tag = `<${node.tag} ${Object.entries(node.attrs || {})
102
- .filter(([, value]) => value !== undefined)
103
- .map(([key, value]) => `${key}='${value}'`)
104
- .join(' ')}`;
125
+ // Same text as filtering `Object.entries(attrs)` and joining, without the
126
+ // entry tuples and the two arrays: this formats every stanza a debug log
127
+ // prints, and large group stanzas carry an attrs object per participant.
128
+ const attrs = node.attrs || {};
129
+ let tag = `<${node.tag} `;
130
+ let separator = '';
131
+ for (const key of Object.keys(attrs)) {
132
+ const value = attrs[key];
133
+ if (value === undefined)
134
+ continue;
135
+ tag += `${separator}${key}='${value}'`;
136
+ separator = ' ';
137
+ }
105
138
  const content = children ? `>\n${children}\n${tabs(i)}</${node.tag}>` : '/>';
106
139
  return tag + content;
107
140
  }
@@ -28,15 +28,35 @@ export const getServerFromDomainType = (initialServer, domainType) => {
28
28
  export const jidEncode = (user, server, device, agent) => {
29
29
  return `${user || ''}${agent ? `_${agent}` : ''}${device ? `:${device}` : ''}@${server}`;
30
30
  };
31
+ /** Index of `char` in `text[from, limit)`, or -1. */
32
+ const indexBefore = (text, char, from, limit) => {
33
+ const index = text.indexOf(char, from);
34
+ return index < limit ? index : -1;
35
+ };
36
+ /** Where a part that starts at `from` ends: the next `char` before `limit`, else `limit`. */
37
+ const endBefore = (text, char, from, limit) => {
38
+ const index = indexBefore(text, char, from, limit);
39
+ return index < 0 ? limit : index;
40
+ };
31
41
  export const jidDecode = (jid) => {
32
42
  const sepIdx = typeof jid === 'string' ? jid.indexOf('@') : -1;
33
43
  if (sepIdx < 0) {
34
44
  return undefined;
35
45
  }
36
- const server = jid.slice(sepIdx + 1);
37
- const userCombined = jid.slice(0, sepIdx);
38
- const [userAgent, device] = userCombined.split(':');
39
- const [user, agent] = userAgent.split('_');
46
+ const value = jid;
47
+ const server = value.slice(sepIdx + 1);
48
+ // Same pieces as splitting the pre-`@` half on ':' and then on '_' and
49
+ // keeping the first two parts of each, located by index instead: this runs
50
+ // for every JID on the message pipeline, and the splits allocated two
51
+ // arrays plus a string per part only to read two of them.
52
+ const colonIdx = indexBefore(value, ':', 0, sepIdx);
53
+ const userAgentEnd = colonIdx < 0 ? sepIdx : colonIdx;
54
+ const device = colonIdx < 0 ? undefined : value.slice(colonIdx + 1, endBefore(value, ':', colonIdx + 1, sepIdx));
55
+ const underscoreIdx = indexBefore(value, '_', 0, userAgentEnd);
56
+ const user = value.slice(0, underscoreIdx < 0 ? userAgentEnd : underscoreIdx);
57
+ const agent = underscoreIdx < 0
58
+ ? undefined
59
+ : value.slice(underscoreIdx + 1, endBefore(value, '_', underscoreIdx + 1, userAgentEnd));
40
60
  let domainType = WAJIDDomains.WHATSAPP;
41
61
  if (server === 'lid') {
42
62
  domainType = WAJIDDomains.LID;
@@ -57,8 +77,6 @@ export const jidDecode = (jid) => {
57
77
  device: device ? +device : undefined
58
78
  };
59
79
  };
60
- const CHAR_DEVICE_SEP = 58; // ':'
61
- const CHAR_AGENT_SEP = 95; // '_'
62
80
  /**
63
81
  * Index at which the user component ends, given the index of the '@'.
64
82
  *
@@ -66,15 +84,13 @@ const CHAR_AGENT_SEP = 95; // '_'
66
84
  * '_', so the user always runs to whichever of ':' or '_' comes first, and to
67
85
  * the '@' when neither is there. Locating that boundary answers both callers
68
86
  * below without the intermediate arrays and result object `jidDecode` allocates.
87
+ * Two native searches rather than a per-character loop.
69
88
  */
70
89
  const userEndBefore = (jid, sepIdx) => {
71
- for (let i = 0; i < sepIdx; i++) {
72
- const code = jid.charCodeAt(i);
73
- if (code === CHAR_DEVICE_SEP || code === CHAR_AGENT_SEP) {
74
- return i;
75
- }
76
- }
77
- return sepIdx;
90
+ const colonIdx = indexBefore(jid, ':', 0, sepIdx);
91
+ const end = colonIdx < 0 ? sepIdx : colonIdx;
92
+ const underscoreIdx = indexBefore(jid, '_', 0, end);
93
+ return underscoreIdx < 0 ? end : underscoreIdx;
78
94
  };
79
95
  /** As above, or -1 when the JID has no server part: the case `jidDecode` reports as `undefined`. */
80
96
  const userEnd = (jid) => {
@@ -94,14 +110,10 @@ export const areJidsSameUser = (jid1, jid2) => {
94
110
  if (end < 0) {
95
111
  return true;
96
112
  }
97
- const left = jid1;
113
+ // Both users span `[0, end)`, so they match exactly when one JID starts with
114
+ // the other's user.
98
115
  const right = jid2;
99
- for (let i = 0; i < end; i++) {
100
- if (left.charCodeAt(i) !== right.charCodeAt(i)) {
101
- return false;
102
- }
103
- }
104
- return true;
116
+ return jid1.startsWith(right.slice(0, end));
105
117
  };
106
118
  export const isJidMetaAI = (jid) => jid?.endsWith('@bot');
107
119
  export const isPnUser = (jid) => jid?.endsWith('@s.whatsapp.net');
@@ -121,6 +121,8 @@ export type HostSocketConfig = {
121
121
  browser?: [os: string, browser: string, version: string];
122
122
  pushName?: string;
123
123
  emitOwnEvents?: boolean;
124
+ /** Additional exact HTTPS authorities for static media; redirects remain disabled. */
125
+ additionalStaticMediaHosts?: readonly string[];
124
126
  customUploadHosts?: Array<{
125
127
  hostname: string;
126
128
  maxContentLengthBytes: number;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@oxidezap/baileyrs",
3
3
  "type": "module",
4
- "version": "0.3.13",
4
+ "version": "0.3.15",
5
5
  "description": "A Rust-powered WhatsApp Web library for JavaScript, with a Baileys-compatible API",
6
6
  "keywords": [
7
7
  "whatsapp",
@@ -74,10 +74,10 @@
74
74
  "compat:layers": "node scripts/compatibility/check-layer-boundaries.ts",
75
75
  "check:host-boundaries": "node scripts/check-host-boundaries.ts",
76
76
  "example": "node ./Example/example.ts",
77
- "format": "oxfmt src Example",
78
- "format:check": "oxfmt --check src Example",
77
+ "format": "oxfmt src Example bench benchmarks vitest.config.ts",
78
+ "format:check": "oxfmt --check src Example && oxfmt --check bench benchmarks vitest.config.ts",
79
79
  "lint": "tsc && oxlint",
80
- "lint:fix": "oxlint --fix && oxfmt src Example",
80
+ "lint:fix": "oxlint --fix && oxfmt src Example bench benchmarks vitest.config.ts",
81
81
  "prepack": "npm run build && node scripts/check-pack.ts",
82
82
  "prepublishOnly": "node scripts/check-registry-deps.mjs",
83
83
  "prepare": "npm run build",
@@ -90,32 +90,39 @@
90
90
  "test:packaged": "node scripts/packaged-upstream-alias.mjs",
91
91
  "typecheck:compat-auditor": "npm run build --silent && npm run compat:check-waproto --silent && npm run compat:layers --silent && npm run typecheck:compat-declarations --silent",
92
92
  "test:e2e": "NODE_TLS_REJECT_UNAUTHORIZED=0 ADV_SECRET_KEY=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= node --expose-gc --test --test-concurrency=1 ./src/__tests__/e2e/*.test-e2e.ts ./scripts/compatibility/__tests__/*.test-e2e.ts",
93
- "typecheck:compat-declarations": "node node_modules/typescript-compat-auditor/bin/tsc -p scripts/compatibility/tsconfig.json"
93
+ "typecheck:compat-declarations": "node node_modules/typescript-compat-auditor/bin/tsc -p scripts/compatibility/tsconfig.json",
94
+ "bench": "vitest bench --run",
95
+ "bench:e2e": "BENCH_SUITE=e2e vitest bench --run",
96
+ "typecheck:bench": "tsc -p bench/tsconfig.json"
94
97
  },
95
98
  "dependencies": {
96
- "@oxidezap/whatsapp-rust-bridge": "0.26.4",
99
+ "@oxidezap/whatsapp-rust-bridge": "0.26.8",
97
100
  "events": "^3.3.0",
98
- "fs-native-extensions": "1.5.2",
101
+ "fs-native-extensions": "1.5.3",
99
102
  "long": "^5.3.2"
100
103
  },
101
104
  "devDependencies": {
102
105
  "@bufbuild/protobuf": "^2.13.0",
106
+ "@codspeed/vitest-plugin": "6.1.1",
103
107
  "@hapi/boom": "^10.0.1",
104
108
  "@types/node": "^26.1.1",
105
109
  "baileys": "7.0.0-rc14",
106
110
  "jimp": "^1.6.0",
107
111
  "link-preview-js": "^5.0.0",
108
112
  "music-metadata": "^12.2.2",
109
- "oxfmt": "^0.74.0",
110
- "oxlint": "1.89.0",
113
+ "oxfmt": "^0.77.0",
114
+ "oxlint": "1.92.0",
111
115
  "pino": "^10.3.1",
112
116
  "pino-pretty": "^13.1.3",
113
- "pkg-pr-new": "^0.0.91",
117
+ "pkg-pr-new": "^0.0.93",
114
118
  "protobufjs": "^8.8.0",
115
119
  "tsc-esm-fix": "^3.1.2",
116
120
  "typescript": "^7.0.2",
117
121
  "typescript-compat-auditor": "npm:typescript@6.0.3",
118
- "wrangler": "4.152.0"
122
+ "undici": "7.30.1",
123
+ "vite": "8.3.6",
124
+ "vitest": "5.1.0",
125
+ "wrangler": "4.158.0"
119
126
  },
120
127
  "peerDependencies": {
121
128
  "@hapi/boom": "^9.1.0 || ^10.0.0",