kage-baileys 3.0.6 → 3.2.4

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 (217) hide show
  1. package/Example/connection.cjs +4 -0
  2. package/README.MD +4726 -48
  3. package/README.md +5941 -0
  4. package/WAProto/WAProto.proto +3395 -415
  5. package/WAProto/compat.cjs +12 -0
  6. package/WAProto/index.d.ts +47104 -19888
  7. package/WAProto/index.js +131979 -57361
  8. package/lib/Addon/http-error.js +43 -0
  9. package/lib/Addon/index.js +32 -0
  10. package/lib/Addon/keyed-db.js +250 -0
  11. package/lib/Addon/link-preview.js +82 -0
  12. package/lib/Defaults/baileys-version.json +3 -0
  13. package/lib/Defaults/connection.js +110 -0
  14. package/lib/Defaults/constants.js +156 -0
  15. package/lib/Defaults/history.js +46 -0
  16. package/lib/Defaults/index.js +230 -0
  17. package/lib/Defaults/media.js +104 -0
  18. package/lib/Defaults/phonenumber-mcc.json +223 -0
  19. package/lib/Defaults/prefix.js +44 -0
  20. package/lib/Extensions/business-advanced.js +382 -0
  21. package/lib/Extensions/business.js +159 -0
  22. package/lib/Extensions/chats-advanced.js +1106 -0
  23. package/lib/Extensions/chats.js +349 -0
  24. package/lib/Extensions/communities-advanced.js +430 -0
  25. package/lib/Extensions/community.js +94 -0
  26. package/lib/Extensions/groups-advanced.js +343 -0
  27. package/lib/Extensions/index.js +30 -0
  28. package/lib/Extensions/messages-recv-advanced.js +1690 -0
  29. package/lib/Extensions/messages-send-advanced.js +622 -0
  30. package/lib/Extensions/messages-send.js +1380 -0
  31. package/lib/Extensions/newsletter-advanced.js +228 -0
  32. package/lib/Extensions/newsletter.js +72 -0
  33. package/lib/Extensions/socket.js +389 -0
  34. package/lib/Modded/message_builder.js +2084 -4
  35. package/lib/Signal/Group/ciphertext-message.js +54 -0
  36. package/lib/Signal/Group/group-session-builder.js +124 -0
  37. package/lib/Signal/Group/group_cipher.js +216 -0
  38. package/lib/Signal/Group/index.js +124 -0
  39. package/lib/Signal/Group/keyhelper.js +108 -0
  40. package/lib/Signal/Group/sender-chain-key.js +83 -0
  41. package/lib/Signal/Group/sender-key-distribution-message.js +157 -0
  42. package/lib/Signal/Group/sender-key-message.js +166 -0
  43. package/lib/Signal/Group/sender-key-name.js +130 -0
  44. package/lib/Signal/Group/sender-key-record.js +113 -0
  45. package/lib/Signal/Group/sender-key-state.js +208 -0
  46. package/lib/Signal/Group/sender-message-key.js +82 -0
  47. package/lib/Signal/libsignal.js +935 -0
  48. package/lib/Signal/lid-mapping.js +545 -1
  49. package/lib/Socket/Client/index.js +60 -0
  50. package/lib/Socket/Client/types.js +51 -0
  51. package/lib/Socket/Client/websocket.js +152 -0
  52. package/lib/Socket/business.js +831 -0
  53. package/lib/Socket/chats.js +2535 -49
  54. package/lib/Socket/communities.js +450 -1
  55. package/lib/Socket/community.js +1022 -0
  56. package/lib/Socket/dugong.js +1 -1
  57. package/lib/Socket/groups.js +747 -0
  58. package/lib/Socket/index.js +60 -2
  59. package/lib/Socket/messages-recv.js +3450 -5
  60. package/lib/Socket/messages-send.js +3123 -0
  61. package/lib/Socket/mex.js +126 -1
  62. package/lib/Socket/newsletter.js +465 -0
  63. package/lib/Socket/socket.js +2217 -1
  64. package/lib/Store/index.js +79 -0
  65. package/lib/Store/make-cache-manager-store.js +186 -0
  66. package/lib/Store/make-in-memory-store.js +878 -0
  67. package/lib/Store/make-ordered-dictionary.js +187 -0
  68. package/lib/Store/object-repository.js +78 -0
  69. package/lib/Types/Auth.js +25 -0
  70. package/lib/Types/Bussines.js +25 -1
  71. package/lib/Types/Call.js +25 -0
  72. package/lib/Types/Chat.js +39 -0
  73. package/lib/Types/Contact.js +25 -0
  74. package/lib/Types/Events.js +25 -0
  75. package/lib/Types/GroupMetadata.js +25 -0
  76. package/lib/Types/Label.js +76 -0
  77. package/lib/Types/LabelAssociation.js +40 -0
  78. package/lib/Types/Message.js +57 -0
  79. package/lib/Types/Mex.js +56 -1
  80. package/lib/Types/MexUpdates.js +46 -0
  81. package/lib/Types/Newsletter.js +56 -0
  82. package/lib/Types/Product.js +25 -0
  83. package/lib/Types/RichType.js +23 -0
  84. package/lib/Types/Signal.js +25 -0
  85. package/lib/Types/Socket.js +25 -0
  86. package/lib/Types/State.js +92 -0
  87. package/lib/Types/USync.js +25 -0
  88. package/lib/Types/index.js +133 -0
  89. package/lib/Utils/auth-utils.js +703 -0
  90. package/lib/Utils/automation-tools.js +51 -16
  91. package/lib/Utils/baileys-event-stream.js +146 -0
  92. package/lib/Utils/browser-utils.js +95 -0
  93. package/lib/Utils/business.js +525 -0
  94. package/lib/Utils/chat-utils.js +1861 -0
  95. package/lib/Utils/companion-reg-client-utils.js +55 -1
  96. package/lib/Utils/crypto.js +355 -0
  97. package/lib/Utils/decode-wa-message.js +709 -0
  98. package/lib/Utils/event-buffer.js +1323 -8
  99. package/lib/Utils/generics.js +945 -1
  100. package/lib/Utils/history.js +266 -0
  101. package/lib/Utils/identity-change-handler.js +62 -1
  102. package/lib/Utils/index.js +114 -0
  103. package/lib/Utils/link-preview.js +179 -0
  104. package/lib/Utils/logger.js +42 -0
  105. package/lib/Utils/lt-hash.js +73 -0
  106. package/lib/Utils/make-mutex.js +104 -0
  107. package/lib/Utils/message-inspector.js +110 -0
  108. package/lib/Utils/message-retry-manager.js +507 -2
  109. package/lib/Utils/messages-media.js +1931 -1
  110. package/lib/Utils/messages.js +3748 -0
  111. package/lib/Utils/noise-handler.js +423 -0
  112. package/lib/Utils/offline-node-processor.js +53 -1
  113. package/lib/Utils/pre-key-manager.js +255 -1
  114. package/lib/Utils/process-message.js +1592 -0
  115. package/lib/Utils/reporting-utils.js +272 -1
  116. package/lib/Utils/rich-message-utils.js +377 -0
  117. package/lib/Utils/rich-messages.js +1 -1
  118. package/lib/Utils/signal.js +437 -0
  119. package/lib/Utils/stanza-ack.js +51 -1
  120. package/lib/Utils/status-refresh.js +37 -0
  121. package/lib/Utils/status-tools.js +4 -2
  122. package/lib/Utils/sync-action-utils.js +63 -1
  123. package/lib/Utils/tc-token-utils.js +185 -1
  124. package/lib/Utils/terminal-banner.js +31 -0
  125. package/lib/Utils/use-multi-file-auth-state.js +271 -0
  126. package/lib/Utils/use-single-file-auth-state.js +108 -0
  127. package/lib/Utils/use-sqlite-auth-state.js +142 -0
  128. package/lib/Utils/validate-connection.js +497 -1
  129. package/lib/Utils/view-once-compat.js +13 -5
  130. package/lib/VoIP/audio-feeder.js +150 -0
  131. package/lib/VoIP/index.js +289 -0
  132. package/lib/VoIP/relay-transport.js +608 -0
  133. package/lib/VoIP/signaling.js +583 -0
  134. package/lib/VoIP/types.js +30 -0
  135. package/lib/VoIP/wasm-engine.js +1261 -2
  136. package/lib/VoIP/worker-bootstrap.js +1090 -2
  137. package/lib/WABinary/constants.js +2805 -0
  138. package/lib/WABinary/decode.js +649 -2
  139. package/lib/WABinary/encode.js +564 -2
  140. package/lib/WABinary/generic-utils.js +401 -0
  141. package/lib/WABinary/index.js +82 -0
  142. package/lib/WABinary/jid-utils.js +290 -0
  143. package/lib/WABinary/types.js +25 -0
  144. package/lib/WAM/BinaryInfo.js +50 -0
  145. package/lib/WAM/constants.js +45747 -0
  146. package/lib/WAM/encode.js +393 -0
  147. package/lib/WAM/index.js +78 -0
  148. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +135 -0
  149. package/lib/WAUSync/Protocols/USyncContactProtocol.js +110 -0
  150. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +142 -0
  151. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +85 -0
  152. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +69 -0
  153. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +107 -0
  154. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +38 -1
  155. package/lib/WAUSync/Protocols/index.js +83 -0
  156. package/lib/WAUSync/USyncQuery.js +241 -2
  157. package/lib/WAUSync/USyncUser.js +86 -0
  158. package/lib/WAUSync/index.js +78 -0
  159. package/lib/assets/wasm/loader.js +1875 -1
  160. package/lib/assets/wasm/worker-modules.js +11047 -1
  161. package/lib/index.d.ts +126 -0
  162. package/lib/index.js +53 -21
  163. package/lib/index.mjs +437 -0
  164. package/licenses/upstream-MIT.txt +22 -0
  165. package/maintenance/api-coverage.json +1642 -0
  166. package/maintenance/archivos-sha256.json +207 -0
  167. package/maintenance/consumer-validation.log +3 -0
  168. package/maintenance/dependency-audit.json +4 -4
  169. package/maintenance/extension-inventory.json +57 -0
  170. package/maintenance/protocol-update.json +1101 -0
  171. package/maintenance/protocol-wire-audit.json +4 -0
  172. package/maintenance/reference-socket-surface.json +209 -0
  173. package/maintenance/resumen-validacion.json +50 -0
  174. package/maintenance/validation.log +2725 -0
  175. package/maintenance/verification.json +566 -0
  176. package/package.json +107 -9
  177. package/scripts/check-imports.cjs +10 -0
  178. package/scripts/check-package.cjs +40 -0
  179. package/scripts/check-syntax.cjs +1 -1
  180. package/scripts/generate-protobuf.cjs +6 -1
  181. package/scripts/generate-public-types.cjs +9 -0
  182. package/scripts/kage-base64-fix.cjs +45 -0
  183. package/scripts/maintenance.cjs +10 -0
  184. package/test/advanced.test.cjs +24 -0
  185. package/test/base64-fix.test.cjs +49 -0
  186. package/test/maintenance.test.cjs +1 -1
  187. package/test/npm-publication.test.cjs +141 -0
  188. package/test/recepcion-reparada.test.cjs +98 -0
  189. package/test/resilience-binary.test.cjs +69 -0
  190. package/test/resilience-transport.test.cjs +34 -0
  191. package/test/types.test.ts +5 -0
  192. package/test/upgrade.test.cjs +104 -0
  193. package/tsconfig.json +20 -0
  194. package/WAProto/p.html +0 -1
  195. package/lib/KageExtra/Modded/message_builder.js +0 -2330
  196. package/lib/KageExtra/VoIP/audio-feeder.js +0 -136
  197. package/lib/KageExtra/VoIP/index.js +0 -282
  198. package/lib/KageExtra/VoIP/relay-transport.js +0 -559
  199. package/lib/KageExtra/VoIP/signaling.js +0 -603
  200. package/lib/KageExtra/VoIP/types.js +0 -17
  201. package/lib/KageExtra/VoIP/wasm-engine.js +0 -1214
  202. package/lib/KageExtra/VoIP/worker-bootstrap.js +0 -1042
  203. package/lib/KageExtra/assets/wasm/loader.js +0 -5
  204. package/lib/KageExtra/assets/wasm/whatsapp.wasm +0 -0
  205. package/lib/KageExtra/assets/wasm/worker-modules.js +0 -273
  206. package/lib/KageExtra/index.js +0 -3
  207. package/lib/KageExtra/package.json +0 -1
  208. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -53
  209. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +0 -24
  210. package/maintenance/revision-full-check.txt +0 -1097
  211. package/maintenance/revision-library-tests.tap +0 -1088
  212. package/maintenance/revision-protobuf.txt +0 -5
  213. package/maintenance/revision-syntax.txt +0 -5
  214. package/maintenance/schema-coverage.json +0 -23
  215. package/maintenance/schema-merge.json +0 -30
  216. package/maintenance/validation-node20.txt +0 -191
  217. package/maintenance/validation-node22.txt +0 -237
@@ -15,4 +15,188 @@
15
15
  return baseContent.length > 0 ? baseContent : undefined;
16
16
  }
17
17
  } exports.buildTcTokenFromJid = buildTcTokenFromJid;
18
- //# sourceMappingURL=tc-token-utils.js.map
18
+ //#
19
+ // Kage: funciones avanzadas.
20
+ const __kageModule187 = (() => {
21
+ const module = { exports: {} }; const exports = module.exports;
22
+ "use strict";
23
+ Object.defineProperty(exports, "__esModule", { value: true });
24
+ exports.TC_TOKEN_INDEX_KEY = void 0;
25
+ exports.readTcTokenIndex = readTcTokenIndex;
26
+ exports.buildMergedTcTokenIndexWrite = buildMergedTcTokenIndexWrite;
27
+ exports.isTcTokenExpired = isTcTokenExpired;
28
+ exports.shouldSendNewTcToken = shouldSendNewTcToken;
29
+ exports.resolveTcTokenJid = resolveTcTokenJid;
30
+ exports.resolveIssuanceJid = resolveIssuanceJid;
31
+ exports.buildTcTokenFromJid = buildTcTokenFromJid;
32
+ exports.storeTcTokensFromIqResult = storeTcTokensFromIqResult;
33
+ const index_js_1 = require("../WABinary/index.js");
34
+ // Same phone-number pattern as WABinary's isJidBot, applied against the user
35
+ // part so the check is invariant to @c.us ↔ @s.whatsapp.net normalization.
36
+ const BOT_PHONE_REGEX = /^1313555\d{4}$|^131655500\d{2}$/;
37
+ /**
38
+ * Mirrors WA Web's `Wid.isRegularUser()` (user ∧ ¬PSA ∧ ¬Bot). Used to gate tctoken
39
+ * storage against malformed notifications — WA Web filters server-side but we
40
+ * defend here for parity with `WAWebSetTcTokenChatAction.handleIncomingTcToken`.
41
+ * Works for both pre- and post-normalized JIDs (`@c.us` vs `@s.whatsapp.net`).
42
+ */
43
+ function isRegularUser(jid) {
44
+ if (!jid)
45
+ return false;
46
+ const user = jid.split('@')[0] ?? '';
47
+ if (user === '0')
48
+ return false; // PSA
49
+ if (BOT_PHONE_REGEX.test(user))
50
+ return false; // Bot by phone pattern
51
+ if ((0, index_js_1.isJidMetaAI)(jid))
52
+ return false; // MetaAI (@bot server)
53
+ return !!((0, index_js_1.isPnUser)(jid) || (0, index_js_1.isLidUser)(jid) || (0, index_js_1.isHostedPnUser)(jid) || (0, index_js_1.isHostedLidUser)(jid) || jid.endsWith('@c.us'));
54
+ }
55
+ const TC_TOKEN_BUCKET_DURATION = 604800; // 7 days
56
+ const TC_TOKEN_NUM_BUCKETS = 4; // ~28-day rolling window
57
+ /** Sentinel key under `tctoken` store holding a JSON array of tracked storage JIDs for cross-session pruning. */
58
+ exports.TC_TOKEN_INDEX_KEY = '__index';
59
+ /** Read the persisted tctoken JID index and return its entries (never contains the sentinel key itself). */
60
+ async function readTcTokenIndex(keys) {
61
+ const data = await keys.get('tctoken', [exports.TC_TOKEN_INDEX_KEY]);
62
+ const entry = data[exports.TC_TOKEN_INDEX_KEY];
63
+ if (!entry?.token?.length)
64
+ return [];
65
+ try {
66
+ const parsed = JSON.parse(Buffer.from(entry.token).toString());
67
+ if (!Array.isArray(parsed))
68
+ return [];
69
+ return parsed.filter((j) => typeof j === 'string' && j.length > 0 && j !== exports.TC_TOKEN_INDEX_KEY);
70
+ }
71
+ catch {
72
+ return [];
73
+ }
74
+ }
75
+ /** Build a SignalDataSet fragment that writes the merged index (persisted ∪ added) under the sentinel key. */
76
+ async function buildMergedTcTokenIndexWrite(keys, addedJids) {
77
+ const persisted = await readTcTokenIndex(keys);
78
+ const merged = new Set(persisted);
79
+ for (const jid of addedJids) {
80
+ if (jid && jid !== exports.TC_TOKEN_INDEX_KEY)
81
+ merged.add(jid);
82
+ }
83
+ return {
84
+ [exports.TC_TOKEN_INDEX_KEY]: { token: Buffer.from(JSON.stringify([...merged])) }
85
+ };
86
+ }
87
+ // WA Web has separate sender/receiver AB props for these but they're identical today
88
+ function isTcTokenExpired(timestamp) {
89
+ if (timestamp === null || timestamp === undefined)
90
+ return true;
91
+ const ts = typeof timestamp === 'string' ? parseInt(timestamp) : timestamp;
92
+ if (isNaN(ts))
93
+ return true;
94
+ const now = Math.floor(Date.now() / 1000);
95
+ const currentBucket = Math.floor(now / TC_TOKEN_BUCKET_DURATION);
96
+ const cutoffBucket = currentBucket - (TC_TOKEN_NUM_BUCKETS - 1);
97
+ const cutoffTimestamp = cutoffBucket * TC_TOKEN_BUCKET_DURATION;
98
+ return ts < cutoffTimestamp;
99
+ }
100
+ function shouldSendNewTcToken(senderTimestamp) {
101
+ if (senderTimestamp === undefined)
102
+ return true;
103
+ const now = Math.floor(Date.now() / 1000);
104
+ const currentBucket = Math.floor(now / TC_TOKEN_BUCKET_DURATION);
105
+ const senderBucket = Math.floor(senderTimestamp / TC_TOKEN_BUCKET_DURATION);
106
+ return currentBucket > senderBucket;
107
+ }
108
+ /** Resolve JID to LID for tctoken storage (WA Web stores under LID) */
109
+ async function resolveTcTokenJid(jid, getLIDForPN) {
110
+ if ((0, index_js_1.isLidUser)(jid))
111
+ return jid;
112
+ const lid = await getLIDForPN(jid);
113
+ return lid ?? jid;
114
+ }
115
+ /** Resolve target JID for issuing privacy token based on AB prop 14303 */
116
+ async function resolveIssuanceJid(jid, issueToLid, getLIDForPN, getPNForLID) {
117
+ if (issueToLid) {
118
+ if ((0, index_js_1.isLidUser)(jid))
119
+ return jid;
120
+ const lid = await getLIDForPN(jid);
121
+ return lid ?? jid;
122
+ }
123
+ if (!(0, index_js_1.isLidUser)(jid))
124
+ return jid;
125
+ if (getPNForLID) {
126
+ const pn = await getPNForLID(jid);
127
+ return pn ?? jid;
128
+ }
129
+ return jid;
130
+ }
131
+ async function buildTcTokenFromJid({ authState, jid, baseContent = [], getLIDForPN }) {
132
+ try {
133
+ const storageJid = await resolveTcTokenJid(jid, getLIDForPN);
134
+ const tcTokenData = await authState.keys.get('tctoken', [storageJid]);
135
+ const entry = tcTokenData?.[storageJid];
136
+ const tcTokenBuffer = entry?.token;
137
+ const timestamp = entry?.timestamp;
138
+ if (!tcTokenBuffer?.length || timestamp === undefined || isTcTokenExpired(timestamp)) {
139
+ if (tcTokenBuffer) {
140
+ // Preserve senderTimestamp so shouldSendNewTcToken() keeps its dedupe state
141
+ // after we drop the unusable peer token. Only wipe the record entirely when
142
+ // there's nothing worth keeping.
143
+ const cleared = entry?.senderTimestamp !== undefined
144
+ ? { token: Buffer.alloc(0), senderTimestamp: entry.senderTimestamp }
145
+ : null;
146
+ await authState.keys.set({ tctoken: { [storageJid]: cleared } });
147
+ }
148
+ return baseContent.length > 0 ? baseContent : undefined;
149
+ }
150
+ baseContent.push({
151
+ tag: 'tctoken',
152
+ attrs: { t: String(timestamp) },
153
+ content: tcTokenBuffer
154
+ });
155
+ return baseContent;
156
+ }
157
+ catch (error) {
158
+ return baseContent.length > 0 ? baseContent : undefined;
159
+ }
160
+ }
161
+ async function storeTcTokensFromIqResult({ result, fallbackJid, keys, getLIDForPN, onNewJidStored }) {
162
+ const tokensNode = (0, index_js_1.getBinaryNodeChild)(result, 'tokens');
163
+ if (!tokensNode)
164
+ return;
165
+ const tokenNodes = (0, index_js_1.getBinaryNodeChildren)(tokensNode, 'token');
166
+ for (const tokenNode of tokenNodes) {
167
+ if (tokenNode.attrs.type !== 'trusted_contact' || !(tokenNode.content instanceof Uint8Array)) {
168
+ continue;
169
+ }
170
+ // In notifications tokenNode.attrs.jid is your own device JID, not the sender's
171
+ const rawJid = (0, index_js_1.jidNormalizedUser)(fallbackJid || tokenNode.attrs.jid);
172
+ if (!isRegularUser(rawJid))
173
+ continue;
174
+ const storageJid = await resolveTcTokenJid(rawJid, getLIDForPN);
175
+ const existingTcData = await keys.get('tctoken', [storageJid]);
176
+ const existingEntry = existingTcData[storageJid];
177
+ const existingTs = existingEntry?.timestamp ? Number(existingEntry.timestamp) : 0;
178
+ const incomingTs = tokenNode.attrs.t ? Number(tokenNode.attrs.t) : 0;
179
+ // timestamp-less tokens would be immediately expired
180
+ if (!incomingTs)
181
+ continue;
182
+ if (existingTs > 0 && existingTs > incomingTs)
183
+ continue;
184
+ await keys.set({
185
+ tctoken: {
186
+ [storageJid]: {
187
+ ...existingEntry,
188
+ token: Buffer.from(tokenNode.content),
189
+ timestamp: tokenNode.attrs.t
190
+ }
191
+ }
192
+ });
193
+ onNewJidStored?.(storageJid);
194
+ }
195
+ }
196
+
197
+ return module.exports;
198
+ })();
199
+ for (const key of Object.keys(__kageModule187)) {
200
+ if (key !== '__esModule' && !Object.prototype.hasOwnProperty.call(exports,key)) Object.defineProperty(exports,key,{enumerable:true,configurable:true,get:()=>__kageModule187[key]});
201
+ }
202
+ Object.defineProperty(exports, Symbol.for('kage.advanced'), {value:__kageModule187, configurable:true});
@@ -0,0 +1,31 @@
1
+ 'use strict';
2
+ const chalk=require('chalk');
3
+ const gradient=require('gradient-string');
4
+ const tinyMap=Object.fromEntries([...('abcdefghijklmnopqrstuvwxyz')].map((c,i)=>[c,[...'ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢ'][i]]));
5
+ function say(text, options={}) {
6
+ const stream=options.stream||process.stdout;
7
+ let rendered=String(text??'').replace(/[\x00-\x08\x0b-\x1f\x7f]/g,'');
8
+ if(options.font==='tiny')rendered=[...rendered.toLowerCase()].map(c=>tinyMap[c]||c).join('');
9
+ else if(options.font==='block')rendered=rendered.toUpperCase().split('\n').map(line=>'▰ '+[...line].join(' ')+' ▰').join('\n');
10
+ else if(options.font==='simple')rendered=rendered.toUpperCase();
11
+ const width=Number(options.width)||stream.columns||80;
12
+ const color=options.forceColor??!!stream.isTTY;
13
+ const colors=(options.colors||[]).filter(name=>typeof chalk[name]==='function');
14
+ rendered=rendered.split('\n').map((line,i)=>{
15
+ const pad=options.align==='center'?Math.max(0,Math.floor((width-[...line].length)/2)):options.align==='right'?Math.max(0,width-[...line].length):0;
16
+ let output=line;
17
+ if(color&&Array.isArray(options.gradient)&&options.gradient.length>=2){try{output=gradient(options.gradient)(line);}catch{}}
18
+ else if(color&&colors.length){const paint=new chalk.Instance({level:1});output=[...line].map((char,index)=>paint[colors[(index+i)%colors.length]](char)).join('');}
19
+ return ' '.repeat(Math.min(500,pad))+output;
20
+ }).join('\n');
21
+ stream.write(rendered+'\n'); return rendered;
22
+ }
23
+ let shown=false;
24
+ function showKageBanner(options={}) {
25
+ if(shown||process.env.KAGE_BANNER==='0')return;
26
+ shown=true;
27
+ say('kage baileys', {font:'simple',align:'center',gradient:['red','magenta'],...options});
28
+ say('Creado por xrljosedv', {font:'console',align:'center',colors:['cyan','magenta','yellow'],...options});
29
+ say('Socio David Zuniga', {font:'console',align:'center',colors:['cyan','magenta','yellow'],...options});
30
+ }
31
+ exports.say=say;exports.showKageBanner=showKageBanner;
@@ -132,3 +132,274 @@ const useMultiFileAuthState = async (folder) => {
132
132
  };
133
133
  };
134
134
  exports.useMultiFileAuthState = useMultiFileAuthState;
135
+
136
+ // Kage: compatibilidad de API.
137
+ const __kageModule79 = (() => {
138
+ const module = { exports: {} }; const exports = module.exports;
139
+ "use strict"
140
+
141
+ Object.defineProperty(exports, "__esModule", { value: true })
142
+
143
+ const { Mutex } = require("async-mutex")
144
+ const { promises } = require("fs")
145
+ const { join } = require("path")
146
+ const { proto } = require("../../WAProto")
147
+ const { initAuthCreds } = require("./auth-utils")
148
+ const { BufferJSON } = require("./generics")
149
+ // We need to lock files due to the fact that we are using async functions to read and write files
150
+ // https://github.com/WhiskeySockets/Baileys/issues/794
151
+ // https://github.com/nodejs/node/issues/26338
152
+ // Use a Map to store mutexes for each file path
153
+ const fileLocks = new Map()
154
+
155
+ // Get or create a mutex for a specific file path
156
+ const getFileLock = (path) => {
157
+ let mutex = fileLocks.get(path)
158
+ if (!mutex) {
159
+ mutex = new Mutex()
160
+ fileLocks.set(path, mutex)
161
+ }
162
+
163
+ return mutex
164
+ }
165
+
166
+ /**
167
+ * stores the full authentication state in a single folder.
168
+ * Far more efficient than singlefileauthstate
169
+ *
170
+ * Again, I wouldn't endorse this for any production level use other than perhaps a bot.
171
+ * Would recommend writing an auth state for use with a proper SQL or No-SQL DB
172
+ * */
173
+ const useMultiFileAuthState = async (folder) => {
174
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
175
+ const writeData = async (data, file) => {
176
+ const filePath = join(folder, fixFileName(file))
177
+ const mutex = getFileLock(filePath)
178
+ return mutex.acquire().then(async (release) => {
179
+ try {
180
+ await promises.writeFile(filePath, JSON.stringify(data, BufferJSON.replacer))
181
+ } finally {
182
+ release()
183
+ }
184
+ })
185
+ }
186
+ const readData = async (file) => {
187
+ try {
188
+ const filePath = join(folder, fixFileName(file))
189
+ const mutex = getFileLock(filePath)
190
+ const data = await mutex.acquire().then(async (release) => {
191
+ try {
192
+ return await promises.readFile(filePath, { encoding: 'utf-8' })
193
+ } finally {
194
+ release()
195
+ }
196
+ })
197
+
198
+ return JSON.parse(data, BufferJSON.reviver)
199
+ } catch (error) {
200
+ return null
201
+ }
202
+ }
203
+ const removeData = async (file) => {
204
+ try {
205
+ const filePath = join(folder, fixFileName(file))
206
+ const mutex = getFileLock(filePath)
207
+ await mutex.acquire().then(async (release) => {
208
+ try {
209
+ await promises.unlink(filePath)
210
+ } finally {
211
+ release()
212
+ }
213
+ })
214
+ } catch {}
215
+ }
216
+ const folderInfo = await promises.stat(folder).catch(() => { })
217
+ if (folderInfo) {
218
+ if (!folderInfo.isDirectory()) {
219
+ throw new Error(`found something that is not a directory at ${folder}, either delete it or specify a different location`)
220
+ }
221
+ }
222
+ else {
223
+ await promises.mkdir(folder, { recursive: true })
224
+ }
225
+ const fixFileName = (file) => {
226
+ return file?.replace(/\//g, '__')?.replace(/:/g, '-')
227
+ }
228
+ const creds = await readData('creds.json') || initAuthCreds()
229
+ return {
230
+ state: {
231
+ creds,
232
+ keys: {
233
+ get: async (type, ids) => {
234
+ const data = {}
235
+ await Promise.all(ids.map(async (id) => {
236
+ let value = await readData(`${type}-${id}.json`)
237
+ if (type === 'app-state-sync-key' && value) {
238
+ value = proto.Message.AppStateSyncKeyData.fromObject(value)
239
+ }
240
+ data[id] = value
241
+ }))
242
+ return data
243
+ },
244
+ set: async (data) => {
245
+ const tasks = []
246
+ for (const category in data) {
247
+ for (const id in data[category]) {
248
+ const value = data[category][id]
249
+ const file = `${category}-${id}.json`
250
+ tasks.push(value ? writeData(value, file) : removeData(file))
251
+ }
252
+ }
253
+ await Promise.all(tasks)
254
+ }
255
+ }
256
+ },
257
+ saveCreds: async () => {
258
+ return writeData(creds, 'creds.json')
259
+ }
260
+ }
261
+ }
262
+
263
+ module.exports = {
264
+ useMultiFileAuthState
265
+ }
266
+ return module.exports;
267
+ })();
268
+ for (const key of Object.keys(__kageModule79)) {
269
+ if (key !== '__esModule' && !Object.prototype.hasOwnProperty.call(exports,key)) Object.defineProperty(exports,key,{enumerable:true,configurable:true,get:()=>__kageModule79[key]});
270
+ }
271
+
272
+ // Kage: funciones avanzadas.
273
+ const __kageModule188 = (() => {
274
+ const module = { exports: {} }; const exports = module.exports;
275
+ "use strict";
276
+ Object.defineProperty(exports, "__esModule", { value: true });
277
+ exports.useMultiFileAuthState = void 0;
278
+ const promises_1 = require("node:fs/promises");
279
+ const node_path_1 = require("node:path");
280
+ const index_js_1 = require("../../WAProto/index.js");
281
+ const index_js_2 = require("../Addon/index.js");
282
+ const auth_utils_js_1 = require("./auth-utils.js");
283
+ const generics_js_1 = require("./generics.js");
284
+ // We need to lock files due to the fact that we are using async functions to read and write files
285
+ // https://github.com/WhiskeySockets/Baileys/issues/794
286
+ // https://github.com/nodejs/node/issues/26338
287
+ // Use a Map to store mutexes for each file path
288
+ const fileLocks = new Map();
289
+ // Get or create a mutex for a specific file path
290
+ const getFileLock = (path) => {
291
+ let mutex = fileLocks.get(path);
292
+ if (!mutex) {
293
+ mutex = (0, index_js_2.createMutex)();
294
+ fileLocks.set(path, mutex);
295
+ }
296
+ return mutex;
297
+ };
298
+ /**
299
+ * stores the full authentication state in a single folder.
300
+ * Far more efficient than singlefileauthstate
301
+ *
302
+ * Again, I wouldn't endorse this for any production level use other than perhaps a bot.
303
+ * Would recommend writing an auth state for use with a proper SQL or No-SQL DB
304
+ * */
305
+ const useMultiFileAuthState = async (folder) => {
306
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
307
+ const writeData = async (data, file) => {
308
+ const filePath = (0, node_path_1.join)(folder, fixFileName(file));
309
+ const mutex = getFileLock(filePath);
310
+ return mutex.acquire().then(async (release) => {
311
+ try {
312
+ await (0, promises_1.writeFile)(filePath, JSON.stringify(data, generics_js_1.BufferJSON.replacer));
313
+ }
314
+ finally {
315
+ release();
316
+ }
317
+ });
318
+ };
319
+ const readData = async (file) => {
320
+ try {
321
+ const filePath = (0, node_path_1.join)(folder, fixFileName(file));
322
+ const mutex = getFileLock(filePath);
323
+ return await mutex.acquire().then(async (release) => {
324
+ try {
325
+ const data = await (0, promises_1.readFile)(filePath, { encoding: 'utf-8' });
326
+ return JSON.parse(data, generics_js_1.BufferJSON.reviver);
327
+ }
328
+ finally {
329
+ release();
330
+ }
331
+ });
332
+ }
333
+ catch (error) {
334
+ return null;
335
+ }
336
+ };
337
+ const removeData = async (file) => {
338
+ try {
339
+ const filePath = (0, node_path_1.join)(folder, fixFileName(file));
340
+ const mutex = getFileLock(filePath);
341
+ return mutex.acquire().then(async (release) => {
342
+ try {
343
+ await (0, promises_1.unlink)(filePath);
344
+ }
345
+ catch {
346
+ }
347
+ finally {
348
+ release();
349
+ }
350
+ });
351
+ }
352
+ catch { }
353
+ };
354
+ const folderInfo = await (0, promises_1.stat)(folder).catch(() => { });
355
+ if (folderInfo) {
356
+ if (!folderInfo.isDirectory()) {
357
+ throw new Error(`found something that is not a directory at ${folder}, either delete it or specify a different location`);
358
+ }
359
+ }
360
+ else {
361
+ await (0, promises_1.mkdir)(folder, { recursive: true });
362
+ }
363
+ const fixFileName = (file) => file?.replace(/\//g, '__')?.replace(/:/g, '-');
364
+ const creds = (await readData('creds.json')) || (0, auth_utils_js_1.initAuthCreds)();
365
+ return {
366
+ state: {
367
+ creds,
368
+ keys: {
369
+ get: async (type, ids) => {
370
+ const data = {};
371
+ await Promise.all(ids.map(async (id) => {
372
+ let value = await readData(`${type}-${id}.json`);
373
+ if (type === 'app-state-sync-key' && value) {
374
+ value = index_js_1.proto.Message.AppStateSyncKeyData.fromObject(value);
375
+ }
376
+ data[id] = value;
377
+ }));
378
+ return data;
379
+ },
380
+ set: async (data) => {
381
+ const tasks = [];
382
+ for (const category in data) {
383
+ for (const id in data[category]) {
384
+ const value = data[category][id];
385
+ const file = `${category}-${id}.json`;
386
+ tasks.push(value ? writeData(value, file) : removeData(file));
387
+ }
388
+ }
389
+ await Promise.all(tasks);
390
+ }
391
+ }
392
+ },
393
+ saveCreds: async () => {
394
+ return writeData(creds, 'creds.json');
395
+ }
396
+ };
397
+ };
398
+ exports.useMultiFileAuthState = useMultiFileAuthState;
399
+
400
+ return module.exports;
401
+ })();
402
+ for (const key of Object.keys(__kageModule188)) {
403
+ if (key !== '__esModule' && !Object.prototype.hasOwnProperty.call(exports,key)) Object.defineProperty(exports,key,{enumerable:true,configurable:true,get:()=>__kageModule188[key]});
404
+ }
405
+ Object.defineProperty(exports, Symbol.for('kage.advanced'), {value:__kageModule188, configurable:true});
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useSingleFileAuthState = void 0;
4
+ const promises_1 = require("node:fs/promises");
5
+ const index_js_1 = require("../Defaults/index.js");
6
+ const index_js_2 = require("../../WAProto/index.js");
7
+ const index_js_3 = require("../Addon/index.js");
8
+ const auth_utils_js_1 = require("./auth-utils.js");
9
+ const generics_js_1 = require("./generics.js");
10
+ // Kage: actualización de compatibilidad.
11
+ const FLUSH_TIMEOUT_MS = 3000;
12
+ // Kage: actualización de compatibilidad.
13
+ const useSingleFileAuthState = async (fileName) => {
14
+ const cache = (0, index_js_3.createCache)({
15
+ max: 20000,
16
+ ttl: index_js_1.DEFAULT_CACHE_TTLS.SIGNAL_STORE
17
+ });
18
+ // Kage: actualización de compatibilidad.
19
+ const mutex = (0, index_js_3.createMutex)();
20
+ let fileData = {};
21
+ let isLoaded = false;
22
+ let flushTimeout = null;
23
+ const loadKey = async () => {
24
+ return await mutex.runExclusive(async () => {
25
+ if (isLoaded)
26
+ return;
27
+ try {
28
+ const data = JSON.parse(await (0, promises_1.readFile)(fileName, 'utf-8'), generics_js_1.BufferJSON.reviver);
29
+ fileData = data || {};
30
+ for (const [keyName, value] of Object.entries(fileData)) {
31
+ cache.set(keyName, value);
32
+ }
33
+ }
34
+ catch {
35
+ fileData = {};
36
+ }
37
+ isLoaded = true;
38
+ });
39
+ };
40
+ const flushKey = () => {
41
+ if (flushTimeout)
42
+ return;
43
+ flushTimeout = setTimeout(async () => {
44
+ flushTimeout = null;
45
+ await mutex.runExclusive(async () => {
46
+ try {
47
+ const tempFile = fileName + '.temp';
48
+ await (0, promises_1.writeFile)(tempFile, JSON.stringify(fileData, generics_js_1.BufferJSON.replacer));
49
+ await (0, promises_1.rename)(tempFile, fileName);
50
+ }
51
+ catch { }
52
+ });
53
+ }, FLUSH_TIMEOUT_MS);
54
+ };
55
+ const writeKey = (keyName, value) => {
56
+ cache.set(keyName, value);
57
+ fileData[keyName] = value;
58
+ flushKey();
59
+ };
60
+ const removeKey = (keyName) => {
61
+ cache.delete(keyName);
62
+ delete fileData[keyName];
63
+ flushKey();
64
+ };
65
+ const fileInfo = await (0, promises_1.stat)(fileName).catch(() => null);
66
+ if (!fileInfo) {
67
+ await (0, promises_1.writeFile)(fileName, '{}');
68
+ }
69
+ else if (!fileInfo.isFile()) {
70
+ throw new Error(`found something that is not a file at ${fileName}, either delete it or specify a different location`);
71
+ }
72
+ await loadKey();
73
+ const creds = fileData['creds'] || (0, auth_utils_js_1.initAuthCreds)();
74
+ return {
75
+ state: {
76
+ creds,
77
+ keys: {
78
+ get: (type, ids) => {
79
+ const data = {};
80
+ for (const id of ids) {
81
+ const keyName = type + id;
82
+ let value = cache.get(keyName);
83
+ if (value === undefined && fileData[keyName] !== undefined) {
84
+ value = fileData[keyName];
85
+ cache.set(keyName, value);
86
+ }
87
+ if (type === 'app-state-sync-key' && value) {
88
+ value = index_js_2.proto.Message.AppStateSyncKeyData.fromObject(value);
89
+ }
90
+ data[id] = value;
91
+ }
92
+ return data;
93
+ },
94
+ set: (data) => {
95
+ for (const category in data) {
96
+ for (const id in data[category]) {
97
+ const keyName = category + id;
98
+ const value = data[category][id];
99
+ value ? writeKey(keyName, value) : removeKey(keyName);
100
+ }
101
+ }
102
+ }
103
+ }
104
+ },
105
+ saveCreds: () => writeKey('creds', creds)
106
+ };
107
+ };
108
+ exports.useSingleFileAuthState = useSingleFileAuthState;