kage-baileys 25.3.31 → 25.3.34

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.
@@ -286,7 +286,8 @@ async function sendA2UIWidget(
286
286
  type = "im_a2ui",
287
287
  wrapped = true,
288
288
  singleScreen = false,
289
- header
289
+ header,
290
+ additionalNodes = []
290
291
  } = {}
291
292
  ) {
292
293
  if (!client) throw new Error("Socket is required");
@@ -349,9 +350,14 @@ async function sendA2UIWidget(
349
350
  },
350
351
  { quoted }
351
352
  );
353
+ const customNodes = Array.isArray(additionalNodes) ? additionalNodes : [];
354
+ const hasCustomBizNode = customNodes.some((node) => node?.tag === "biz" || node?.tag === "hsm");
355
+ const finalAdditionalNodes = hasCustomBizNode
356
+ ? customNodes
357
+ : [getBizBinaryNode(msg.message), ...customNodes];
352
358
  await client.relayMessage(msg.key.remoteJid, msg.message, {
353
359
  messageId: msg.key.id,
354
- additionalNodes: [getBizBinaryNode(msg.message)]
360
+ additionalNodes: finalAdditionalNodes
355
361
  });
356
362
  return msg;
357
363
  }
@@ -870,13 +870,17 @@ class Button extends BaseBuilder {
870
870
  { ...options }
871
871
  );
872
872
  }
873
- async send(jid, { ...options } = {}) {
873
+ async send(jid, { additionalNodes = [], ...options } = {}) {
874
874
  const msg = await this.build(jid, options);
875
- const bizNode = getBizBinaryNode(msg.message);
875
+ const customNodes = Array.isArray(additionalNodes) ? additionalNodes : [];
876
+ const hasCustomBizNode = customNodes.some((node) => node?.tag === "biz" || node?.tag === "hsm");
877
+ const finalAdditionalNodes = hasCustomBizNode
878
+ ? customNodes
879
+ : [getBizBinaryNode(msg.message), ...customNodes];
876
880
  await this.#client.relayMessage(msg.key.remoteJid, msg.message, {
881
+ ...options,
877
882
  messageId: msg.key.id,
878
- additionalNodes: [bizNode],
879
- ...options
883
+ additionalNodes: finalAdditionalNodes
880
884
  });
881
885
  return msg;
882
886
  }
@@ -135,15 +135,19 @@ class ButtonV2 extends BaseBuilder {
135
135
  return msg;
136
136
  }
137
137
 
138
- async send(jid, { ...options } = {}) {
138
+ async send(jid, { additionalNodes = [], ...options } = {}) {
139
139
  if (this._buttons.length < 1) throw new Error('ButtonV2 requires at least one button');
140
140
  const msg = await this.build(jid, options);
141
- const bizNode = getBizBinaryNode(msg.message);
141
+ const customNodes = Array.isArray(additionalNodes) ? additionalNodes : [];
142
+ const hasCustomBizNode = customNodes.some((node) => node?.tag === 'biz' || node?.tag === 'hsm');
143
+ const finalAdditionalNodes = hasCustomBizNode
144
+ ? customNodes
145
+ : [getBizBinaryNode(msg.message), ...customNodes];
142
146
 
143
147
  await this.#client.relayMessage(msg.key.remoteJid, msg.message, {
144
- messageId: msg.key.id,
145
- additionalNodes: [bizNode],
146
148
  ...options,
149
+ messageId: msg.key.id,
150
+ additionalNodes: finalAdditionalNodes,
147
151
  });
148
152
  return msg;
149
153
  }
@@ -139,15 +139,19 @@ class Carousel extends BaseBuilder {
139
139
  { ...options }
140
140
  );
141
141
  }
142
- async send(jid, { ...options } = {}) {
142
+ async send(jid, { additionalNodes = [], ...options } = {}) {
143
143
  if (this._cards.length === 0)
144
144
  throw new Error("Carousel requires at least one card (use addCard())");
145
145
  const msg = this.build(jid, options);
146
- const bizNode = getBizBinaryNode(msg.message);
146
+ const customNodes = Array.isArray(additionalNodes) ? additionalNodes : [];
147
+ const hasCustomBizNode = customNodes.some((node) => node?.tag === "biz" || node?.tag === "hsm");
148
+ const finalAdditionalNodes = hasCustomBizNode
149
+ ? customNodes
150
+ : [getBizBinaryNode(msg.message), ...customNodes];
147
151
  await this.#client.relayMessage(msg.key.remoteJid, msg.message, {
152
+ ...options,
148
153
  messageId: msg.key.id,
149
- additionalNodes: [bizNode],
150
- ...options
154
+ additionalNodes: finalAdditionalNodes
151
155
  });
152
156
  return msg;
153
157
  }
@@ -177,7 +177,7 @@ export const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connect
177
177
  * Use to ensure your WA connection is always on the latest version
178
178
  */
179
179
  export const fetchLatestBaileysVersion = async (options = {}) => {
180
- const URL = 'https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/index.ts';
180
+ const URL = 'https://raw.githubusercontent.com/xrljosedv/kage-baileys/master/src/Defaults/index.ts';
181
181
  try {
182
182
  const response = await fetch(URL, {
183
183
  dispatcher: options.dispatcher,
@@ -5,7 +5,7 @@ import { proto } from '../../WAProto/index.js';
5
5
  import { initAuthCreds } from './auth-utils.js';
6
6
  import { BufferJSON } from './generics.js';
7
7
  // We need to lock files due to the fact that we are using async functions to read and write files
8
- // https://github.com/WhiskeySockets/Baileys/issues/794
8
+ // https://github.com/xrljosedv/kage-baileys/issues/794
9
9
  // https://github.com/nodejs/node/issues/26338
10
10
  // Use a Map to store mutexes for each file path
11
11
  const fileLocks = new Map();
@@ -12,4 +12,5 @@ export declare const reduceBinaryNodeToDictionary: (node: BinaryNode, tag: strin
12
12
  };
13
13
  export declare const getBinaryNodeMessages: ({ content }: BinaryNode) => proto.WebMessageInfo[];
14
14
  export declare function binaryNodeToString(node: BinaryNode | BinaryNode['content'], i?: number): string;
15
- //# sourceMappingURL=generic-utils.d.ts.map
15
+ export declare const getBizBinaryNode: (message: proto.IMessage | Record<string, unknown>) => BinaryNode;
16
+ //# sourceMappingURL=generic-utils.d.ts.map
@@ -1,5 +1,6 @@
1
1
  import { Boom } from '@hapi/boom';
2
2
  import { proto } from '../../WAProto/index.js';
3
+ import { randomBytes } from 'node:crypto';
3
4
  import {} from './types.js';
4
5
  // some extra useful utilities
5
6
  const indexCache = new WeakMap();
@@ -110,4 +111,155 @@ export function binaryNodeToString(node, i = 0) {
110
111
  const content = children ? `>\n${children}\n${tabs(i)}</${node.tag}>` : '/>';
111
112
  return tag + content;
112
113
  }
113
- //# sourceMappingURL=generic-utils.js.map
114
+ const BIZ_FLOW_NAMES = new Set([
115
+ 'mpm',
116
+ 'cta_catalog',
117
+ 'send_location',
118
+ 'call_permission_request',
119
+ 'wa_payment_transaction_details',
120
+ 'automated_greeting_message_view_catalog',
121
+ ]);
122
+
123
+ const BIZ_NATIVE_FLOW_ATTRIBUTES = { type: 'native_flow', v: '1' };
124
+
125
+ const createMixedNativeFlowNode = () => ({
126
+ tag: 'interactive',
127
+ attrs: { ...BIZ_NATIVE_FLOW_ATTRIBUTES },
128
+ content: [
129
+ {
130
+ tag: 'native_flow',
131
+ attrs: { v: '9', name: 'mixed' },
132
+ },
133
+ ],
134
+ });
135
+
136
+ const createListNode = () => ({
137
+ tag: 'list',
138
+ attrs: { v: '2', type: 'product_list' },
139
+ });
140
+
141
+ const unwrapBizMessage = (input) => {
142
+ let message = input;
143
+ const visited = new Set();
144
+ const wrappers = [
145
+ 'ephemeralMessage',
146
+ 'viewOnceMessage',
147
+ 'viewOnceMessageV2',
148
+ 'viewOnceMessageV2Extension',
149
+ 'documentWithCaptionMessage',
150
+ 'editedMessage',
151
+ 'groupMentionedMessage',
152
+ 'groupStatusMessage',
153
+ 'groupStatusMessageV2',
154
+ 'botInvokeMessage',
155
+ 'botForwardedMessage',
156
+ 'deviceSentMessage',
157
+ ];
158
+
159
+ while (message && typeof message === 'object' && !visited.has(message)) {
160
+ visited.add(message);
161
+ let next;
162
+ for (const wrapper of wrappers) {
163
+ const candidate = message[wrapper]?.message;
164
+ if (candidate && typeof candidate === 'object') {
165
+ next = candidate;
166
+ break;
167
+ }
168
+ }
169
+ if (!next) break;
170
+ message = next;
171
+ }
172
+
173
+ return message && typeof message === 'object' ? message : {};
174
+ };
175
+
176
+ /**
177
+ * Creates the companion business binary node required by WhatsApp for
178
+ * interactive, native-flow, carousel, button, template and list messages.
179
+ *
180
+ * @param {object} input A WAProto message or a message payload.
181
+ * @returns {import('./types.js').BinaryNode}
182
+ */
183
+ export const getBizBinaryNode = (input) => {
184
+ const message = unwrapBizMessage(input?.message ?? input);
185
+ const interactiveMessage = message.interactiveMessage;
186
+ const carouselCards = interactiveMessage?.carouselMessage?.cards;
187
+ const cardFlowMessage = Array.isArray(carouselCards)
188
+ ? carouselCards.find((card) => card?.nativeFlowMessage)?.nativeFlowMessage
189
+ : undefined;
190
+ const flowMessage = interactiveMessage?.nativeFlowMessage || cardFlowMessage;
191
+ const flowButtons = Array.isArray(flowMessage?.buttons) ? flowMessage.buttons : [];
192
+ const firstButtonName = flowButtons.find((button) => typeof button?.name === 'string')?.name;
193
+ const bizAttributes = {
194
+ actual_actors: '2',
195
+ host_storage: '2',
196
+ privacy_mode_ts: String(Math.floor(Date.now() / 1000)),
197
+ };
198
+ const qualityControlNode = {
199
+ tag: 'quality_control',
200
+ attrs: {
201
+ decision_id: randomBytes(20).toString('hex'),
202
+ source_type: 'third_party',
203
+ },
204
+ content: [
205
+ {
206
+ tag: 'decision_source',
207
+ attrs: { value: 'df' },
208
+ },
209
+ ],
210
+ };
211
+
212
+ if (firstButtonName === 'review_and_pay' || firstButtonName === 'payment_info') {
213
+ return {
214
+ tag: 'biz',
215
+ attrs: {
216
+ ...bizAttributes,
217
+ native_flow_name: firstButtonName === 'review_and_pay' ? 'order_details' : 'payment_info',
218
+ },
219
+ content: [qualityControlNode],
220
+ };
221
+ }
222
+
223
+ if (firstButtonName && BIZ_FLOW_NAMES.has(firstButtonName)) {
224
+ return {
225
+ tag: 'biz',
226
+ attrs: bizAttributes,
227
+ content: [
228
+ {
229
+ tag: 'interactive',
230
+ attrs: { ...BIZ_NATIVE_FLOW_ATTRIBUTES },
231
+ content: [
232
+ {
233
+ tag: 'native_flow',
234
+ attrs: { v: '2', name: firstButtonName },
235
+ },
236
+ ],
237
+ },
238
+ qualityControlNode,
239
+ ],
240
+ };
241
+ }
242
+
243
+ if (flowMessage || message.buttonsMessage || message.templateMessage) {
244
+ return {
245
+ tag: 'biz',
246
+ attrs: bizAttributes,
247
+ content: [createMixedNativeFlowNode(), qualityControlNode],
248
+ };
249
+ }
250
+
251
+ if (message.listMessage) {
252
+ return {
253
+ tag: 'biz',
254
+ attrs: bizAttributes,
255
+ content: [createListNode(), qualityControlNode],
256
+ };
257
+ }
258
+
259
+ return {
260
+ tag: 'biz',
261
+ attrs: bizAttributes,
262
+ content: [qualityControlNode],
263
+ };
264
+ };
265
+ //# sourceMappingURL=generic-utils.js.map
package/package.json CHANGED
@@ -1,15 +1,15 @@
1
1
  {
2
2
  "name": "kage-baileys",
3
3
  "type": "module",
4
- "version": "25.3.31",
4
+ "version": "25.3.34",
5
5
  "description": "A WebSockets library for interacting with WhatsApp Web",
6
6
  "keywords": [
7
7
  "whatsapp",
8
8
  "automation"
9
9
  ],
10
- "homepage": "https://github.com/WhiskeySockets/Baileys/",
10
+ "homepage": "https://github.com/xrljosedv/kage-baileys/",
11
11
  "repository": {
12
- "url": "git@github.com:WhiskeySockets/Baileys.git"
12
+ "url": "git@github.com:xrljosedv/kage-baileys.git"
13
13
  },
14
14
  "license": "MIT",
15
15
  "author": "Rajeh Taher",
@@ -21,25 +21,21 @@
21
21
  "engine-requirements.js",
22
22
  "extras/**/*",
23
23
  "helpers/**/*",
24
- "licenses/**/*"
24
+ "licenses/**/*",
25
+ "scripts/**/*",
26
+ "test/**/*"
25
27
  ],
26
28
  "scripts": {
27
- "build:all": "npm run build && npm run build:docs",
28
- "build:docs": "typedoc",
29
- "build": "tsc -P tsconfig.build.json && tsc-esm-fix --tsconfig=tsconfig.build.json --ext=.js",
29
+ "build:all": "npm run check",
30
+ "build": "npm run check",
31
+ "check": "node ./scripts/verify-package.mjs",
30
32
  "changelog:last": "conventional-changelog -p angular -r 2",
31
33
  "changelog:preview": "conventional-changelog -p angular -u",
32
34
  "changelog:update": "conventional-changelog -p angular -i CHANGELOG.md -s -r 0",
33
- "example": "tsx ./Example/example.ts",
34
35
  "gen:protobuf": "sh WAProto/GenerateStatics.sh",
35
- "format": "prettier --write \"src/**/*.{ts,js,json,md}\"",
36
- "lint": "tsc && eslint src --ext .js,.ts",
37
- "lint:fix": "npm run format && npm run lint -- --fix",
38
- "preinstall": "node ./engine-requirements.js",
36
+ "lint": "npm run check",
39
37
  "release": "release-it",
40
- "test": "node --experimental-vm-modules ./node_modules/.bin/jest --testMatch '**/*.test.ts'",
41
- "test:e2e": "NODE_TLS_REJECT_UNAUTHORIZED=0 node --experimental-vm-modules ./node_modules/.bin/jest --runInBand --forceExit --testMatch '**/*.test-e2e.ts'",
42
- "update:version": "tsx ./scripts/update-version.ts"
38
+ "test": "node --test"
43
39
  },
44
40
  "dependencies": {
45
41
  "@adiwajshing/keyed-db": "^0.2.4",
@@ -0,0 +1,63 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
7
+ const sourceRoots = ['lib', 'WAProto', 'extras', 'helpers', 'scripts', 'test'];
8
+ const sourceExtensions = new Set(['.js', '.mjs', '.cjs']);
9
+ const failures = [];
10
+ const checked = [];
11
+
12
+ function walk(directory) {
13
+ if (!existsSync(directory)) return;
14
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
15
+ if (entry.name === 'node_modules' || entry.name === '.git') continue;
16
+ const file = path.join(directory, entry.name);
17
+ if (entry.isDirectory()) walk(file);
18
+ else if (sourceExtensions.has(path.extname(entry.name))) checked.push(file);
19
+ }
20
+ }
21
+
22
+ function resolveLocalImport(sourceFile, specifier) {
23
+ const target = path.resolve(path.dirname(sourceFile), specifier);
24
+ const candidates = [target];
25
+ if (!path.extname(target)) {
26
+ candidates.push(`${target}.js`, `${target}.mjs`, `${target}.cjs`, `${target}.json`);
27
+ }
28
+ candidates.push(path.join(target, 'index.js'), path.join(target, 'index.mjs'), path.join(target, 'index.cjs'));
29
+ return candidates.find((candidate) => existsSync(candidate) && statSync(candidate).isFile());
30
+ }
31
+
32
+ for (const directory of sourceRoots) walk(path.join(root, directory));
33
+
34
+ for (const file of checked) {
35
+ const result = spawnSync(process.execPath, ['--check', file], { encoding: 'utf8' });
36
+ if (result.status !== 0) {
37
+ failures.push(`${path.relative(root, file)}: ${result.stderr || result.stdout || 'syntax check failed'}`);
38
+ continue;
39
+ }
40
+
41
+ const source = readFileSync(file, 'utf8');
42
+ const importPattern = /(?:\bfrom\s*|\bimport\s*\(\s*|\brequire\s*\(\s*)['"](\.{1,2}\/[^'"]+)['"]/g;
43
+ for (const match of source.matchAll(importPattern)) {
44
+ if (!resolveLocalImport(file, match[1])) {
45
+ failures.push(`${path.relative(root, file)}: unresolved local import ${match[1]}`);
46
+ }
47
+ }
48
+ }
49
+
50
+ const packageJson = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8'));
51
+ for (const field of ['main', 'types']) {
52
+ if (packageJson[field] && !existsSync(path.join(root, packageJson[field]))) {
53
+ failures.push(`package.json: ${field} target does not exist: ${packageJson[field]}`);
54
+ }
55
+ }
56
+
57
+ if (failures.length) {
58
+ console.error(`Package check failed (${failures.length} issue${failures.length === 1 ? '' : 's'}):`);
59
+ for (const failure of failures) console.error(`- ${failure}`);
60
+ process.exitCode = 1;
61
+ } else {
62
+ console.log(`Package check passed: ${checked.length} JavaScript files; syntax and local import paths are valid.`);
63
+ }
@@ -0,0 +1,37 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { getBizBinaryNode } from '../lib/WABinary/index.js';
4
+
5
+ test('creates the mixed native-flow node for interactive buttons', () => {
6
+ const node = getBizBinaryNode({ interactiveMessage: { nativeFlowMessage: { buttons: [{ name: 'quick_reply' }] } } });
7
+ assert.equal(node.tag, 'biz');
8
+ assert.equal(node.content[0].tag, 'interactive');
9
+ assert.deepEqual(node.content[0].content[0].attrs, { v: '9', name: 'mixed' });
10
+ assert.equal(node.content[1].tag, 'quality_control');
11
+ });
12
+
13
+ test('creates the list companion node for list messages', () => {
14
+ const node = getBizBinaryNode({ listMessage: {} });
15
+ assert.deepEqual(node.content[0], { tag: 'list', attrs: { v: '2', type: 'product_list' } });
16
+ });
17
+
18
+ test('uses the dedicated native-flow node for supported special flows', () => {
19
+ const node = getBizBinaryNode({ interactiveMessage: { nativeFlowMessage: { buttons: [{ name: 'send_location' }] } } });
20
+ assert.equal(node.content[0].content[0].attrs.name, 'send_location');
21
+ assert.equal(node.content[0].content[0].attrs.v, '2');
22
+ });
23
+
24
+ test('maps review_and_pay to the order_details business flow', () => {
25
+ const node = getBizBinaryNode({ interactiveMessage: { nativeFlowMessage: { buttons: [{ name: 'review_and_pay' }] } } });
26
+ assert.equal(node.attrs.native_flow_name, 'order_details');
27
+ });
28
+
29
+ test('finds native-flow data inside carousel cards', () => {
30
+ const node = getBizBinaryNode({ interactiveMessage: { carouselMessage: { cards: [{ nativeFlowMessage: { buttons: [{ name: 'mpm' }] } }] } } });
31
+ assert.equal(node.content[0].content[0].attrs.name, 'mpm');
32
+ });
33
+
34
+ test('unwraps view-once messages before selecting the business node', () => {
35
+ const node = getBizBinaryNode({ viewOnceMessage: { message: { buttonsMessage: {} } } });
36
+ assert.equal(node.content[0].content[0].attrs.name, 'mixed');
37
+ });