kage-baileys 25.3.35 → 25.3.40

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 (80) hide show
  1. package/README.md +118 -0
  2. package/WAProto/WAProto.proto +8 -0
  3. package/WAProto/index.d.ts +124 -0
  4. package/helpers/interactive-pay.d.ts +48 -0
  5. package/helpers/interactive-pay.js +160 -57
  6. package/helpers/media-thumb.d.ts +7 -0
  7. package/helpers/media-thumb.js +141 -57
  8. package/lib/Builders/A2UI.js +8 -2
  9. package/lib/Builders/Button.js +8 -4
  10. package/lib/Builders/ButtonV2.js +8 -4
  11. package/lib/Builders/Carousel.js +8 -4
  12. package/lib/Defaults/baileys-version.json +6 -2
  13. package/lib/Defaults/connection.cjs +1 -1
  14. package/lib/Defaults/index.js +2 -2
  15. package/lib/Defaults/wileys-version.json +5 -1
  16. package/lib/Extensions/bootstrap.cjs +34 -0
  17. package/lib/Framework/Bot.js +2 -4
  18. package/lib/Framework/StatsManager.js +31 -18
  19. package/lib/Framework/Store/SQLiteStore.js +4 -11
  20. package/lib/Signal/lid-mapping.d.ts +2 -1
  21. package/lib/Signal/lid-mapping.js +55 -46
  22. package/lib/Socket/Client/websocket.js +6 -1
  23. package/lib/Socket/index.d.ts +1 -0
  24. package/lib/Socket/messages-recv.js +77 -46
  25. package/lib/Socket/messages-send.d.ts +1 -0
  26. package/lib/Socket/messages-send.js +24 -9
  27. package/lib/Socket/mex.d.ts +2 -1
  28. package/lib/Socket/mex.d.ts.map +1 -1
  29. package/lib/Socket/mex.js +27 -10
  30. package/lib/Socket/newsletter-utils.js +112 -0
  31. package/lib/Socket/newsletter.d.ts +1 -0
  32. package/lib/Socket/newsletter.js +21 -43
  33. package/lib/Socket/socket.d.ts +2 -0
  34. package/lib/Socket/socket.js +17 -0
  35. package/lib/Types/Events.d.ts +6 -0
  36. package/lib/Types/Kage.d.ts +6 -0
  37. package/lib/Types/Message.d.ts +3 -0
  38. package/lib/Types/Mex.d.ts +2 -2
  39. package/lib/Types/Mex.js +2 -2
  40. package/lib/Types/index.d.ts +1 -0
  41. package/lib/Utils/auth-utils.js +9 -5
  42. package/lib/Utils/browser-utils.js +2 -0
  43. package/lib/Utils/decode-wa-message.js +11 -1
  44. package/lib/Utils/decrypt-message-edit.d.ts +12 -0
  45. package/lib/Utils/decrypt-message-edit.d.ts.map +1 -0
  46. package/lib/Utils/decrypt-message-edit.js +33 -0
  47. package/lib/Utils/event-buffer.js +7 -0
  48. package/lib/Utils/generics.js +3 -35
  49. package/lib/Utils/index.d.ts +5 -1
  50. package/lib/Utils/index.js +5 -1
  51. package/lib/Utils/kage-messages.cjs +41 -5
  52. package/lib/Utils/media-message-guards.cjs +127 -0
  53. package/lib/Utils/messages-media.d.ts +2 -2
  54. package/lib/Utils/messages-media.js +22 -18
  55. package/lib/Utils/messages-whiskey.js +78 -26
  56. package/lib/Utils/messages.d.ts +8 -0
  57. package/lib/Utils/native-flow.d.ts +14 -0
  58. package/lib/Utils/native-flow.js +140 -0
  59. package/lib/Utils/offline-node-processor.js +15 -3
  60. package/lib/Utils/payment-messages.d.ts +11 -0
  61. package/lib/Utils/payment-messages.js +136 -0
  62. package/lib/Utils/photo.d.ts +7 -0
  63. package/lib/Utils/photo.js +31 -0
  64. package/lib/Utils/process-message.d.ts +1 -1
  65. package/lib/Utils/process-message.js +75 -4
  66. package/lib/Utils/sqlite-adapter.cjs +68 -0
  67. package/lib/Utils/use-sqlite-auth-state.cjs +5 -13
  68. package/lib/WABinary/generic-utils.d.ts +2 -1
  69. package/lib/WABinary/generic-utils.js +153 -1
  70. package/lib/index.d.ts +2 -0
  71. package/lib/index.js +2 -0
  72. package/licenses/elaina-native-flow-MIT.txt +22 -0
  73. package/package.json +16 -15
  74. package/scripts/verify-package.mjs +150 -0
  75. package/test/get-biz-binary-node.test.js +37 -0
  76. package/test/media-message-guards.test.js +79 -0
  77. package/test/native-flow-payment.test.js +269 -0
  78. package/test/newsletter-utils.test.js +58 -0
  79. package/test/offline-node-processor.test.js +59 -0
  80. package/test/sqlite-adapter.test.js +87 -0
package/README.md CHANGED
@@ -1076,6 +1076,80 @@ await sock.sendMessage(jid, {
1076
1076
  })
1077
1077
  ```
1078
1078
 
1079
+ ### `review_and_pay` Native Flow con miniatura JPEG
1080
+
1081
+ Kage incluye un constructor para el formato `interactiveMessage` + `nativeFlowMessage` que se transmite mediante `relayMessage`. La miniatura acepta un `Buffer`, una imagen en base64, un `data:image/...` o una URL HTTP(S); las imágenes PNG/WebP/GIF se convierten a JPEG mediante `sharp` sin truncar bytes.
1082
+
1083
+ ```javascript
1084
+ import { buildReviewAndPayMessage } from 'kage-baileys'
1085
+
1086
+ const content = await buildReviewAndPayMessage({
1087
+ header: { title: '', subtitle: '' },
1088
+ body: 'Texto',
1089
+ footer: 'Footer',
1090
+ thumbnail: 'https://cdn.example.com/producto.jpg',
1091
+ paymentParams: {
1092
+ currency: 'PEN',
1093
+ payment_configuration: '',
1094
+ payment_type: 'upr',
1095
+ total_amount: { value: 137, offset: 100 },
1096
+ reference_id: 'KFG_001',
1097
+ type: 'physical-goods',
1098
+ order: {
1099
+ status: 'pending',
1100
+ description: 'Pequeña descripción',
1101
+ order_type: 'PAYMENT_REQUEST',
1102
+ items: [{
1103
+ name: 'Título principal',
1104
+ amount: { value: 138, offset: 100 },
1105
+ quantity: 1
1106
+ }]
1107
+ },
1108
+ payment_settings: [
1109
+ {
1110
+ type: 'payment_account',
1111
+ payment_account: {
1112
+ account_type: 'digital_wallet',
1113
+ identifier_type: 'phone_number',
1114
+ identifier_value: '51900000000',
1115
+ institution_name: 'Yape',
1116
+ beneficiary_name: 'Nombre del beneficiario'
1117
+ }
1118
+ }
1119
+ ],
1120
+ additional_note: 'Descripción principal',
1121
+ share_payment_status: false,
1122
+ is_soft_deleted: false
1123
+ }
1124
+ })
1125
+
1126
+ await conn.relayMessage(m.chat, content, {})
1127
+ ```
1128
+
1129
+ También se puede usar el método instalado automáticamente en el socket:
1130
+
1131
+ ```javascript
1132
+ await conn.sendReviewAndPay(m.chat, {
1133
+ body: 'Texto',
1134
+ footer: 'Footer',
1135
+ thumbnail: 'https://cdn.example.com/producto.jpg',
1136
+ paymentParams: datosDelPago
1137
+ })
1138
+ ```
1139
+
1140
+ `payment_settings` admite varias cuentas (Yape, Plin, bancos y otros métodos) y conserva los identificadores proporcionados. Reemplaza todos los datos de ejemplo o marcadores por datos reales y autorizados; Kage solo construye y transmite el mensaje, no procesa cobros ni confirma pagos. El cliente, la cuenta, la región y las capacidades habilitadas por WhatsApp determinan si el botón se muestra y puede utilizarse. `review_and_pay` puede no renderizarse en WhatsApp Web/iOS.
1141
+
1142
+ ### Helpers de fotos y perfil
1143
+
1144
+ ```javascript
1145
+ await conn.sendPhoto(jid, './foto.jpg', { caption: 'Foto' })
1146
+ const photoUrl = await conn.getProfilePhoto(jid, 'image')
1147
+ await conn.setProfilePhoto(jid, './avatar.jpg')
1148
+ await conn.removeProfilePhoto(jid)
1149
+ ```
1150
+
1151
+ También se exportan `sendPhoto`, `getProfilePhoto`, `setProfilePhoto`, `removeProfilePhoto`, `normalizePhotoThumbnail`, `normalizeThumbnail` y `ensureJpegThumbnail` desde el paquete.
1152
+
1079
1153
  ## 📁 Mensajes multimedia
1080
1154
 
1081
1155
  > [!NOTE]
@@ -2177,3 +2251,47 @@ Mantente informado de las actualizaciones y novedades del proyecto:
2177
2251
  **kage-baileys** — la mejor Baileys de 2026 · API de WhatsApp Web con corrección de @lid a @pn
2178
2252
 
2179
2253
  </div>
2254
+
2255
+
2256
+ ## Diagnóstico de medios y mensajes de visualización única
2257
+
2258
+ `getMediaDownloadStatus(message)` permite comprobar si un mensaje contiene un medio normal descargable:
2259
+
2260
+ - `ready`: hay clave de medio y `url` o `directPath`.
2261
+ - `missing_media_key` / `missing_media_location`: WhatsApp entregó un payload incompleto.
2262
+ - `view_once_protected`: el payload está marcado como visualización única y la descarga desde `downloadMediaMessage` se rechaza.
2263
+ - `view_once_unavailable`: WhatsApp no entregó el archivo o su clave/ruta al dispositivo vinculado.
2264
+
2265
+ Kage Baileys no elimina la protección de visualización única ni reconstruye archivos que WhatsApp no envió. Cuando WhatsApp retiene un mensaje de este tipo, se emite `messages.upsert` con `key.isViewOnce === true` y `messageStubParameters: ['VIEW_ONCE_UNAVAILABLE']`, además del evento `kage.viewonce.unavailable`.
2266
+
2267
+ Para medios normales, usa `downloadMediaMessage(message, 'buffer', {}, { logger, reuploadRequest: sock.updateMediaMessage })`. La re-subida automática reconoce los estados HTTP 404/410 de `Boom` y vuelve a intentar una sola vez con el mensaje actualizado.
2268
+
2269
+ ```js
2270
+ import { getMediaDownloadStatus, downloadMediaMessage } from 'kage-baileys'
2271
+
2272
+ const state = getMediaDownloadStatus(message)
2273
+ if (state.status === 'ready') {
2274
+ const buffer = await downloadMediaMessage(message, 'buffer', {}, {
2275
+ logger: sock.logger,
2276
+ reuploadRequest: sock.updateMediaMessage
2277
+ })
2278
+ } else if (state.status === 'view_once_unavailable' || state.status === 'view_once_protected') {
2279
+ // No hay descarga: solicita al remitente que comparta el archivo como medio normal.
2280
+ }
2281
+
2282
+ sock.ev.on('kage.viewonce.unavailable', ({ key }) => {
2283
+ console.info('WhatsApp no entregó el contenido view-once:', key.id)
2284
+ })
2285
+ ```
2286
+
2287
+
2288
+ ## RedX RC15 core compatibility updates
2289
+
2290
+ This Kage build incorporates selected fixes reviewed from RedX Baileys 7.0.0-rc15: encrypted WhatsApp message-edit decoding, serialized PN/LID mapping updates, pairing-code handshake readiness, top-level status-stanza acknowledgements, device-sent context preservation, non-blocking signal cache operations, and bounded media/queue handling. Kage-specific Builders, Native Flow, payment helpers, media guards, and ViewOnce availability diagnostics remain in place.
2291
+
2292
+ ### Newsletter / WMex compatibility
2293
+
2294
+ - `newsletterMetadata('invite', codeOrUrl)` accepts invite codes and WhatsApp channel share URLs such as `https://whatsapp.com/channel/<code>/<post-id>`.
2295
+ - `newsletterJidFromInvite(codeOrUrl)` resolves the channel JID from metadata.
2296
+ - WMex response parsing accepts JSON bodies with a binary prefix and safely handles partial newsletter metadata responses.
2297
+ - Compact binary newsletter metadata is accepted only when exactly one channel JID can be identified; ambiguous payloads are rejected instead of guessed.
@@ -7150,6 +7150,14 @@ message WebMessageInfo {
7150
7150
  optional GroupHistoryBundleInfo groupHistoryBundleInfo = 75;
7151
7151
  optional InteractiveMessageAdditionalMetadata interactiveMessageAdditionalMetadata = 76;
7152
7152
  optional QuarantinedMessage quarantinedMessage = 77;
7153
+ // Additional WebMessageInfo metadata merged from the Elaina/Dnuzi schema lineage.
7154
+ optional uint32 nonJidMentions = 78;
7155
+ optional string hsmTag = 79;
7156
+ optional uint64 ephemeralExpirationTimestamp = 80;
7157
+ optional ScheduledMessageMetadata scheduledMessageMetadata = 81;
7158
+ optional string decisionId = 82;
7159
+ repeated string decisionSources = 83;
7160
+ optional EventInviteAdditionalMetadata eventInviteAdditionalMetadata = 84;
7153
7161
  enum BizPrivacyStatus {
7154
7162
  E2EE = 0;
7155
7163
  FB = 2;
@@ -14044,3 +14044,127 @@ export namespace proto {
14044
14044
  interface MusicUserIdAction { musicUserIdMap: { [k: string]: string }; }
14045
14045
  }
14046
14046
  }
14047
+
14048
+ // Kage additive protocol declarations already materialized by WAProto/merge-runtime.js.
14049
+ // Additional Message fields are compatible with Elaina/Dnuzi Baileys schema extensions.
14050
+ export namespace proto {
14051
+ interface IMessage {
14052
+ instantImageMessage?: (proto.Message.IImageMessage | null);
14053
+ requestLocationMessage?: (any | null);
14054
+ requestLocationUpdateMessage?: (any | null);
14055
+ botGroupParticipantMessage?: (proto.Message.IFutureProofMessage | null);
14056
+ audioStickerMessage?: (proto.Message.IFutureProofMessage | null);
14057
+ acp2SettingMessage?: (proto.Message.IFutureProofMessage | null);
14058
+ newsletterFollowerInviteMessage?: (any | null);
14059
+ newsletterAdminProfileMessage?: (proto.Message.IFutureProofMessage | null);
14060
+ newsletterAdminProfileMessageV2?: (proto.Message.IFutureProofMessage | null);
14061
+ spoilerMessage?: (proto.Message.IFutureProofMessage | null);
14062
+ pollCreationMessageV6?: (proto.Message.IPollCreationMessage | null);
14063
+ conditionalRevealMessage?: (any | null);
14064
+ pollAddOptionMessage?: (any | null);
14065
+ eventInviteMessage?: (any | null);
14066
+ groupRootKeyShare?: (any | null);
14067
+ paymentReminderMessage?: (proto.Message.IPaymentReminderMessage | null);
14068
+ splitPaymentMessage?: (proto.Message.ISplitPaymentMessage | null);
14069
+ newsletterAdminProfileStatusMessage?: (proto.Message.IFutureProofMessage | null);
14070
+ rootSecretDistributeMessage?: (any | null);
14071
+ splitPaymentUpdateMessage?: (proto.Message.ISplitPaymentUpdateMessage | null);
14072
+ musicMessage?: (any | null);
14073
+ statusLinkPreviewMetadata?: (any | null);
14074
+ botPlatformRegistrationSuccessMessage?: (proto.Message.IFutureProofMessage | null);
14075
+ newsletterScheduledMessage?: (proto.Message.IFutureProofMessage | null);
14076
+ }
14077
+ interface Message extends IMessage {}
14078
+
14079
+ namespace Message {
14080
+ interface IInteractiveMessage {
14081
+ bloksWidget?: (any | null);
14082
+ }
14083
+ interface InteractiveMessage extends IInteractiveMessage {}
14084
+
14085
+ interface IPaymentReminderMessage {
14086
+ reminderId?: string | null;
14087
+ instanceId?: string | null;
14088
+ description?: string | null;
14089
+ frequency?: number | null;
14090
+ status?: number | null;
14091
+ payeeVpa?: string | null;
14092
+ payeeJid?: string | null;
14093
+ payerJid?: string | null;
14094
+ amount?: (proto.IMoney | null);
14095
+ }
14096
+ class PaymentReminderMessage implements IPaymentReminderMessage {
14097
+ constructor(properties?: IPaymentReminderMessage);
14098
+ public reminderId?: string | null;
14099
+ public instanceId?: string | null;
14100
+ public description?: string | null;
14101
+ public frequency?: number | null;
14102
+ public status?: number | null;
14103
+ public payeeVpa?: string | null;
14104
+ public payeeJid?: string | null;
14105
+ public payerJid?: string | null;
14106
+ public amount?: proto.IMoney | null;
14107
+ public static create(properties?: IPaymentReminderMessage): PaymentReminderMessage;
14108
+ public static encode(message: IPaymentReminderMessage, writer?: $protobuf.Writer): $protobuf.Writer;
14109
+ public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): PaymentReminderMessage;
14110
+ public static fromObject(value: { [key: string]: any }): PaymentReminderMessage;
14111
+ public static toObject(message: PaymentReminderMessage, options?: $protobuf.IConversionOptions): { [key: string]: any };
14112
+ }
14113
+ namespace PaymentReminderMessage {
14114
+ enum ReminderFrequency { REMINDER_FREQUENCY_UNKNOWN = 0; WEEKLY = 1; BI_WEEKLY = 2; MONTHLY = 3; QUARTERLY = 4; }
14115
+ enum ReminderStatus { REMINDER_STATUS_UNKNOWN = 0; ACTIVE = 1; CANCELLED_BY_CREATOR = 2; STOPPED_BY_RECEIVER = 3; EXPIRED = 4; PAID = 5; }
14116
+ }
14117
+
14118
+ interface ISplitPaymentParticipant {
14119
+ jid?: string | null;
14120
+ amount?: proto.IMoney | null;
14121
+ status?: number | null;
14122
+ }
14123
+ interface ISplitPaymentMessage {
14124
+ splitId?: string | null;
14125
+ totalAmount?: proto.IMoney | null;
14126
+ description?: string | null;
14127
+ requesterJid?: string | null;
14128
+ participants?: ISplitPaymentParticipant[] | null;
14129
+ createdAtMs?: number | Long | null;
14130
+ contextInfo?: proto.IContextInfo | null;
14131
+ }
14132
+ class SplitPaymentMessage implements ISplitPaymentMessage {
14133
+ constructor(properties?: ISplitPaymentMessage);
14134
+ public splitId?: string | null;
14135
+ public totalAmount?: proto.IMoney | null;
14136
+ public description?: string | null;
14137
+ public requesterJid?: string | null;
14138
+ public participants: ISplitPaymentParticipant[];
14139
+ public createdAtMs?: number | Long | null;
14140
+ public contextInfo?: proto.IContextInfo | null;
14141
+ public static create(properties?: ISplitPaymentMessage): SplitPaymentMessage;
14142
+ public static encode(message: ISplitPaymentMessage, writer?: $protobuf.Writer): $protobuf.Writer;
14143
+ public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): SplitPaymentMessage;
14144
+ public static fromObject(value: { [key: string]: any }): SplitPaymentMessage;
14145
+ public static toObject(message: SplitPaymentMessage, options?: $protobuf.IConversionOptions): { [key: string]: any };
14146
+ }
14147
+ interface ISplitPaymentUpdateMessage { splitId?: string | null; participantJid?: string | null; }
14148
+ class SplitPaymentUpdateMessage implements ISplitPaymentUpdateMessage {
14149
+ constructor(properties?: ISplitPaymentUpdateMessage);
14150
+ public splitId?: string | null;
14151
+ public participantJid?: string | null;
14152
+ public static create(properties?: ISplitPaymentUpdateMessage): SplitPaymentUpdateMessage;
14153
+ public static encode(message: ISplitPaymentUpdateMessage, writer?: $protobuf.Writer): $protobuf.Writer;
14154
+ public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): SplitPaymentUpdateMessage;
14155
+ public static fromObject(value: { [key: string]: any }): SplitPaymentUpdateMessage;
14156
+ public static toObject(message: SplitPaymentUpdateMessage, options?: $protobuf.IConversionOptions): { [key: string]: any };
14157
+ }
14158
+ }
14159
+
14160
+ interface IWebMessageInfo {
14161
+ eventInviteAdditionalMetadata?: (any | null);
14162
+ nonJidMentions?: (number | null);
14163
+ hsmTag?: (string | null);
14164
+ ephemeralExpirationTimestamp?: (number | Long | null);
14165
+ scheduledMessageMetadata?: (any | null);
14166
+ decisionId?: (string | null);
14167
+ decisionSources?: (string[] | null);
14168
+ }
14169
+ interface WebMessageInfo extends IWebMessageInfo {}
14170
+ }
@@ -0,0 +1,48 @@
1
+ import type { proto } from '../WAProto/index.js';
2
+
3
+ export interface PaymentAccount {
4
+ type?: string;
5
+ payment_account: {
6
+ account_type?: string;
7
+ identifier_type?: string;
8
+ identifier_value: string;
9
+ institution_name?: string;
10
+ beneficiary_name?: string;
11
+ [key: string]: unknown;
12
+ };
13
+ [key: string]: unknown;
14
+ }
15
+
16
+ export interface ReviewAndPayOptions {
17
+ title?: string;
18
+ subtitle?: string;
19
+ body?: string | { text?: string };
20
+ footer?: string | { text?: string };
21
+ thumbnail?: Buffer | Uint8Array | string;
22
+ jpegThumbnail?: Buffer | Uint8Array | string;
23
+ image?: Buffer | Uint8Array | string;
24
+ currency?: string;
25
+ totalValue?: number;
26
+ totalAmount?: { value: number; offset: number };
27
+ offset?: number;
28
+ referenceId?: string;
29
+ orderDescription?: string;
30
+ itemName?: string;
31
+ itemValue?: number;
32
+ quantity?: number;
33
+ items?: Array<{ name: string; amount: { value: number; offset: number }; quantity: number; [key: string]: unknown }>;
34
+ paymentAccounts?: PaymentAccount[];
35
+ paymentSettings?: PaymentAccount[];
36
+ paymentParams?: Record<string, unknown> | string;
37
+ paymentConfiguration?: string;
38
+ paymentType?: string;
39
+ type?: string;
40
+ additionalNote?: string;
41
+ contextInfo?: proto.IContextInfo;
42
+ [key: string]: unknown;
43
+ }
44
+
45
+ export function buildReviewAndPayMessage(options?: ReviewAndPayOptions): Promise<proto.IMessage>;
46
+ export function sendReviewAndPay(conn: { relayMessage(jid: string, content: proto.IMessage, options?: Record<string, unknown>): Promise<unknown> }, jid: string, options?: ReviewAndPayOptions, relayOptions?: Record<string, unknown>): Promise<unknown>;
47
+ declare const _default: { buildReviewAndPayMessage: typeof buildReviewAndPayMessage; sendReviewAndPay: typeof sendReviewAndPay };
48
+ export default _default;
@@ -1,76 +1,179 @@
1
1
  /**
2
- * Kage Baileys — Native Flow review_and_pay
2
+ * Kage Baileys Native Flow: review_and_pay.
3
+ * The payment details are sent as the documented Native Flow JSON payload;
4
+ * this function does not collect, validate or process actual payments.
3
5
  */
4
- import { normalizeThumbnail } from './media-thumb.js'
6
+ import { normalizeThumbnail } from './media-thumb.js';
5
7
 
6
- export async function buildReviewAndPayMessage({
7
- title = '',
8
- subtitle = '',
9
- body = 'Texto',
10
- footer = 'Footer',
11
- thumbnail,
12
- currency = 'PEN',
13
- totalValue = 137,
14
- offset = 100,
15
- referenceId = 'KFG_001',
16
- orderDescription = 'Descripción',
17
- itemName = 'Producto',
18
- itemValue = 138,
19
- quantity = 1,
20
- additionalNote = 'Nota',
21
- paymentAccounts = [],
22
- contextInfo = {}
23
- } = {}) {
24
- const thumbBuf = thumbnail ? await normalizeThumbnail(thumbnail) : null
25
- const accounts = paymentAccounts.length ? paymentAccounts : [{
26
- type: 'payment_account',
27
- payment_account: {
28
- account_type: 'digital_wallet',
29
- identifier_type: 'phone_number',
30
- identifier_value: '51900000000',
31
- institution_name: 'Yape',
32
- beneficiary_name: 'Pago'
8
+ const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
9
+ const positiveInteger = (value, name) => {
10
+ const number = Number(value);
11
+ if (!Number.isSafeInteger(number) || number <= 0) throw new TypeError(`${name} must be a positive safe integer`);
12
+ return number;
13
+ };
14
+ const amountObject = (value, offset, name) => {
15
+ if (isObject(value)) {
16
+ return {
17
+ value: positiveInteger(value.value, `${name}.value`),
18
+ offset: positiveInteger(value.offset, `${name}.offset`)
19
+ };
20
+ }
21
+ return { value: positiveInteger(value, `${name}.value`), offset: positiveInteger(offset, `${name}.offset`) };
22
+ };
23
+
24
+ function normalizePaymentAccounts(accounts) {
25
+ if (accounts == null) return [];
26
+ if (!Array.isArray(accounts)) throw new TypeError('paymentAccounts must be an array');
27
+ return accounts.map((entry, index) => {
28
+ if (!isObject(entry)) throw new TypeError(`paymentAccounts[${index}] must be an object`);
29
+ const paymentAccount = entry.payment_account ?? entry.paymentAccount;
30
+ if (!isObject(paymentAccount)) throw new TypeError(`paymentAccounts[${index}].payment_account is required`);
31
+ const identifier = paymentAccount.identifier_value ?? paymentAccount.identifierValue;
32
+ if (typeof identifier !== 'string' || !identifier.trim()) {
33
+ throw new TypeError(`paymentAccounts[${index}] needs a nonempty identifier_value`);
34
+ }
35
+ const result = { ...entry, type: entry.type || 'payment_account', payment_account: { ...paymentAccount } };
36
+ delete result.paymentAccount;
37
+ if (result.payment_account.identifierValue !== undefined && result.payment_account.identifier_value === undefined) {
38
+ result.payment_account.identifier_value = result.payment_account.identifierValue;
39
+ }
40
+ delete result.payment_account.identifierValue;
41
+ if (result.payment_account.accountType && !result.payment_account.account_type) {
42
+ result.payment_account.account_type = result.payment_account.accountType;
43
+ }
44
+ if (result.payment_account.identifierType && !result.payment_account.identifier_type) {
45
+ result.payment_account.identifier_type = result.payment_account.identifierType;
46
+ }
47
+ if (result.payment_account.institutionName && !result.payment_account.institution_name) {
48
+ result.payment_account.institution_name = result.payment_account.institutionName;
33
49
  }
34
- }]
35
- const buttonParams = {
50
+ if (result.payment_account.beneficiaryName && !result.payment_account.beneficiary_name) {
51
+ result.payment_account.beneficiary_name = result.payment_account.beneficiaryName;
52
+ }
53
+ delete result.payment_account.accountType;
54
+ delete result.payment_account.identifierType;
55
+ delete result.payment_account.institutionName;
56
+ delete result.payment_account.beneficiaryName;
57
+ return result;
58
+ });
59
+ }
60
+
61
+ function normalizePaymentParams(options) {
62
+ let supplied = options.paymentParams ?? options.buttonParams ?? options.payment_params;
63
+ if (typeof supplied === 'string') {
64
+ try { supplied = JSON.parse(supplied); }
65
+ catch (error) { throw new TypeError(`paymentParams is not valid JSON: ${error.message}`); }
66
+ }
67
+ if (supplied != null && !isObject(supplied)) throw new TypeError('paymentParams must be an object or JSON string');
68
+
69
+ const currency = String(options.currency ?? supplied?.currency ?? 'PEN').toUpperCase();
70
+ if (!/^[A-Z]{3}$/.test(currency)) throw new TypeError('currency must be a three-letter ISO code');
71
+
72
+ const totalAmount = options.totalAmount ?? supplied?.total_amount ?? supplied?.totalAmount;
73
+ const orderItems = options.items ?? supplied?.order?.items ?? [{
74
+ name: options.itemName ?? 'Producto',
75
+ amount: amountObject(options.itemValue ?? 138, options.offset ?? 100, 'item.amount'),
76
+ quantity: positiveInteger(options.quantity ?? 1, 'quantity')
77
+ }];
78
+ if (!Array.isArray(orderItems) || orderItems.length === 0) throw new TypeError('order.items must contain at least one item');
79
+
80
+ const normalizedItems = orderItems.map((item, index) => {
81
+ if (!isObject(item)) throw new TypeError(`order.items[${index}] must be an object`);
82
+ const name = item.name ?? item.title;
83
+ if (typeof name !== 'string' || !name.trim()) throw new TypeError(`order.items[${index}].name is required`);
84
+ const itemAmount = item.amount ?? { value: options.itemValue ?? 138, offset: options.offset ?? 100 };
85
+ return {
86
+ ...item,
87
+ name: name.trim(),
88
+ amount: amountObject(itemAmount, options.offset ?? 100, `order.items[${index}].amount`),
89
+ quantity: positiveInteger(item.quantity ?? 1, `order.items[${index}].quantity`)
90
+ };
91
+ });
92
+
93
+ const accounts = options.paymentAccounts ?? options.paymentSettings ?? options.payment_settings ?? supplied?.payment_settings ?? [];
94
+ const params = {
36
95
  currency,
37
- payment_configuration: '',
38
- payment_type: 'upr',
39
- total_amount: { value: totalValue, offset },
40
- reference_id: referenceId,
41
- type: 'physical-goods',
96
+ payment_configuration: options.paymentConfiguration ?? supplied?.payment_configuration ?? '',
97
+ payment_type: options.paymentType ?? supplied?.payment_type ?? 'upr',
98
+ total_amount: amountObject(totalAmount ?? { value: options.totalValue ?? 137, offset: options.offset ?? 100 }, options.offset ?? 100, 'total_amount'),
99
+ reference_id: String(options.referenceId ?? options.reference_id ?? supplied?.reference_id ?? `KAGE_${Date.now()}`),
100
+ type: options.type ?? supplied?.type ?? 'physical-goods',
42
101
  order: {
43
- status: 'pending',
44
- description: orderDescription,
45
- order_type: 'PAYMENT_REQUEST',
46
- items: [{ name: itemName, amount: { value: itemValue, offset }, quantity }]
102
+ ...(isObject(supplied?.order) ? supplied.order : {}),
103
+ status: options.orderStatus ?? supplied?.order?.status ?? 'pending',
104
+ description: options.orderDescription ?? supplied?.order?.description ?? 'Descripción',
105
+ order_type: options.orderType ?? supplied?.order?.order_type ?? 'PAYMENT_REQUEST',
106
+ items: normalizedItems
47
107
  },
48
- payment_settings: accounts,
49
- additional_note: additionalNote,
50
- share_payment_status: false,
51
- is_soft_deleted: false
108
+ payment_settings: normalizePaymentAccounts(accounts),
109
+ additional_note: options.additionalNote ?? options.additional_note ?? supplied?.additional_note ?? '',
110
+ share_payment_status: options.sharePaymentStatus ?? supplied?.share_payment_status ?? false,
111
+ is_soft_deleted: options.isSoftDeleted ?? supplied?.is_soft_deleted ?? false
112
+ };
113
+
114
+ if (!params.reference_id.trim()) throw new TypeError('referenceId cannot be empty');
115
+ if (supplied) {
116
+ const merged = { ...supplied, ...params };
117
+ if (isObject(supplied.order)) merged.order = { ...supplied.order, ...params.order };
118
+ return merged;
119
+ }
120
+ return params;
121
+ }
122
+
123
+ /** Build a relayMessage-compatible interactiveMessage with a review_and_pay button. */
124
+ export async function buildReviewAndPayMessage(options = {}) {
125
+ if (!isObject(options)) throw new TypeError('buildReviewAndPayMessage options must be an object');
126
+
127
+ const headerOptions = isObject(options.header) ? options.header : {};
128
+ const thumbnailInput = options.thumbnail ?? options.jpegThumbnail ?? options.image ?? headerOptions.jpegThumbnail;
129
+ const thumbnail = thumbnailInput == null ? null : await normalizeThumbnail(thumbnailInput, {
130
+ maxBytes: options.maxThumbnailBytes ?? 64_000,
131
+ fetchTimeout: options.fetchTimeout ?? 20_000,
132
+ strict: true
133
+ });
134
+ const paymentParams = normalizePaymentParams(options);
135
+ const buttonParamsJson = JSON.stringify(paymentParams);
136
+ if (Buffer.byteLength(buttonParamsJson, 'utf8') > 64_000) throw new RangeError('review_and_pay button parameters exceed 64 KB');
137
+
138
+ const title = options.title ?? headerOptions.title ?? '';
139
+ const subtitle = options.subtitle ?? headerOptions.subtitle ?? '';
140
+ const body = typeof options.body === 'string' ? options.body : (options.body?.text ?? 'Texto');
141
+ const footer = typeof options.footer === 'string' ? options.footer : (options.footer?.text ?? 'Footer');
142
+ if (typeof title !== 'string' || typeof subtitle !== 'string' || typeof body !== 'string' || typeof footer !== 'string') {
143
+ throw new TypeError('header title, subtitle, body and footer must be strings');
52
144
  }
145
+ if (options.contextInfo != null && !isObject(options.contextInfo)) throw new TypeError('contextInfo must be an object');
146
+
147
+ const header = {
148
+ ...headerOptions,
149
+ title,
150
+ subtitle,
151
+ hasMediaAttachment: Boolean(thumbnail),
152
+ ...(thumbnail ? { jpegThumbnail: thumbnail } : {})
153
+ };
154
+ if (!thumbnail) delete header.jpegThumbnail;
155
+
53
156
  return {
54
157
  interactiveMessage: {
55
- header: {
56
- title: title || '',
57
- subtitle: subtitle || '',
58
- hasMediaAttachment: !!thumbBuf,
59
- ...(thumbBuf ? { jpegThumbnail: thumbBuf } : {})
60
- },
158
+ header,
61
159
  body: { text: body },
62
160
  footer: { text: footer },
63
161
  nativeFlowMessage: {
64
- buttons: [{ name: 'review_and_pay', buttonParamsJson: JSON.stringify(buttonParams) }]
162
+ buttons: [{ name: 'review_and_pay', buttonParamsJson }],
163
+ messageParamsJson: '{}',
164
+ messageVersion: 1
65
165
  },
66
- contextInfo: contextInfo || {}
166
+ contextInfo: options.contextInfo ? { ...options.contextInfo } : {}
67
167
  }
68
- }
168
+ };
69
169
  }
70
170
 
71
- export async function sendReviewAndPay(conn, jid, options = {}, relayOpts = {}) {
72
- const content = await buildReviewAndPayMessage(options)
73
- return conn.relayMessage(jid, content, relayOpts)
171
+ /** Build and relay the Native Flow payment request through an authenticated Baileys socket. */
172
+ export async function sendReviewAndPay(conn, jid, options = {}, relayOptions = {}) {
173
+ if (!conn || typeof conn.relayMessage !== 'function') throw new TypeError('A connected Baileys socket with relayMessage is required');
174
+ if (typeof jid !== 'string' || !jid.trim()) throw new TypeError('A destination JID is required');
175
+ const payload = await buildReviewAndPayMessage(options);
176
+ return conn.relayMessage(jid, payload, relayOptions ?? {});
74
177
  }
75
178
 
76
- export default { buildReviewAndPayMessage, sendReviewAndPay }
179
+ export default { buildReviewAndPayMessage, sendReviewAndPay };
@@ -0,0 +1,7 @@
1
+ export interface ThumbnailOptions { maxBytes?: number; fetchTimeout?: number; maxDownloadBytes?: number; strict?: boolean }
2
+ export function isDataUrl(value: unknown): value is string;
3
+ export function stripDataUrl(value: string): string;
4
+ export function normalizeThumbnail(input: Buffer | Uint8Array | string | null | undefined, options?: ThumbnailOptions): Promise<Buffer | null>;
5
+ export function ensureJpegThumbnail<T extends Record<string, any>>(message: T, options?: ThumbnailOptions): Promise<T>;
6
+ declare const _default: { normalizeThumbnail: typeof normalizeThumbnail; ensureJpegThumbnail: typeof ensureJpegThumbnail; isDataUrl: typeof isDataUrl; stripDataUrl: typeof stripDataUrl };
7
+ export default _default;