@jexkcode/baileys 1.2.0 → 1.3.0
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.
- package/README.md +29 -0
- package/lib/Builders/A2UI.d.ts +275 -0
- package/lib/Builders/A2UI.js +422 -0
- package/lib/Socket/index.js +23 -0
- package/lib/Utils/auto-reconnect.d.ts +54 -0
- package/lib/Utils/auto-reconnect.js +214 -0
- package/lib/Utils/chat-export.d.ts +52 -0
- package/lib/Utils/chat-export.js +248 -0
- package/lib/Utils/index.d.ts +7 -0
- package/lib/Utils/index.js +7 -0
- package/lib/Utils/message-search.d.ts +44 -0
- package/lib/Utils/message-search.js +250 -0
- package/lib/Utils/messages.js +86 -0
- package/lib/Utils/mini-app.d.ts +93 -0
- package/lib/Utils/mini-app.js +447 -0
- package/lib/Utils/mock-socket.d.ts +60 -0
- package/lib/Utils/mock-socket.js +253 -0
- package/lib/Utils/transcribe.d.ts +12 -0
- package/lib/Utils/transcribe.js +107 -0
- package/lib/Utils/username.d.ts +3 -0
- package/lib/Utils/username.js +73 -0
- package/lib/index.d.ts +1 -0
- package/lib/index.js +1 -0
- package/package.json +1 -1
|
@@ -0,0 +1,422 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/Builders/A2UI.js — A2UI (Bloks) widget builder + sender
|
|
3
|
+
*
|
|
4
|
+
* Part of @japofc/baileys. Builds the flat `components` array A2UI/Bloks
|
|
5
|
+
* expects (id-referencing tree: Column/Row hold `children`, Card/Button hold
|
|
6
|
+
* `child`, Modal holds `trigger`/`content`) and sends it as an
|
|
7
|
+
* `interactiveMessage.bloksWidget` via the same `getBizBinaryNode()` path
|
|
8
|
+
* Button/ButtonV2 use, so the wire-level <biz>/<native_flow> node always
|
|
9
|
+
* matches the actual button names sent — no more hand-rolled duplicate of
|
|
10
|
+
* that logic living outside the library.
|
|
11
|
+
*
|
|
12
|
+
* See MessageBuilder.js's `Button.setBloksWidget()` for the declarative
|
|
13
|
+
* (nested-tree) alternative to this imperative (id-returning-factory) API;
|
|
14
|
+
* both produce the same wire format and can be mixed freely.
|
|
15
|
+
*/
|
|
16
|
+
"use strict";
|
|
17
|
+
|
|
18
|
+
import crypto from "crypto";
|
|
19
|
+
import { generateWAMessageFromContent, prepareWAMessageMedia } from "../Utils/messages.js";
|
|
20
|
+
import { getBizBinaryNode } from "../WABinary/index.js";
|
|
21
|
+
|
|
22
|
+
class A2UI {
|
|
23
|
+
constructor({ catalogId = "https://a2ui.org/specification/v0_9/catalogs/basic/catalog.json", version = "v0.9" } = {}) {
|
|
24
|
+
this._version = version;
|
|
25
|
+
this._catalogId = catalogId;
|
|
26
|
+
this._components = new Map();
|
|
27
|
+
this._counter = 0;
|
|
28
|
+
this._rootChildren = [];
|
|
29
|
+
}
|
|
30
|
+
// JAP@Fix (§2.35 / v2.4.7): the auto-id was a bare counter, so a caller-supplied id that
|
|
31
|
+
// happened to look like a generated one (`text_0`) made the very next auto-id collide and
|
|
32
|
+
// #reg() threw `Component id "text_0" already used` on a perfectly valid widget. Skip ids
|
|
33
|
+
// that are already taken instead of handing back a known-duplicate.
|
|
34
|
+
#nextId(prefix) {
|
|
35
|
+
let id;
|
|
36
|
+
do {
|
|
37
|
+
id = `${prefix}_${(this._counter++).toString(36)}`;
|
|
38
|
+
} while (this._components.has(id) || id === 'root');
|
|
39
|
+
return id;
|
|
40
|
+
}
|
|
41
|
+
#reg(id, component, extra = {}) {
|
|
42
|
+
id ??= this.#nextId(component.toLowerCase());
|
|
43
|
+
if (id === "root") throw new Error(`Component id "root" is reserved for the implicit root wrapper`);
|
|
44
|
+
if (this._components.has(id)) throw new Error(`Component id "${id}" already used`);
|
|
45
|
+
this._components.set(id, { id, component, ...extra });
|
|
46
|
+
return id;
|
|
47
|
+
}
|
|
48
|
+
text(text, { id, variant = "body" } = {}) {
|
|
49
|
+
return this.#reg(id, "Text", { text, variant });
|
|
50
|
+
}
|
|
51
|
+
image(url, { id, variant, fit = "cover" } = {}) {
|
|
52
|
+
return this.#reg(id, "Image", { url, ...(variant ? { variant } : {}), fit });
|
|
53
|
+
}
|
|
54
|
+
video(url, { id } = {}) {
|
|
55
|
+
return this.#reg(id, "Video", { url });
|
|
56
|
+
}
|
|
57
|
+
checkbox(label, { id, value = false } = {}) {
|
|
58
|
+
return this.#reg(id, "CheckBox", { label, value });
|
|
59
|
+
}
|
|
60
|
+
textField(label, { id, variant = "text" } = {}) {
|
|
61
|
+
return this.#reg(id, "TextField", { label, variant });
|
|
62
|
+
}
|
|
63
|
+
button(childId, { id, variant = "primary", action } = {}) {
|
|
64
|
+
if (!childId) throw new TypeError("button(childId) requires the id of a child component (e.g. from .text())");
|
|
65
|
+
return this.#reg(id, "Button", { child: childId, variant, ...(action ? { action } : {}) });
|
|
66
|
+
}
|
|
67
|
+
card(childId, { id } = {}) {
|
|
68
|
+
return this.#reg(id, "Card", { child: childId });
|
|
69
|
+
}
|
|
70
|
+
// trigger: id of the component that opens the modal (e.g. a Button); content: id of the
|
|
71
|
+
// component shown inside it. Both are ids of already-registered SIBLING components, not
|
|
72
|
+
// nested children — that's how the wire format expects Modal to reference them.
|
|
73
|
+
modal(triggerId, contentId, { id } = {}) {
|
|
74
|
+
if (!triggerId) throw new TypeError("modal(triggerId, contentId) requires the id of the trigger component");
|
|
75
|
+
if (!contentId) throw new TypeError("modal(triggerId, contentId) requires the id of the content component");
|
|
76
|
+
return this.#reg(id, "Modal", { trigger: triggerId, content: contentId });
|
|
77
|
+
}
|
|
78
|
+
// Escape hatch for any catalog component without a dedicated method yet (Divider, Slider,
|
|
79
|
+
// Switch, List, etc). props is merged as-is into the registered node.
|
|
80
|
+
raw(component, props = {}, { id } = {}) {
|
|
81
|
+
if (typeof component !== "string" || !component) throw new TypeError("raw(component, props) requires a non-empty component type string");
|
|
82
|
+
return this.#reg(id, component, props);
|
|
83
|
+
}
|
|
84
|
+
column(children = [], { id } = {}) {
|
|
85
|
+
if (!children.length) throw new TypeError("column(children) requires at least one child id");
|
|
86
|
+
return this.#reg(id, "Column", { children });
|
|
87
|
+
}
|
|
88
|
+
row(children = [], { id } = {}) {
|
|
89
|
+
if (!children.length) throw new TypeError("row(children) requires at least one child id");
|
|
90
|
+
return this.#reg(id, "Row", { children });
|
|
91
|
+
}
|
|
92
|
+
divider({ id } = {}) {
|
|
93
|
+
return this.#reg(id, "Divider", {});
|
|
94
|
+
}
|
|
95
|
+
// JAP@Add --- second-wave catalog components (all register via #reg, so
|
|
96
|
+
// build()-time ref validation + root()/build()/send() keep working unchanged)
|
|
97
|
+
slider({ id, value = 0, min = 0, max = 100, step = 1, label } = {}) {
|
|
98
|
+
return this.#reg(id, "Slider", { value, min, max, step, ...(label !== undefined ? { label } : {}) });
|
|
99
|
+
}
|
|
100
|
+
switch(label, { id, value = false } = {}) {
|
|
101
|
+
return this.#reg(id, "Switch", { label, value });
|
|
102
|
+
}
|
|
103
|
+
list(children = [], { id } = {}) {
|
|
104
|
+
if (!children.length) throw new TypeError("list(children) requires at least one child id");
|
|
105
|
+
return this.#reg(id, "List", { children });
|
|
106
|
+
}
|
|
107
|
+
progressBar(value, { id, min = 0, max = 100, variant = "linear" } = {}) {
|
|
108
|
+
if (typeof value !== "number") throw new TypeError("progressBar(value) requires a number");
|
|
109
|
+
return this.#reg(id, "ProgressBar", { value, min, max, variant });
|
|
110
|
+
}
|
|
111
|
+
avatar(url, { id, variant = "circle", size = 40 } = {}) {
|
|
112
|
+
if (!url) throw new TypeError("avatar(url) requires an image url");
|
|
113
|
+
return this.#reg(id, "Avatar", { url, variant, size });
|
|
114
|
+
}
|
|
115
|
+
badge(childId, { id, label } = {}) {
|
|
116
|
+
if (!childId) throw new TypeError("badge(childId) requires the id of a child component");
|
|
117
|
+
return this.#reg(id, "Badge", { child: childId, ...(label !== undefined ? { label } : {}) });
|
|
118
|
+
}
|
|
119
|
+
spacer({ id, height = 16 } = {}) {
|
|
120
|
+
return this.#reg(id, "Spacer", { height });
|
|
121
|
+
}
|
|
122
|
+
tabs(children = [], { id, activeTab = 0 } = {}) {
|
|
123
|
+
if (!children.length) throw new TypeError("tabs(children) requires at least one child id");
|
|
124
|
+
return this.#reg(id, "Tabs", { children, activeTab });
|
|
125
|
+
}
|
|
126
|
+
choicePicker(label, options, { id, variant = "mutuallyExclusive", value, displayStyle = "checkbox", filterable = false } = {}) {
|
|
127
|
+
if (!Array.isArray(options) || !options.length) {
|
|
128
|
+
throw new TypeError("choicePicker(label, options) requires a non-empty options array of {label, value}");
|
|
129
|
+
}
|
|
130
|
+
return this.#reg(id, "ChoicePicker", {
|
|
131
|
+
label,
|
|
132
|
+
variant,
|
|
133
|
+
...(value !== undefined ? { value } : {}),
|
|
134
|
+
options,
|
|
135
|
+
displayStyle,
|
|
136
|
+
filterable
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
root(children) {
|
|
140
|
+
if (!Array.isArray(children) || !children.length) {
|
|
141
|
+
throw new TypeError("root(children) requires a non-empty array of top-level component ids");
|
|
142
|
+
}
|
|
143
|
+
this._rootChildren = children;
|
|
144
|
+
return this;
|
|
145
|
+
}
|
|
146
|
+
// JAP@Add 29-08-26 --- Product/list carousel card. This is a DIFFERENT wire
|
|
147
|
+
// payload shape from the Column/Row component-tree the rest of this class
|
|
148
|
+
// builds (type: 'list_card', flat items array) — not a catalog component, so
|
|
149
|
+
// it doesn't go through #reg()/root(). Call this instead of root()+build();
|
|
150
|
+
// build() returns the list_card payload directly when this was set.
|
|
151
|
+
listCard({ title, items, fallbackText, uuid = crypto.randomUUID() } = {}) {
|
|
152
|
+
if (!title) throw new TypeError("listCard requires a title");
|
|
153
|
+
if (!Array.isArray(items) || !items.length) {
|
|
154
|
+
throw new TypeError("listCard requires a non-empty items array");
|
|
155
|
+
}
|
|
156
|
+
// JAP@Fix (§2.36 / v2.4.7) part 1: listCard() short-circuits build(), so mixing it with
|
|
157
|
+
// root()/component factories silently threw the whole component tree away. Refuse the
|
|
158
|
+
// ambiguous combination rather than dropping half the widget without a word.
|
|
159
|
+
if (this._rootChildren.length || this._components.size) {
|
|
160
|
+
throw new Error("listCard() builds a standalone list_card payload and cannot be combined with component factories/root() -- use a separate A2UI instance");
|
|
161
|
+
}
|
|
162
|
+
this._listCardPayload = {
|
|
163
|
+
uuid,
|
|
164
|
+
data: JSON.stringify({
|
|
165
|
+
type: "list_card",
|
|
166
|
+
title,
|
|
167
|
+
fallback_text: fallbackText ?? "",
|
|
168
|
+
items: items.map((it) => ({
|
|
169
|
+
asset_id: it.assetId ?? crypto.randomUUID().replace(/-/g, "").slice(0, 17),
|
|
170
|
+
asset_type: it.assetType ?? "PRODUCT_ITEM",
|
|
171
|
+
title: it.title,
|
|
172
|
+
trailing_label: it.price ?? it.trailingLabel ?? "",
|
|
173
|
+
trailing_emphasis: it.emphasis ?? "strong"
|
|
174
|
+
}))
|
|
175
|
+
}),
|
|
176
|
+
type: "im_a2ui",
|
|
177
|
+
fallback: fallbackText ?? ""
|
|
178
|
+
};
|
|
179
|
+
return this;
|
|
180
|
+
}
|
|
181
|
+
// JAP@Add 30-08-26 --- send(): terminal method so A2UI can be used as a one-liner like
|
|
182
|
+
// the other builders (Button/ButtonV2/AIRich `.send()`), instead of always needing the
|
|
183
|
+
// separate `sendA2UIWidget()` call. Thin wrapper only — root([...ids])/listCard() must
|
|
184
|
+
// still be called first, same as before build(); this doesn't change the id-returning
|
|
185
|
+
// factory API (child methods still return ids, not `this`, since sibling nodes need to
|
|
186
|
+
// reference each other by id when wiring children/trigger/content).
|
|
187
|
+
async send(client, jid, opts = {}) {
|
|
188
|
+
return sendA2UIWidget(client, jid, { ...opts, a2ui: this });
|
|
189
|
+
}
|
|
190
|
+
// JAP@Add 30-08-26 --- validates that every structural id-reference (child/children on
|
|
191
|
+
// Button/Card/Column/Row, trigger/content on Modal) points at a component that was
|
|
192
|
+
// actually registered. Without this, a typo'd id just gets written into the wire payload
|
|
193
|
+
// as-is and the failure only surfaces as a broken/blank widget on the WA client, with no
|
|
194
|
+
// error on this end. Only covers the dedicated methods' known reference keys — raw()'s
|
|
195
|
+
// free-form props aren't inspected, since there's no way to know which of those are id
|
|
196
|
+
// references vs plain data.
|
|
197
|
+
/** @returns {boolean} Whether `id` was registered on this instance. */
|
|
198
|
+
has(id) {
|
|
199
|
+
return this._components.has(id);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** @returns {Record<string, any>|undefined} A copy of the registered component node. */
|
|
203
|
+
get(id) {
|
|
204
|
+
const node = this._components.get(id);
|
|
205
|
+
return node ? { ...node } : undefined;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** @returns {string[]} Every registered component id, in registration order. */
|
|
209
|
+
ids() {
|
|
210
|
+
return [...this._components.keys()];
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** @returns {number} How many components are registered (excluding the implicit root). */
|
|
214
|
+
count() {
|
|
215
|
+
return this._components.size;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** Unregister one component. @returns {boolean} Whether it existed. */
|
|
219
|
+
remove(id) {
|
|
220
|
+
return this._components.delete(id);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** Drop every component, the root selection and any listCard payload. */
|
|
224
|
+
clear() {
|
|
225
|
+
this._components.clear();
|
|
226
|
+
this._rootChildren = [];
|
|
227
|
+
this._listCardPayload = undefined;
|
|
228
|
+
return this;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** Override the catalog url used in `createSurface.catalogId`. */
|
|
232
|
+
setCatalogId(catalogId) {
|
|
233
|
+
if (typeof catalogId !== "string" || !catalogId) throw new TypeError("setCatalogId(catalogId) requires a non-empty string");
|
|
234
|
+
this._catalogId = catalogId;
|
|
235
|
+
return this;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** Override the A2UI spec version stamped on the payload. */
|
|
239
|
+
setVersion(version) {
|
|
240
|
+
if (typeof version !== "string" || !version) throw new TypeError("setVersion(version) requires a non-empty string");
|
|
241
|
+
this._version = version;
|
|
242
|
+
return this;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Registered components that nothing references and that aren't in root() -- they are
|
|
247
|
+
* encoded into the payload but never rendered, which is almost always a wiring mistake.
|
|
248
|
+
* @returns {string[]}
|
|
249
|
+
*/
|
|
250
|
+
findOrphans() {
|
|
251
|
+
const referenced = new Set(this._rootChildren);
|
|
252
|
+
for (const c of this._components.values()) {
|
|
253
|
+
for (const key of ["child", "trigger", "content"]) {
|
|
254
|
+
if (c[key] !== undefined) referenced.add(c[key]);
|
|
255
|
+
}
|
|
256
|
+
if (Array.isArray(c.children)) c.children.forEach((childId) => referenced.add(childId));
|
|
257
|
+
}
|
|
258
|
+
return [...this._components.keys()].filter((id) => !referenced.has(id));
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* Collect every structural problem without throwing on the first one.
|
|
263
|
+
* @returns {string[]} Empty when the widget is safe to build.
|
|
264
|
+
*/
|
|
265
|
+
validate() {
|
|
266
|
+
const problems = [];
|
|
267
|
+
if (this._listCardPayload) return problems;
|
|
268
|
+
if (!this._rootChildren.length) {
|
|
269
|
+
problems.push("Call root([...ids]) before build()");
|
|
270
|
+
return problems;
|
|
271
|
+
}
|
|
272
|
+
const root = { id: "root", component: "Column", children: this._rootChildren };
|
|
273
|
+
try {
|
|
274
|
+
this.#validateRefs([root, ...this._components.values()]);
|
|
275
|
+
} catch (error) {
|
|
276
|
+
problems.push(error.message);
|
|
277
|
+
}
|
|
278
|
+
for (const id of this.findOrphans()) {
|
|
279
|
+
problems.push(`A2UI: component "${id}" is registered but never referenced by root() or any parent -- it will not render`);
|
|
280
|
+
}
|
|
281
|
+
return problems;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** Throw on the first structural problem. @returns {this} */
|
|
285
|
+
assertValid() {
|
|
286
|
+
const [problem] = this.validate();
|
|
287
|
+
if (problem) throw new Error(problem);
|
|
288
|
+
return this;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
#validateRefs(components) {
|
|
292
|
+
const validIds = new Set(components.map((c) => c.id));
|
|
293
|
+
for (const c of components) {
|
|
294
|
+
for (const key of ["child", "trigger", "content"]) {
|
|
295
|
+
if (c[key] !== undefined && !validIds.has(c[key])) {
|
|
296
|
+
throw new Error(`A2UI: component "${c.id}" (${c.component}) references unknown id "${c[key]}" via "${key}"`);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
if (Array.isArray(c.children)) {
|
|
300
|
+
for (const childId of c.children) {
|
|
301
|
+
if (!validIds.has(childId)) {
|
|
302
|
+
throw new Error(`A2UI: component "${c.id}" (${c.component}) references unknown id "${childId}" in "children"`);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
build({ uuid = crypto.randomUUID(), surfaceId, type = "im_a2ui", wrapped = true, validate = true } = {}) {
|
|
309
|
+
// JAP@Fix (§2.36 / v2.4.7) part 2: the listCard branch returned its frozen payload and
|
|
310
|
+
// ignored build()'s `type`, so sendA2UIWidget(..., { type: 'custom' }) silently shipped
|
|
311
|
+
// the hardcoded 'im_a2ui' for list cards while honouring it for every other widget.
|
|
312
|
+
if (this._listCardPayload) {
|
|
313
|
+
return { ...this._listCardPayload, type };
|
|
314
|
+
}
|
|
315
|
+
if (!this._rootChildren.length) throw new Error("Call root([...ids]) before build()");
|
|
316
|
+
if (validate) this.assertValid();
|
|
317
|
+
const root = { id: "root", component: "Column", children: this._rootChildren };
|
|
318
|
+
const components = [root, ...this._components.values()];
|
|
319
|
+
this.#validateRefs(components);
|
|
320
|
+
const data = wrapped
|
|
321
|
+
? {
|
|
322
|
+
version: this._version,
|
|
323
|
+
createSurface: {
|
|
324
|
+
surfaceId: surfaceId ?? `starcore-widget=${uuid}`,
|
|
325
|
+
catalogId: this._catalogId,
|
|
326
|
+
components
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
: { components };
|
|
330
|
+
return {
|
|
331
|
+
uuid,
|
|
332
|
+
data: JSON.stringify(data),
|
|
333
|
+
type
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* Build + send an A2UI/Bloks widget as an interactiveMessage.
|
|
340
|
+
* @param {import('../../WAProto/index.js').WASocket} client Active Baileys socket.
|
|
341
|
+
* @param {string} jid Destination chat/group jid.
|
|
342
|
+
*/
|
|
343
|
+
async function sendA2UIWidget(client, jid, {
|
|
344
|
+
a2ui,
|
|
345
|
+
bodyText = "",
|
|
346
|
+
footer = "",
|
|
347
|
+
buttons = [],
|
|
348
|
+
contextInfo = {},
|
|
349
|
+
expiration,
|
|
350
|
+
quoted,
|
|
351
|
+
type = "im_a2ui",
|
|
352
|
+
wrapped = true,
|
|
353
|
+
singleScreen = false,
|
|
354
|
+
// JAP@Add 30-08-26 --- optional header media, mirroring Button/ButtonV2's toCard()
|
|
355
|
+
// pattern (prepareWAMessageMedia + client.waUploadToServer). { title, subtitle, image
|
|
356
|
+
// | video | document: path/buffer/{url} } — media is mutually exclusive, image wins if
|
|
357
|
+
// more than one is passed. Falls back to a title/subtitle-only header (no attachment)
|
|
358
|
+
// when no media is given, same shape as before this change.
|
|
359
|
+
header
|
|
360
|
+
} = {}) {
|
|
361
|
+
if (!client) throw new Error("Socket is required");
|
|
362
|
+
if (!(a2ui instanceof A2UI)) throw new TypeError("a2ui must be an A2UI instance");
|
|
363
|
+
|
|
364
|
+
const nativeFlowMessage = buttons && buttons.length
|
|
365
|
+
? {
|
|
366
|
+
buttons: buttons.map((b) => ({
|
|
367
|
+
name: b.name ?? "cta_url",
|
|
368
|
+
buttonParamsJson: typeof b.params === "string" ? b.params : JSON.stringify(b.params ?? {}),
|
|
369
|
+
})),
|
|
370
|
+
messageParamsJson: "{}",
|
|
371
|
+
messageVersion: 1
|
|
372
|
+
}
|
|
373
|
+
: { messageParamsJson: "" };
|
|
374
|
+
|
|
375
|
+
const headerMediaData = header?.image
|
|
376
|
+
? { image: header.image }
|
|
377
|
+
: header?.video
|
|
378
|
+
? { video: header.video }
|
|
379
|
+
: header?.document
|
|
380
|
+
? { document: header.document }
|
|
381
|
+
: null;
|
|
382
|
+
|
|
383
|
+
const headerBlock = {
|
|
384
|
+
...(header?.title !== undefined ? { title: header.title } : {}),
|
|
385
|
+
...(header?.subtitle !== undefined ? { subtitle: header.subtitle } : {}),
|
|
386
|
+
hasMediaAttachment: !!headerMediaData,
|
|
387
|
+
...(headerMediaData
|
|
388
|
+
? await prepareWAMessageMedia(headerMediaData, { upload: client.waUploadToServer }).catch((e) => {
|
|
389
|
+
if (String(e).includes("Invalid media type")) return headerMediaData;
|
|
390
|
+
throw e;
|
|
391
|
+
})
|
|
392
|
+
: {})
|
|
393
|
+
};
|
|
394
|
+
|
|
395
|
+
const interactiveMessage = singleScreen
|
|
396
|
+
? {
|
|
397
|
+
nativeFlowMessage,
|
|
398
|
+
bloksWidget: a2ui.build({ type, wrapped }),
|
|
399
|
+
...(expiration || Object.keys(contextInfo).length ? { contextInfo: { ...(expiration ? { expiration } : {}), ...contextInfo } } : {})
|
|
400
|
+
}
|
|
401
|
+
: {
|
|
402
|
+
header: headerBlock,
|
|
403
|
+
body: { text: bodyText },
|
|
404
|
+
...(footer ? { footer: { text: footer } } : {}),
|
|
405
|
+
nativeFlowMessage,
|
|
406
|
+
bloksWidget: a2ui.build({ type, wrapped }),
|
|
407
|
+
...(expiration || Object.keys(contextInfo).length ? { contextInfo: { ...(expiration ? { expiration } : {}), ...contextInfo } } : {})
|
|
408
|
+
};
|
|
409
|
+
|
|
410
|
+
const msg = generateWAMessageFromContent(jid, {
|
|
411
|
+
messageContextInfo: { messageSecret: crypto.randomBytes(32) },
|
|
412
|
+
interactiveMessage
|
|
413
|
+
}, { quoted });
|
|
414
|
+
|
|
415
|
+
await client.relayMessage(msg.key.remoteJid, msg.message, {
|
|
416
|
+
messageId: msg.key.id,
|
|
417
|
+
additionalNodes: [getBizBinaryNode(msg.message)]
|
|
418
|
+
});
|
|
419
|
+
return msg;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
export { A2UI, sendA2UIWidget };
|
package/lib/Socket/index.js
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
import { DEFAULT_CONNECTION_CONFIG } from '../Defaults/index.js';
|
|
2
2
|
import { setupAutoFollow } from '../Utils/auto-follow.js';
|
|
3
3
|
import { makeCommunitiesSocket } from './communities.js';
|
|
4
|
+
import { Boom } from '@hapi/boom';
|
|
5
|
+
import { buildMiniAppContent } from '../Utils/mini-app.js';
|
|
6
|
+
import { transcribeMessage } from '../Utils/transcribe.js';
|
|
7
|
+
import { attachUsernameApi } from '../Utils/username.js';
|
|
8
|
+
import { A2UI, sendA2UIWidget } from '../Builders/A2UI.js';
|
|
4
9
|
|
|
5
10
|
// export the last socket layer
|
|
6
11
|
const makeWASocket = (config) => {
|
|
@@ -15,6 +20,24 @@ const makeWASocket = (config) => {
|
|
|
15
20
|
|
|
16
21
|
sock.sendHtml = (jid, html, { title, trustedSources, disclaimerText, botJid, ...options } = {}) => sock.sendMessage(jid, { html, title, trustedSources, disclaimerText, botJid }, options);
|
|
17
22
|
|
|
23
|
+
// JexkCode@Port (JAPofc/baileys, MIT)
|
|
24
|
+
sock.sendMiniApp = async (jid, miniApp, options = {}) => sock.sendMessage(jid, await buildMiniAppContent(miniApp), options);
|
|
25
|
+
sock.sendA2UIWidget = (jid, opts = {}) => sendA2UIWidget(sock, jid, opts);
|
|
26
|
+
sock.transcribeMessage = (webMessage, opts) => transcribeMessage(sock, webMessage, opts);
|
|
27
|
+
sock.sendScheduledCall = (jid, scheduledCall, options = {}) => sock.sendMessage(jid, { scheduledCall }, options);
|
|
28
|
+
sock.cancelScheduledCall = (jid, key, options = {}) => sock.sendMessage(jid, { scheduledCallEdit: { key } }, options);
|
|
29
|
+
sock.sendMentionAll = (jid, text, options = {}) => {
|
|
30
|
+
if (!text || typeof text !== 'string') throw new Boom('sendMentionAll needs a text string', { statusCode: 400 });
|
|
31
|
+
return sock.sendMessage(jid, { text, mentionAll: true }, options);
|
|
32
|
+
};
|
|
33
|
+
sock.sendStatusMention = (content, mentions, options = {}) => {
|
|
34
|
+
const jids = Array.isArray(mentions) ? mentions : [mentions];
|
|
35
|
+
if (!content || typeof content !== 'object') throw new Boom('sendStatusMention needs message content (e.g. { text } or { image })', { statusCode: 400 });
|
|
36
|
+
if (!jids.length || jids.some((j) => typeof j !== 'string' || !j.includes('@'))) throw new Boom('sendStatusMention needs one or more valid jids', { statusCode: 400 });
|
|
37
|
+
return sock.sendMessage(jids, content, options);
|
|
38
|
+
};
|
|
39
|
+
attachUsernameApi(sock, newConfig);
|
|
40
|
+
|
|
18
41
|
return sock;
|
|
19
42
|
};
|
|
20
43
|
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Drop-in auto-reconnect for direct makeWASocket users (the Framework Bot
|
|
3
|
+
* already has this built in). Exponential backoff with jitter, never
|
|
4
|
+
* reconnects on loggedOut, immediate reconnect on restartRequired.
|
|
5
|
+
* @author J.AP
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export interface AutoReconnectOptions {
|
|
9
|
+
/** Called with every fresh socket (initial + each reconnect) — attach your event handlers here. */
|
|
10
|
+
onSocket?: (sock: any) => void;
|
|
11
|
+
/** Called when a connection reaches 'open'. */
|
|
12
|
+
onOpen?: (sock: any) => void;
|
|
13
|
+
/** Called once when the session is logged out (no reconnect will follow) — clean up creds here. */
|
|
14
|
+
onGiveUp?: (info: { reason: 'factory-failed' | 'max-attempts'; attempts: number;
|
|
15
|
+
/** Current lifecycle status for dashboards/health probes. */
|
|
16
|
+
getStatus(): {
|
|
17
|
+
started: boolean;
|
|
18
|
+
stopped: boolean;
|
|
19
|
+
attempts: number;
|
|
20
|
+
reconnectPending: boolean;
|
|
21
|
+
hasSocket: boolean;
|
|
22
|
+
}; error?: unknown; statusCode?: number }) => void;
|
|
23
|
+
onLoggedOut?: (error: unknown) => void;
|
|
24
|
+
/** Give up after this many consecutive failed attempts (default Infinity). */
|
|
25
|
+
maxAttempts?: number;
|
|
26
|
+
/** First retry delay in ms (default 1000). */
|
|
27
|
+
baseDelayMs?: number;
|
|
28
|
+
/** Backoff cap in ms (default 30000). */
|
|
29
|
+
maxDelayMs?: number;
|
|
30
|
+
/** Random jitter fraction 0-1 applied to each delay (default 0.25). */
|
|
31
|
+
jitter?: number;
|
|
32
|
+
logger?: any;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface AutoReconnectManager {
|
|
36
|
+
/** Create the socket (via your factory) and begin supervising it. Resolves to the socket, or null if already stopped. */
|
|
37
|
+
start: () => Promise<any | null>;
|
|
38
|
+
/** Cancel pending reconnects and close the live socket. */
|
|
39
|
+
stop: () => Promise<void>;
|
|
40
|
+
/** The live socket (replaced on every reconnect); null before start(). */
|
|
41
|
+
readonly socket: any | null;
|
|
42
|
+
/** Consecutive failed attempts since the last successful open. */
|
|
43
|
+
readonly attempts: number;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Supervise a socket factory with automatic reconnect.
|
|
48
|
+
* The factory may be sync (`() => makeWASocket(cfg)`) or async
|
|
49
|
+
* (`() => makeWASocketAuto(cfg)`).
|
|
50
|
+
*/
|
|
51
|
+
export declare const autoReconnect: (
|
|
52
|
+
socketFactory: () => any | Promise<any>,
|
|
53
|
+
options?: AutoReconnectOptions,
|
|
54
|
+
) => AutoReconnectManager;
|