@x4r1s3/baileys 0.0.0-stage → 1.0.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.
Files changed (183) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1262 -2
  3. package/SECURITY.md +47 -0
  4. package/WAProto/V +1 -0
  5. package/WAProto/WAProto.proto +8892 -0
  6. package/WAProto/index.d.ts +104128 -0
  7. package/WAProto/index.js +334920 -0
  8. package/assets/rolling-circle.svg +133 -0
  9. package/assets/x4r1s3-banner.svg +32 -0
  10. package/engine-requirements.js +27 -0
  11. package/lib/Builders/A2UI.js +245 -0
  12. package/lib/Builders/AIRich.js +179 -0
  13. package/lib/Builders/Button.js +108 -0
  14. package/lib/Builders/CFC.js +284 -0
  15. package/lib/Builders/Carousel.js +81 -0
  16. package/lib/Call/THIRD_PARTY_LICENSE.txt +21 -0
  17. package/lib/Call/audio-feeder.mjs +179 -0
  18. package/lib/Call/audio-recorder.mjs +250 -0
  19. package/lib/Call/fetch-wasm-resources.mjs +104 -0
  20. package/lib/Call/index.mjs +680 -0
  21. package/lib/Call/relay-transport.mjs +563 -0
  22. package/lib/Call/signaling.mjs +641 -0
  23. package/lib/Call/types.mjs +17 -0
  24. package/lib/Call/video-feeder.mjs +94 -0
  25. package/lib/Call/wasm-engine.mjs +1372 -0
  26. package/lib/Call/worker-bootstrap.mjs +1042 -0
  27. package/lib/Defaults/ban-checker.js +56 -0
  28. package/lib/Defaults/index.js +170 -0
  29. package/lib/Signal/Group/ciphertext-message.js +23 -0
  30. package/lib/Signal/Group/group-session-builder.js +41 -0
  31. package/lib/Signal/Group/group_cipher.js +93 -0
  32. package/lib/Signal/Group/index.js +23 -0
  33. package/lib/Signal/Group/keyhelper.js +29 -0
  34. package/lib/Signal/Group/sender-chain-key.js +37 -0
  35. package/lib/Signal/Group/sender-key-distribution-message.js +74 -0
  36. package/lib/Signal/Group/sender-key-message.js +77 -0
  37. package/lib/Signal/Group/sender-key-name.js +59 -0
  38. package/lib/Signal/Group/sender-key-record.js +52 -0
  39. package/lib/Signal/Group/sender-key-state.js +95 -0
  40. package/lib/Signal/Group/sender-message-key.js +37 -0
  41. package/lib/Signal/libsignal.js +440 -0
  42. package/lib/Signal/lid-mapping.js +292 -0
  43. package/lib/Socket/Client/index.js +14 -0
  44. package/lib/Socket/Client/types.js +22 -0
  45. package/lib/Socket/Client/websocket.js +65 -0
  46. package/lib/Socket/aigroups.js +327 -0
  47. package/lib/Socket/ban-checker.js +165 -0
  48. package/lib/Socket/business.js +419 -0
  49. package/lib/Socket/chats.js +1921 -0
  50. package/lib/Socket/communities.js +443 -0
  51. package/lib/Socket/graphql.js +911 -0
  52. package/lib/Socket/groups.js +561 -0
  53. package/lib/Socket/index.js +49 -0
  54. package/lib/Socket/interactive-handler.js +612 -0
  55. package/lib/Socket/interop.js +575 -0
  56. package/lib/Socket/managed-account.js +220 -0
  57. package/lib/Socket/messages-recv.js +2191 -0
  58. package/lib/Socket/messages-send.js +4104 -0
  59. package/lib/Socket/mex.js +53 -0
  60. package/lib/Socket/newsletter.js +291 -0
  61. package/lib/Socket/privacy.js +458 -0
  62. package/lib/Socket/registration.js +440 -0
  63. package/lib/Socket/socket.js +1029 -0
  64. package/lib/Socket/status-actions.js +287 -0
  65. package/lib/Socket/username.js +241 -0
  66. package/lib/Store/index.js +16 -0
  67. package/lib/Store/make-cache-manager-store.js +101 -0
  68. package/lib/Store/make-in-memory-store.js +432 -0
  69. package/lib/Store/make-ordered-dictionary.js +90 -0
  70. package/lib/Store/object-repository.js +35 -0
  71. package/lib/Types/Auth.js +13 -0
  72. package/lib/Types/Bussines.js +13 -0
  73. package/lib/Types/Call.js +13 -0
  74. package/lib/Types/Chat.js +19 -0
  75. package/lib/Types/Contact.js +13 -0
  76. package/lib/Types/Events.js +13 -0
  77. package/lib/Types/GroupMetadata.js +13 -0
  78. package/lib/Types/Label.js +36 -0
  79. package/lib/Types/LabelAssociation.js +18 -0
  80. package/lib/Types/Message.js +30 -0
  81. package/lib/Types/Mex.js +53 -0
  82. package/lib/Types/Product.js +13 -0
  83. package/lib/Types/RichType.js +34 -0
  84. package/lib/Types/Signal.js +13 -0
  85. package/lib/Types/Socket.js +14 -0
  86. package/lib/Types/State.js +60 -0
  87. package/lib/Types/USync.js +13 -0
  88. package/lib/Types/index.js +37 -0
  89. package/lib/Utils/auth-utils.js +313 -0
  90. package/lib/Utils/ban-checker.js +48 -0
  91. package/lib/Utils/bot-capabilities.js +96 -0
  92. package/lib/Utils/bot-planning-replay.js +177 -0
  93. package/lib/Utils/browser-utils.js +40 -0
  94. package/lib/Utils/business.js +242 -0
  95. package/lib/Utils/c2582.js +147 -0
  96. package/lib/Utils/chat-utils.js +905 -0
  97. package/lib/Utils/companion-reg-client-utils.js +44 -0
  98. package/lib/Utils/consumer-application.js +114 -0
  99. package/lib/Utils/crypto.js +129 -0
  100. package/lib/Utils/decode-wa-message.js +496 -0
  101. package/lib/Utils/direct-chat-theme.js +164 -0
  102. package/lib/Utils/event-buffer.js +601 -0
  103. package/lib/Utils/experimental-proto.js +206 -0
  104. package/lib/Utils/games/miniapp.js +17 -0
  105. package/lib/Utils/games/slot-machine.js +270 -0
  106. package/lib/Utils/games/website-preview.js +306 -0
  107. package/lib/Utils/generics.js +402 -0
  108. package/lib/Utils/group-history.js +68 -0
  109. package/lib/Utils/group-wallpaper.js +168 -0
  110. package/lib/Utils/history.js +162 -0
  111. package/lib/Utils/identity-change-handler.js +60 -0
  112. package/lib/Utils/index.js +61 -0
  113. package/lib/Utils/jid-display-normalization.js +221 -0
  114. package/lib/Utils/link-preview.js +96 -0
  115. package/lib/Utils/logger.js +14 -0
  116. package/lib/Utils/lt-hash.js +19 -0
  117. package/lib/Utils/make-mutex.js +44 -0
  118. package/lib/Utils/message-composer.js +709 -0
  119. package/lib/Utils/message-inspect.js +79 -0
  120. package/lib/Utils/message-retry-manager.js +253 -0
  121. package/lib/Utils/message-security.js +167 -0
  122. package/lib/Utils/messages-media.js +1027 -0
  123. package/lib/Utils/messages.js +2467 -0
  124. package/lib/Utils/meta-ai-msmsg.js +215 -0
  125. package/lib/Utils/meta-compositing.js +239 -0
  126. package/lib/Utils/native-flow.js +158 -0
  127. package/lib/Utils/newsletter-live-update-utils.js +74 -0
  128. package/lib/Utils/newsletter-status-utils.js +152 -0
  129. package/lib/Utils/noise-handler.js +212 -0
  130. package/lib/Utils/offline-node-processor.js +51 -0
  131. package/lib/Utils/poll-manager.js +206 -0
  132. package/lib/Utils/portable-compat.js +12 -0
  133. package/lib/Utils/pre-key-manager.js +117 -0
  134. package/lib/Utils/process-message.js +610 -0
  135. package/lib/Utils/reporting-utils.js +269 -0
  136. package/lib/Utils/rich-message-utils.js +2841 -0
  137. package/lib/Utils/scheduled-message.js +107 -0
  138. package/lib/Utils/signal.js +212 -0
  139. package/lib/Utils/source-grep.js +57 -0
  140. package/lib/Utils/stanza-ack.js +49 -0
  141. package/lib/Utils/sticker-annotation.js +87 -0
  142. package/lib/Utils/sync-action-utils.js +59 -0
  143. package/lib/Utils/tc-token-utils.js +174 -0
  144. package/lib/Utils/use-multi-file-auth-state.js +132 -0
  145. package/lib/Utils/use-single-file-auth-state.js +108 -0
  146. package/lib/Utils/use-sqlite-auth-state.js +120 -0
  147. package/lib/Utils/validate-connection.js +220 -0
  148. package/lib/Utils/view-once-utils.js +218 -0
  149. package/lib/Utils/voip-rekey.js +32 -0
  150. package/lib/Utils/website-preview.js +27 -0
  151. package/lib/Utils/welcome-flow.js +228 -0
  152. package/lib/Utils/x4r1s3.js +144 -0
  153. package/lib/WABinary/constants.js +1475 -0
  154. package/lib/WABinary/decode.js +273 -0
  155. package/lib/WABinary/encode.js +231 -0
  156. package/lib/WABinary/generic-utils.js +242 -0
  157. package/lib/WABinary/index.js +17 -0
  158. package/lib/WABinary/jid-utils.js +107 -0
  159. package/lib/WABinary/types.js +13 -0
  160. package/lib/WAM/BinaryInfo.js +21 -0
  161. package/lib/WAM/constants.js +22864 -0
  162. package/lib/WAM/encode.js +161 -0
  163. package/lib/WAM/index.js +15 -0
  164. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +108 -0
  165. package/lib/WAUSync/Protocols/USyncContactProtocol.js +68 -0
  166. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +65 -0
  167. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +38 -0
  168. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +82 -0
  169. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +40 -0
  170. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +37 -0
  171. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +49 -0
  172. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +46 -0
  173. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +36 -0
  174. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +62 -0
  175. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +40 -0
  176. package/lib/WAUSync/Protocols/index.js +24 -0
  177. package/lib/WAUSync/USyncQuery.js +213 -0
  178. package/lib/WAUSync/USyncUser.js +66 -0
  179. package/lib/WAUSync/index.js +15 -0
  180. package/lib/antiban.cjs +4726 -0
  181. package/lib/index.d.ts +1285 -0
  182. package/lib/index.js +30 -0
  183. package/package.json +125 -4
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Optional WhatsApp registration-status checker.
3
+ *
4
+ * This module is deliberately opt-in. It does not run during installation,
5
+ * connection setup, or message sending, and it does not contain credentials.
6
+ * Callers should review the endpoint and applicable terms before use.
7
+ */
8
+
9
+ const cleanNumber = (value) => String(value ?? '').replace(/[\s().\-/]/g, '').replace(/^00/, '').replace(/^\+/, '');
10
+
11
+ export const normalizeBanCheckNumber = (value) => {
12
+ const number = cleanNumber(typeof value === 'object' ? value.number : value);
13
+ if (!/^\d{6,15}$/.test(number)) throw new TypeError('number must be an international phone number');
14
+ return `+${number}`;
15
+ };
16
+
17
+ export const checkStatusWA = async (number, options = {}) => {
18
+ const normalized = normalizeBanCheckNumber(number);
19
+ const endpoint = options.endpoint || 'https://v.whatsapp.net/v2/exist';
20
+ const fetchImpl = options.fetch || globalThis.fetch;
21
+ if (typeof fetchImpl !== 'function') throw new TypeError('a fetch implementation is required');
22
+ const url = new URL(endpoint);
23
+ url.searchParams.set('in', normalized.slice(1));
24
+ const response = await fetchImpl(url, {
25
+ method: 'GET',
26
+ headers: { ...(options.headers || {}) },
27
+ signal: options.signal
28
+ });
29
+ let body = null;
30
+ try { body = await response.json(); } catch { body = null; }
31
+ const reason = String(body?.reason || body?.error || body?.status || '').toLowerCase();
32
+ let status = 'unknown';
33
+ if (response.status === 429 || /rate.?limit|too many/.test(reason)) status = 'rate_limited';
34
+ else if (/blocked|official|banned|ban|temporar|perman/.test(reason)) status = /banned|ban|temporar|perman/.test(reason) ? 'banned' : 'blocked';
35
+ else if (/not.?registered|does.?not.?exist/.test(reason)) status = 'not_registered';
36
+ else if (response.ok) status = 'active';
37
+ return {
38
+ number: normalized,
39
+ status,
40
+ isBanned: status === 'banned',
41
+ isNeedOfficialWa: status === 'blocked',
42
+ diagnostics: options.diagnostic === true ? {
43
+ httpStatus: response.status,
44
+ ok: response.ok,
45
+ bodyKeys: body && typeof body === 'object' ? Object.keys(body).sort() : []
46
+ } : undefined
47
+ };
48
+ };
@@ -0,0 +1,96 @@
1
+ /**
2
+ * @X4R1S3
3
+ *
4
+ * File: lib/Utils/bot-capabilities.js
5
+ * About: Bot capabilities module for the X4R1S3 WhatsApp protocol client.
6
+ * Important exports: BotCapabilityType, normalizeBotCapabilities, buildBotCapabilityMetadata, buildBotRichResponse, capability
7
+ * Directions: Import the listed exports and preserve protocol, validation, and compatibility invariants when modifying.
8
+ *
9
+ * Copyright and attribution notice.
10
+ * Do not copy, reproduce, redistribute, modify, or create derivative works
11
+ * from this source without explicit written permission.
12
+ */
13
+ import { proto } from '../../WAProto/index.js';
14
+
15
+ /**
16
+ * Numeric capability values exposed by WAProto.BotCapabilityMetadata.
17
+ * Keep this derived from the generated protobuf so callers cannot drift from
18
+ * the checked-in schema.
19
+ */
20
+ export const BotCapabilityType = proto.BotCapabilityMetadata.BotCapabilityType;
21
+
22
+ const capabilityNames = new Set(
23
+ Object.keys(BotCapabilityType).filter(name => Number.isNaN(Number(name)))
24
+ );
25
+
26
+ /** Normalize enum names/numbers and reject unknown capability values. */
27
+ export const normalizeBotCapabilities = (capabilities = []) => {
28
+ if (!Array.isArray(capabilities)) {
29
+ throw new TypeError('capabilities must be an array');
30
+ }
31
+ const values = capabilities.map(capability => {
32
+ if (typeof capability === 'string') {
33
+ if (!capabilityNames.has(capability)) {
34
+ throw new TypeError(`Unknown bot capability: ${capability}`);
35
+ }
36
+ return BotCapabilityType[capability];
37
+ }
38
+ if (Number.isInteger(capability) && BotCapabilityType[capability] !== undefined) {
39
+ return capability;
40
+ }
41
+ throw new TypeError(`Invalid bot capability: ${String(capability)}`);
42
+ });
43
+ return [...new Set(values)];
44
+ };
45
+
46
+ export const buildBotCapabilityMetadata = (capabilities = []) => ({
47
+ capabilities: normalizeBotCapabilities(capabilities)
48
+ });
49
+
50
+ /**
51
+ * Build the canonical wrapper used by WhatsApp's bot rich-response messages.
52
+ * The capability list is deliberately explicit; unknown or duplicate values
53
+ * are never put on the wire.
54
+ */
55
+ export const buildBotRichResponse = ({
56
+ text,
57
+ submessages,
58
+ capabilities = [],
59
+ botMetadata = {},
60
+ botJid = '867051314767696@bot',
61
+ richResponse = {}
62
+ } = {}) => {
63
+ const resolvedSubmessages = submessages || (text == null ? [] : [{
64
+ messageType: proto.AIRichResponseSubMessageType.AI_RICH_RESPONSE_TEXT,
65
+ messageText: String(text)
66
+ }]);
67
+ return {
68
+ messageContextInfo: {
69
+ botMetadata: {
70
+ ...botMetadata,
71
+ capabilityMetadata: buildBotCapabilityMetadata(capabilities)
72
+ }
73
+ },
74
+ botForwardedMessage: {
75
+ message: {
76
+ richResponseMessage: {
77
+ messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD,
78
+ submessages: resolvedSubmessages,
79
+ ...richResponse,
80
+ contextInfo: {
81
+ isForwarded: true,
82
+ forwardingScore: 1,
83
+ forwardedAiBotMessageInfo: { botJid },
84
+ forwardOrigin: 4,
85
+ ...(richResponse.contextInfo || {})
86
+ }
87
+ }
88
+ }
89
+ }
90
+ };
91
+ };
92
+
93
+ export const capability = (name) => {
94
+ if (!capabilityNames.has(name)) throw new TypeError(`Unknown bot capability: ${name}`);
95
+ return BotCapabilityType[name];
96
+ };
@@ -0,0 +1,177 @@
1
+ /**
2
+ * @X4R1S3
3
+ *
4
+ * File: lib/Utils/bot-planning-replay.js
5
+ * About: Bot planning replay module for the X4R1S3 WhatsApp protocol client.
6
+ * Important exports: replayPlanning, replayPlanningOnly, buildReasoningSteps, buildSearchSteps, mixedSteps
7
+ * Directions: Import the listed exports and preserve protocol, validation, and compatibility invariants when modifying.
8
+ *
9
+ * Copyright and attribution notice.
10
+ * Do not copy, reproduce, redistribute, modify, or create derivative works
11
+ * from this source without explicit written permission.
12
+ */
13
+ /**
14
+ * Lia@Changes [WIP]
15
+ * botPlanningReplay — Meta AI-style live reasoning feed.
16
+ *
17
+ * UNIVERSAL VERSION: Works on ALL WhatsApp clients.
18
+ * - Native Meta AI rendering for compatible clients
19
+ * - Plain text fallback for regular clients (no "Update WhatsApp")
20
+ *
21
+ * Flow:
22
+ * Send placeholder (all steps pending)
23
+ * → edit: step[0] → DONE
24
+ * → edit: step[1] → DONE
25
+ * → ...
26
+ * → MESSAGE_EDIT: final answer on the same message key
27
+ *
28
+ * If you use or copy this code, please credit @X4R1S3/bailey.
29
+ */
30
+
31
+ import { proto } from '../../WAProto/index.js';
32
+ import {
33
+ buildCompositingPlaceholder,
34
+ buildProgressIndicator,
35
+ buildPlainPlaceholder,
36
+ PlanningStepStatus
37
+ } from './meta-compositing.js';
38
+ import { BOT_RENDERING_CONFIG_METADATA } from '../Defaults/index.js';
39
+ import { delay } from './generics.js';
40
+
41
+ // ─── Internal: build native Meta AI frame ──────────────────────────────────
42
+ const buildReplayFrame = (description, steps, placeholderText = '') => {
43
+ return buildCompositingPlaceholder({ description, steps, placeholderText });
44
+ };
45
+
46
+ // ─── Internal: edit planning bubble (native Meta AI) ───────────────────────
47
+ const editPlanningBubble = async (sock, jid, key, description, steps, placeholderText) => {
48
+ const updated = buildReplayFrame(description, steps, placeholderText);
49
+ await sock.sendMessage(jid, { raw: true, edit: key, ...updated });
50
+ };
51
+
52
+ // ─── Internal: edit plain text bubble (universal) ──────────────────────────
53
+ const editPlainBubble = async (sock, jid, key, description, steps, placeholderText) => {
54
+ const updated = buildPlainPlaceholder(description, steps, placeholderText);
55
+ await sock.sendMessage(jid, { edit: key, ...updated });
56
+ };
57
+
58
+ /**
59
+ * replayPlanning — full live planning animation (UNIVERSAL).
60
+ */
61
+ export const replayPlanning = async (sock, jid, steps, finalContent, {
62
+ description = 'Thinking…',
63
+ placeholderText = '',
64
+ stepDelayMs = 900,
65
+ finalPauseMs = 600,
66
+ abortOnDisconnect = true,
67
+ sendOptions = {},
68
+ useNativeMeta = false
69
+ } = {}) => {
70
+ if (!steps?.length) {
71
+ throw new Error('replayPlanning: steps array must have at least one entry');
72
+ }
73
+
74
+ let aborted = false;
75
+ const onClose = () => { aborted = true; };
76
+ if (abortOnDisconnect) {
77
+ sock.ev?.once?.('connection.update', ({ connection }) => {
78
+ if (connection === 'close') onClose();
79
+ });
80
+ }
81
+
82
+ // Show typing
83
+ await sock.sendPresenceUpdate('composing', jid);
84
+
85
+ // Build initial steps (all pending)
86
+ const initialSteps = steps.map(step => ({
87
+ ...step,
88
+ status: PlanningStepStatus.IN_PROGRESS
89
+ }));
90
+
91
+ // Determine mode
92
+ const isNative = useNativeMeta && false; // Always false for now — force universal
93
+
94
+ // Send initial placeholder
95
+ let placeholder;
96
+ if (isNative) {
97
+ placeholder = await sock.sendMessage(jid, {
98
+ raw: true,
99
+ ...buildReplayFrame(description, initialSteps, placeholderText)
100
+ });
101
+ } else {
102
+ placeholder = await sock.sendMessage(jid,
103
+ buildPlainPlaceholder(description, initialSteps, placeholderText)
104
+ );
105
+ }
106
+
107
+ const key = placeholder?.key;
108
+
109
+ // Replay loop
110
+ try {
111
+ const currentSteps = [...initialSteps];
112
+
113
+ for (let i = 0; i < currentSteps.length; i++) {
114
+ if (aborted) break;
115
+ await delay(stepDelayMs);
116
+ if (aborted) break;
117
+
118
+ currentSteps[i] = { ...currentSteps[i], status: PlanningStepStatus.DONE };
119
+
120
+ if (key) {
121
+ if (isNative) {
122
+ await editPlanningBubble(sock, jid, key, description, currentSteps, placeholderText);
123
+ } else {
124
+ await editPlainBubble(sock, jid, key, description, currentSteps, placeholderText);
125
+ }
126
+ }
127
+ }
128
+
129
+ if (!aborted && finalPauseMs > 0) {
130
+ await delay(finalPauseMs);
131
+ }
132
+
133
+ } catch (err) {
134
+ // Keep the latest successfully rendered frame if an intermediate edit fails.
135
+ }
136
+
137
+ await sock.sendPresenceUpdate('paused', jid);
138
+
139
+ // Skip the final edit if _skipFinalSend is set (for replayPlanningOnly).
140
+ if (sendOptions._skipFinalSend || !key || aborted) return placeholder;
141
+
142
+ const { _skipFinalSend: _ignored, ...finalSendOptions } = sendOptions;
143
+ return sock.sendMessage(jid, { ...finalContent, edit: key }, finalSendOptions);
144
+ };
145
+
146
+ /**
147
+ * replayPlanningOnly — animation WITHOUT final message.
148
+ */
149
+ export const replayPlanningOnly = async (sock, jid, steps, options = {}) => {
150
+ return replayPlanning(sock, jid, steps, null, {
151
+ ...options,
152
+ sendOptions: { ...options.sendOptions, _skipFinalSend: true }
153
+ });
154
+ };
155
+
156
+ /**
157
+ * buildReasoningSteps — steps with isReasoning: true.
158
+ */
159
+ export const buildReasoningSteps = (titles) =>
160
+ titles.map(title => ({ title, isReasoning: true }));
161
+
162
+ /**
163
+ * buildSearchSteps — steps with isEnhancedSearch: true.
164
+ */
165
+ export const buildSearchSteps = (titles) =>
166
+ titles.map(title => ({ title, isEnhancedSearch: true }));
167
+
168
+ /**
169
+ * mixedSteps — mix reasoning + search + plain steps.
170
+ */
171
+ export const mixedSteps = (defs) =>
172
+ defs.map(({ title, body, type }) => ({
173
+ title,
174
+ ...(body ? { body } : {}),
175
+ ...(type === 'reasoning' ? { isReasoning: true } : {}),
176
+ ...(type === 'search' ? { isEnhancedSearch: true } : {})
177
+ }));
@@ -0,0 +1,40 @@
1
+ /**
2
+ * @X4R1S3
3
+ *
4
+ * File: lib/Utils/browser-utils.js
5
+ * About: Browser utils module for the X4R1S3 WhatsApp protocol client.
6
+ * Important exports: Browsers, getPlatformId
7
+ * Directions: Import the listed exports and preserve protocol, validation, and compatibility invariants when modifying.
8
+ *
9
+ * Copyright and attribution notice.
10
+ * Do not copy, reproduce, redistribute, modify, or create derivative works
11
+ * from this source without explicit written permission.
12
+ */
13
+ import { platform, release } from 'node:os';
14
+ import { proto } from '../../WAProto/index.js';
15
+ const PLATFORM_MAP = {
16
+ aix: 'AIX',
17
+ darwin: 'Mac OS',
18
+ win32: 'Windows',
19
+ android: 'Android',
20
+ freebsd: 'FreeBSD',
21
+ openbsd: 'OpenBSD',
22
+ sunos: 'Solaris',
23
+ linux: undefined,
24
+ haiku: undefined,
25
+ cygwin: undefined,
26
+ netbsd: undefined
27
+ };
28
+ export const Browsers = {
29
+ ubuntu: browser => ['Ubuntu', browser, '22.04.4'],
30
+ macOS: browser => ['Mac OS', browser, '14.4.1'],
31
+ baileys: browser => ['Baileys', browser, '6.5.0'],
32
+ windows: browser => ['Windows', browser, '10.0.22631'],
33
+ android: browser => [browser, 'Android', ''],
34
+ /** The appropriate browser based on your OS & release */
35
+ appropriate: browser => [PLATFORM_MAP[platform()] || 'Ubuntu', browser, release()]
36
+ };
37
+ export const getPlatformId = (browser) => {
38
+ const platformType = proto.DeviceProps.PlatformType[browser.toUpperCase()];
39
+ return platformType ? platformType.toString() : '1'; //chrome
40
+ };
@@ -0,0 +1,242 @@
1
+ /**
2
+ * @X4R1S3
3
+ *
4
+ * File: lib/Utils/business.js
5
+ * About: Business module for the X4R1S3 WhatsApp protocol client.
6
+ * Important exports: parseCatalogNode, parseCollectionsNode, parseOrderDetailsNode, toProductNode, parseProductNode, uploadingNecessaryImagesOfProduct, uploadingNecessaryImages
7
+ * Directions: Import the listed exports and preserve protocol, validation, and compatibility invariants when modifying.
8
+ *
9
+ * Copyright and attribution notice.
10
+ * Do not copy, reproduce, redistribute, modify, or create derivative works
11
+ * from this source without explicit written permission.
12
+ */
13
+ import { Boom } from '@hapi/boom';
14
+ import { createHash } from 'crypto';
15
+ import { createWriteStream, promises as fs } from 'fs';
16
+ import { tmpdir } from 'os';
17
+ import { join } from 'path';
18
+ import { getBinaryNodeChild, getBinaryNodeChildren, getBinaryNodeChildString } from '../WABinary/index.js';
19
+ import { generateMessageIDV2 } from './generics.js';
20
+ import { getStream, getUrlFromDirectPath } from './messages-media.js';
21
+ export const parseCatalogNode = (node) => {
22
+ const catalogNode = getBinaryNodeChild(node, 'product_catalog');
23
+ const products = getBinaryNodeChildren(catalogNode, 'product').map(parseProductNode);
24
+ const paging = getBinaryNodeChild(catalogNode, 'paging');
25
+ return {
26
+ products,
27
+ nextPageCursor: paging ? getBinaryNodeChildString(paging, 'after') : undefined
28
+ };
29
+ };
30
+ export const parseCollectionsNode = (node) => {
31
+ const collectionsNode = getBinaryNodeChild(node, 'collections');
32
+ const collections = getBinaryNodeChildren(collectionsNode, 'collection').map(collectionNode => {
33
+ const id = getBinaryNodeChildString(collectionNode, 'id');
34
+ const name = getBinaryNodeChildString(collectionNode, 'name');
35
+ const products = getBinaryNodeChildren(collectionNode, 'product').map(parseProductNode);
36
+ return {
37
+ id,
38
+ name,
39
+ products,
40
+ status: parseStatusInfo(collectionNode)
41
+ };
42
+ });
43
+ return {
44
+ collections
45
+ };
46
+ };
47
+ export const parseOrderDetailsNode = (node) => {
48
+ const orderNode = getBinaryNodeChild(node, 'order');
49
+ const products = getBinaryNodeChildren(orderNode, 'product').map(productNode => {
50
+ const imageNode = getBinaryNodeChild(productNode, 'image');
51
+ return {
52
+ id: getBinaryNodeChildString(productNode, 'id'),
53
+ name: getBinaryNodeChildString(productNode, 'name'),
54
+ imageUrl: getBinaryNodeChildString(imageNode, 'url'),
55
+ price: +getBinaryNodeChildString(productNode, 'price'),
56
+ currency: getBinaryNodeChildString(productNode, 'currency'),
57
+ quantity: +getBinaryNodeChildString(productNode, 'quantity')
58
+ };
59
+ });
60
+ const priceNode = getBinaryNodeChild(orderNode, 'price');
61
+ const orderDetails = {
62
+ price: {
63
+ total: +getBinaryNodeChildString(priceNode, 'total'),
64
+ currency: getBinaryNodeChildString(priceNode, 'currency')
65
+ },
66
+ products
67
+ };
68
+ return orderDetails;
69
+ };
70
+ export const toProductNode = (productId, product) => {
71
+ const attrs = {};
72
+ const content = [];
73
+ if (typeof productId !== 'undefined') {
74
+ content.push({
75
+ tag: 'id',
76
+ attrs: {},
77
+ content: Buffer.from(productId)
78
+ });
79
+ }
80
+ if (typeof product.name !== 'undefined') {
81
+ content.push({
82
+ tag: 'name',
83
+ attrs: {},
84
+ content: Buffer.from(product.name)
85
+ });
86
+ }
87
+ if (typeof product.description !== 'undefined') {
88
+ content.push({
89
+ tag: 'description',
90
+ attrs: {},
91
+ content: Buffer.from(product.description)
92
+ });
93
+ }
94
+ if (typeof product.retailerId !== 'undefined') {
95
+ content.push({
96
+ tag: 'retailer_id',
97
+ attrs: {},
98
+ content: Buffer.from(product.retailerId)
99
+ });
100
+ }
101
+ if (product.images.length) {
102
+ content.push({
103
+ tag: 'media',
104
+ attrs: {},
105
+ content: product.images.map(img => {
106
+ if (!('url' in img)) {
107
+ throw new Boom('Expected img for product to already be uploaded', { statusCode: 400 });
108
+ }
109
+ return {
110
+ tag: 'image',
111
+ attrs: {},
112
+ content: [
113
+ {
114
+ tag: 'url',
115
+ attrs: {},
116
+ content: Buffer.from(img.url.toString())
117
+ }
118
+ ]
119
+ };
120
+ })
121
+ });
122
+ }
123
+ if (typeof product.price !== 'undefined') {
124
+ content.push({
125
+ tag: 'price',
126
+ attrs: {},
127
+ content: Buffer.from(product.price.toString())
128
+ });
129
+ }
130
+ if (typeof product.currency !== 'undefined') {
131
+ content.push({
132
+ tag: 'currency',
133
+ attrs: {},
134
+ content: Buffer.from(product.currency)
135
+ });
136
+ }
137
+ if ('originCountryCode' in product) {
138
+ if (typeof product.originCountryCode === 'undefined') {
139
+ attrs['compliance_category'] = 'COUNTRY_ORIGIN_EXEMPT';
140
+ }
141
+ else {
142
+ content.push({
143
+ tag: 'compliance_info',
144
+ attrs: {},
145
+ content: [
146
+ {
147
+ tag: 'country_code_origin',
148
+ attrs: {},
149
+ content: Buffer.from(product.originCountryCode)
150
+ }
151
+ ]
152
+ });
153
+ }
154
+ }
155
+ if (typeof product.isHidden !== 'undefined') {
156
+ attrs['is_hidden'] = product.isHidden.toString();
157
+ }
158
+ const node = {
159
+ tag: 'product',
160
+ attrs,
161
+ content
162
+ };
163
+ return node;
164
+ };
165
+ export const parseProductNode = (productNode) => {
166
+ const isHidden = productNode.attrs.is_hidden === 'true';
167
+ const id = getBinaryNodeChildString(productNode, 'id');
168
+ const mediaNode = getBinaryNodeChild(productNode, 'media');
169
+ const statusInfoNode = getBinaryNodeChild(productNode, 'status_info');
170
+ const product = {
171
+ id,
172
+ imageUrls: parseImageUrls(mediaNode),
173
+ reviewStatus: {
174
+ whatsapp: getBinaryNodeChildString(statusInfoNode, 'status')
175
+ },
176
+ availability: 'in stock',
177
+ name: getBinaryNodeChildString(productNode, 'name'),
178
+ retailerId: getBinaryNodeChildString(productNode, 'retailer_id'),
179
+ url: getBinaryNodeChildString(productNode, 'url'),
180
+ description: getBinaryNodeChildString(productNode, 'description'),
181
+ price: +getBinaryNodeChildString(productNode, 'price'),
182
+ currency: getBinaryNodeChildString(productNode, 'currency'),
183
+ isHidden
184
+ };
185
+ return product;
186
+ };
187
+ /**
188
+ * Uploads images not already uploaded to WA's servers
189
+ */
190
+ export async function uploadingNecessaryImagesOfProduct(product, waUploadToServer, timeoutMs = 30000) {
191
+ product = {
192
+ ...product,
193
+ images: product.images
194
+ ? await uploadingNecessaryImages(product.images, waUploadToServer, timeoutMs)
195
+ : product.images
196
+ };
197
+ return product;
198
+ }
199
+ /**
200
+ * Uploads images not already uploaded to WA's servers
201
+ */
202
+ export const uploadingNecessaryImages = async (images, waUploadToServer, timeoutMs = 30000) => {
203
+ const results = await Promise.all(images.map(async (img) => {
204
+ if ('url' in img) {
205
+ const url = img.url.toString();
206
+ if (url.includes('.whatsapp.net')) {
207
+ return { url };
208
+ }
209
+ }
210
+ const { stream } = await getStream(img);
211
+ const hasher = createHash('sha256');
212
+ const filePath = join(tmpdir(), 'img' + generateMessageIDV2());
213
+ const encFileWriteStream = createWriteStream(filePath);
214
+ for await (const block of stream) {
215
+ hasher.update(block);
216
+ encFileWriteStream.write(block);
217
+ }
218
+ const sha = hasher.digest('base64');
219
+ const { directPath } = await waUploadToServer(filePath, {
220
+ mediaType: 'product-catalog-image',
221
+ fileEncSha256B64: sha,
222
+ timeoutMs
223
+ });
224
+ await fs.unlink(filePath).catch(err => console.log('Error deleting temp file ', err));
225
+ return { url: getUrlFromDirectPath(directPath) };
226
+ }));
227
+ return results;
228
+ };
229
+ const parseImageUrls = (mediaNode) => {
230
+ const imgNode = getBinaryNodeChild(mediaNode, 'image');
231
+ return {
232
+ requested: getBinaryNodeChildString(imgNode, 'request_image_url'),
233
+ original: getBinaryNodeChildString(imgNode, 'original_image_url')
234
+ };
235
+ };
236
+ const parseStatusInfo = (mediaNode) => {
237
+ const node = getBinaryNodeChild(mediaNode, 'status_info');
238
+ return {
239
+ status: getBinaryNodeChildString(node, 'status'),
240
+ canAppeal: getBinaryNodeChildString(node, 'can_appeal') === 'true'
241
+ };
242
+ };