@ikyyjee/ikyysinggle 1.7.7

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 (142) hide show
  1. package/WAProto/GenerateStatics.sh +3 -0
  2. package/WAProto/WAProto.proto +8083 -0
  3. package/WAProto/fix-imports.js +85 -0
  4. package/WAProto/index.d.ts +29095 -0
  5. package/WAProto/index.js +172336 -0
  6. package/engine-requirements.js +10 -0
  7. package/lib/Defaults/index.js +194 -0
  8. package/lib/Signal/Group/ciphertext-message.js +12 -0
  9. package/lib/Signal/Group/group-session-builder.js +30 -0
  10. package/lib/Signal/Group/group_cipher.js +82 -0
  11. package/lib/Signal/Group/index.js +12 -0
  12. package/lib/Signal/Group/keyhelper.js +18 -0
  13. package/lib/Signal/Group/sender-chain-key.js +26 -0
  14. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  15. package/lib/Signal/Group/sender-key-message.js +66 -0
  16. package/lib/Signal/Group/sender-key-name.js +48 -0
  17. package/lib/Signal/Group/sender-key-record.js +41 -0
  18. package/lib/Signal/Group/sender-key-state.js +84 -0
  19. package/lib/Signal/Group/sender-message-key.js +26 -0
  20. package/lib/Signal/libsignal.js +431 -0
  21. package/lib/Signal/lid-mapping.js +277 -0
  22. package/lib/Socket/Client/index.js +3 -0
  23. package/lib/Socket/Client/types.js +11 -0
  24. package/lib/Socket/Client/websocket.js +102 -0
  25. package/lib/Socket/aigroups.js +221 -0
  26. package/lib/Socket/business.js +379 -0
  27. package/lib/Socket/chats.js +1193 -0
  28. package/lib/Socket/communities.js +431 -0
  29. package/lib/Socket/graphql.js +524 -0
  30. package/lib/Socket/groups.js +408 -0
  31. package/lib/Socket/index.js +49 -0
  32. package/lib/Socket/interop.js +341 -0
  33. package/lib/Socket/luxu.js +510 -0
  34. package/lib/Socket/managed-account.js +99 -0
  35. package/lib/Socket/messages-recv.js +2009 -0
  36. package/lib/Socket/messages-send.js +1608 -0
  37. package/lib/Socket/mex.js +41 -0
  38. package/lib/Socket/newsletter.js +399 -0
  39. package/lib/Socket/privacy.js +128 -0
  40. package/lib/Socket/registration.js +238 -0
  41. package/lib/Socket/socket.js +1000 -0
  42. package/lib/Socket/text-router.js +67 -0
  43. package/lib/Socket/username.js +234 -0
  44. package/lib/Store/index.js +10 -0
  45. package/lib/Store/keyed-db.js +108 -0
  46. package/lib/Store/make-cache-manager-store.js +85 -0
  47. package/lib/Store/make-in-memory-store.js +198 -0
  48. package/lib/Store/make-ordered-dictionary.js +75 -0
  49. package/lib/Store/object-repository.js +32 -0
  50. package/lib/Types/Auth.js +2 -0
  51. package/lib/Types/Bussines.js +2 -0
  52. package/lib/Types/Call.js +2 -0
  53. package/lib/Types/Chat.js +8 -0
  54. package/lib/Types/Contact.js +2 -0
  55. package/lib/Types/Events.js +2 -0
  56. package/lib/Types/GroupMetadata.js +2 -0
  57. package/lib/Types/Label.js +25 -0
  58. package/lib/Types/LabelAssociation.js +7 -0
  59. package/lib/Types/Message.js +11 -0
  60. package/lib/Types/Mex.js +114 -0
  61. package/lib/Types/Product.js +2 -0
  62. package/lib/Types/Signal.js +2 -0
  63. package/lib/Types/Socket.js +3 -0
  64. package/lib/Types/State.js +56 -0
  65. package/lib/Types/USync.js +2 -0
  66. package/lib/Types/index.js +26 -0
  67. package/lib/Utils/adaptive-healing.js +53 -0
  68. package/lib/Utils/auth-utils.js +302 -0
  69. package/lib/Utils/browser-utils.js +50 -0
  70. package/lib/Utils/business.js +231 -0
  71. package/lib/Utils/chat-utils.js +872 -0
  72. package/lib/Utils/command-loader.js +108 -0
  73. package/lib/Utils/companion-reg-client-utils.js +35 -0
  74. package/lib/Utils/consumer-application.js +106 -0
  75. package/lib/Utils/crypto.js +137 -0
  76. package/lib/Utils/curve25519-js.js +262 -0
  77. package/lib/Utils/decode-wa-message.js +498 -0
  78. package/lib/Utils/event-buffer.js +622 -0
  79. package/lib/Utils/generics.js +403 -0
  80. package/lib/Utils/group-history.js +47 -0
  81. package/lib/Utils/history.js +134 -0
  82. package/lib/Utils/identity-change-handler.js +50 -0
  83. package/lib/Utils/index.js +38 -0
  84. package/lib/Utils/jid-display-normalization.js +198 -0
  85. package/lib/Utils/link-preview.js +85 -0
  86. package/lib/Utils/logger.js +3 -0
  87. package/lib/Utils/lt-hash.js +8 -0
  88. package/lib/Utils/make-mutex.js +33 -0
  89. package/lib/Utils/message-composer.js +273 -0
  90. package/lib/Utils/message-retry-manager.js +267 -0
  91. package/lib/Utils/messages-media.js +791 -0
  92. package/lib/Utils/messages.js +1260 -0
  93. package/lib/Utils/meta-ai-msmsg.js +271 -0
  94. package/lib/Utils/native-bridge.js +77 -0
  95. package/lib/Utils/noise-handler.js +201 -0
  96. package/lib/Utils/offline-node-processor.js +40 -0
  97. package/lib/Utils/optimizer.js +90 -0
  98. package/lib/Utils/pre-key-manager.js +106 -0
  99. package/lib/Utils/process-message.js +630 -0
  100. package/lib/Utils/reporting-utils.js +258 -0
  101. package/lib/Utils/session-pool.js +73 -0
  102. package/lib/Utils/signal.js +207 -0
  103. package/lib/Utils/stanza-ack.js +38 -0
  104. package/lib/Utils/sticker.js +139 -0
  105. package/lib/Utils/sync-action-utils.js +49 -0
  106. package/lib/Utils/tc-token-utils.js +163 -0
  107. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  108. package/lib/Utils/use-sqlite-auth-state.js +168 -0
  109. package/lib/Utils/validate-connection.js +203 -0
  110. package/lib/Utils/view-once-cache.js +79 -0
  111. package/lib/Utils/voip-rekey.js +25 -0
  112. package/lib/Utils/warmup.js +117 -0
  113. package/lib/WABinary/constants.js +1301 -0
  114. package/lib/WABinary/decode.js +262 -0
  115. package/lib/WABinary/encode.js +220 -0
  116. package/lib/WABinary/generic-utils.js +204 -0
  117. package/lib/WABinary/index.js +6 -0
  118. package/lib/WABinary/jid-utils.js +98 -0
  119. package/lib/WABinary/types.js +2 -0
  120. package/lib/WAM/BinaryInfo.js +10 -0
  121. package/lib/WAM/constants.js +22853 -0
  122. package/lib/WAM/encode.js +150 -0
  123. package/lib/WAM/index.js +4 -0
  124. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +41 -0
  125. package/lib/WAUSync/Protocols/USyncContactProtocol.js +52 -0
  126. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  127. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  128. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +52 -0
  129. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +31 -0
  130. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +26 -0
  131. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  132. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +35 -0
  133. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  134. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  135. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  136. package/lib/WAUSync/Protocols/index.js +13 -0
  137. package/lib/WAUSync/USyncQuery.js +127 -0
  138. package/lib/WAUSync/USyncUser.js +31 -0
  139. package/lib/WAUSync/index.js +4 -0
  140. package/lib/antiban.js +4083 -0
  141. package/lib/index.js +24 -0
  142. package/package.json +147 -0
@@ -0,0 +1,198 @@
1
+ /**
2
+ * lib/Utils/jid-display-normalization.js — turns LID (linked/privacy
3
+ * identifiers) back into the phone-number JID for anything you'd display
4
+ * or re-send, using hints from the message itself, group metadata, and the
5
+ * signal repository's own LID<->PN mapping (falling back to a best-effort
6
+ * guess only if none of those resolve it). Pure data transform, no network
7
+ * calls beyond the signalRepository lookup already used elsewhere in this
8
+ * library.
9
+ */
10
+ import { isHostedLidUser, isHostedPnUser, isLidUser, isPnUser, jidDecode } from '../WABinary/index.js';
11
+ const createLidPnDebug = logger => {
12
+ const enabled = process.env.LID_PN_DEBUG === '1' || process.env.LID_PN_DEBUG === 'true';
13
+ return (phase, payload) => {
14
+ if (!enabled) {
15
+ return;
16
+ }
17
+ logger?.debug({ ...payload, phase }, 'lid->pn normalization trace');
18
+ };
19
+ };
20
+ const fallbackPnFromLidJid = jid => {
21
+ const decoded = jidDecode(jid);
22
+ const rawUser = decoded?.user || (typeof jid === 'string' ? jid.split('@')[0] : '');
23
+ const user = rawUser.split(':')[0];
24
+ if (!user) {
25
+ return jid;
26
+ }
27
+ return `${user}@s.whatsapp.net`;
28
+ };
29
+ const toDisplayPnJid = jid => {
30
+ if (!jid || typeof jid !== 'string') {
31
+ return jid;
32
+ }
33
+ const decoded = jidDecode(jid);
34
+ if (!decoded?.user) {
35
+ return jid;
36
+ }
37
+ if (!isPnUser(jid) && !isHostedPnUser(jid)) {
38
+ return jid;
39
+ }
40
+ const user = decoded.user.split(':')[0];
41
+ if (!user) {
42
+ return jid;
43
+ }
44
+ const server = decoded.server === 'hosted' ? 'hosted' : 's.whatsapp.net';
45
+ return `${user}@${server}`;
46
+ };
47
+ const buildLidPnHints = key => {
48
+ const hints = new Map();
49
+ if (!key) {
50
+ return hints;
51
+ }
52
+ const addHint = (lid, pn) => {
53
+ if (!isLidUser(lid) && !isHostedLidUser(lid)) {
54
+ return;
55
+ }
56
+ if (!isPnUser(pn) && !isHostedPnUser(pn)) {
57
+ return;
58
+ }
59
+ hints.set(lid, pn);
60
+ const lidDecoded = jidDecode(lid);
61
+ const pnDecoded = jidDecode(pn);
62
+ if (lidDecoded?.user && pnDecoded?.user) {
63
+ hints.set(`${lidDecoded.user}@lid`, `${pnDecoded.user}@s.whatsapp.net`);
64
+ }
65
+ };
66
+ addHint(key.participant, key.participantAlt);
67
+ addHint(key.remoteJid, key.remoteJidAlt);
68
+ addHint(key.participantAlt, key.participant);
69
+ addHint(key.remoteJidAlt, key.remoteJid);
70
+ return hints;
71
+ };
72
+ const mergeGroupDataHints = (hints, groupData, debug) => {
73
+ if (!groupData?.participants?.length) {
74
+ return;
75
+ }
76
+ debug?.('groupData-size', { participants: groupData.participants.length });
77
+ for (const participant of groupData.participants) {
78
+ const lidCandidate = participant?.lid;
79
+ const idCandidate = participant?.id;
80
+ const pnCandidate = participant?.phoneNumber;
81
+ const lid = (isLidUser(lidCandidate) || isHostedLidUser(lidCandidate)
82
+ ? lidCandidate
83
+ : undefined) ||
84
+ (isLidUser(idCandidate) || isHostedLidUser(idCandidate) ? idCandidate : undefined);
85
+ const pn = (isPnUser(pnCandidate) || isHostedPnUser(pnCandidate)
86
+ ? pnCandidate
87
+ : undefined) ||
88
+ (isPnUser(idCandidate) || isHostedPnUser(idCandidate) ? idCandidate : undefined);
89
+ if (!lid || !pn) {
90
+ continue;
91
+ }
92
+ if ((isLidUser(lid) || isHostedLidUser(lid)) &&
93
+ (isPnUser(pn) || isHostedPnUser(pn))) {
94
+ const displayPn = toDisplayPnJid(pn);
95
+ hints.set(lid, displayPn);
96
+ const lidDecoded = jidDecode(lid);
97
+ if (lidDecoded?.user) {
98
+ hints.set(`${lidDecoded.user}@lid`, displayPn);
99
+ }
100
+ debug?.('group-hint', { lid, pn: displayPn });
101
+ }
102
+ }
103
+ };
104
+ const normalizeToPnJid = async (jid, hints, signalRepository, debug) => {
105
+ if (!jid || typeof jid !== 'string') {
106
+ return jid;
107
+ }
108
+ if (!isLidUser(jid) && !isHostedLidUser(jid)) {
109
+ return jid;
110
+ }
111
+ debug?.('input', { lid: jid });
112
+ const hinted = hints.get(jid);
113
+ if (hinted) {
114
+ const normalized = toDisplayPnJid(hinted);
115
+ debug?.('hint-exact', { lid: jid, hinted, normalized });
116
+ return normalized;
117
+ }
118
+ const decoded = jidDecode(jid);
119
+ if (decoded?.user) {
120
+ const userHint = hints.get(`${decoded.user}@lid`);
121
+ if (userHint) {
122
+ const normalized = toDisplayPnJid(userHint);
123
+ debug?.('hint-user', { lid: jid, userHint, normalized });
124
+ return normalized;
125
+ }
126
+ }
127
+ const mapped = await signalRepository?.lidMapping?.getPNForLID?.(jid);
128
+ if (mapped) {
129
+ const normalized = toDisplayPnJid(mapped);
130
+ debug?.('mapping', { lid: jid, mapped, normalized });
131
+ return normalized;
132
+ }
133
+ const fallback = fallbackPnFromLidJid(jid);
134
+ debug?.('fallback', { lid: jid, fallback });
135
+ return fallback;
136
+ };
137
+ const normalizeMentionedJidsToPn = async (node, hints, signalRepository, debug) => {
138
+ if (!node || typeof node !== 'object') {
139
+ return;
140
+ }
141
+ if (Array.isArray(node)) {
142
+ for (const item of node) {
143
+ await normalizeMentionedJidsToPn(item, hints, signalRepository, debug);
144
+ }
145
+ return;
146
+ }
147
+ if (Array.isArray(node.mentionedJid)) {
148
+ const before = [...node.mentionedJid];
149
+ node.mentionedJid = await Promise.all(node.mentionedJid.map(jid => normalizeToPnJid(jid, hints, signalRepository, debug)));
150
+ debug?.('mentions', { before, after: node.mentionedJid });
151
+ }
152
+ if (typeof node.participant === 'string') {
153
+ const before = node.participant;
154
+ node.participant = await normalizeToPnJid(node.participant, hints, signalRepository, debug);
155
+ if (before !== node.participant) {
156
+ debug?.('participant-field', { before, after: node.participant });
157
+ }
158
+ }
159
+ if (typeof node.remoteJid === 'string') {
160
+ const before = node.remoteJid;
161
+ node.remoteJid = await normalizeToPnJid(node.remoteJid, hints, signalRepository, debug);
162
+ if (before !== node.remoteJid) {
163
+ debug?.('remoteJid-field', { before, after: node.remoteJid });
164
+ }
165
+ }
166
+ for (const value of Object.values(node)) {
167
+ if (value && typeof value === 'object') {
168
+ await normalizeMentionedJidsToPn(value, hints, signalRepository, debug);
169
+ }
170
+ }
171
+ };
172
+ export const normalizeMentionedJidsForSend = async (mentions, groupData, signalRepository, logger) => {
173
+ if (!Array.isArray(mentions)) {
174
+ return mentions;
175
+ }
176
+ const debug = createLidPnDebug(logger);
177
+ const hints = new Map();
178
+ mergeGroupDataHints(hints, groupData, debug);
179
+ const normalized = await Promise.all(mentions.map(jid => normalizeToPnJid(jid, hints, signalRepository, debug)));
180
+ debug('send-mentions-result', { before: mentions, after: normalized });
181
+ return normalized;
182
+ };
183
+ export const normalizeMessageForDisplayJids = async (messageInfo, signalRepository, logger, groupData) => {
184
+ if (!messageInfo?.key) {
185
+ return messageInfo;
186
+ }
187
+ const debug = createLidPnDebug(logger);
188
+ const hints = buildLidPnHints(messageInfo.key);
189
+ mergeGroupDataHints(hints, groupData, debug);
190
+ const beforeKey = { ...messageInfo.key };
191
+ messageInfo.key.participant = await normalizeToPnJid(messageInfo.key.participant, hints, signalRepository, debug);
192
+ messageInfo.key.participantAlt = await normalizeToPnJid(messageInfo.key.participantAlt, hints, signalRepository, debug);
193
+ messageInfo.key.remoteJid = await normalizeToPnJid(messageInfo.key.remoteJid, hints, signalRepository, debug);
194
+ messageInfo.key.remoteJidAlt = await normalizeToPnJid(messageInfo.key.remoteJidAlt, hints, signalRepository, debug);
195
+ await normalizeMentionedJidsToPn(messageInfo.message, hints, signalRepository, debug);
196
+ debug('display-key-result', { before: beforeKey, after: messageInfo.key });
197
+ return messageInfo;
198
+ };
@@ -0,0 +1,85 @@
1
+ import { prepareWAMessageMedia } from './messages.js';
2
+ import { extractImageThumb, getHttpStream } from './messages-media.js';
3
+ const THUMBNAIL_WIDTH_PX = 192;
4
+ /** Fetches an image and generates a thumbnail for it */
5
+ const getCompressedJpegThumbnail = async (url, { thumbnailWidth, fetchOpts }) => {
6
+ const stream = await getHttpStream(url, fetchOpts);
7
+ const result = await extractImageThumb(stream, thumbnailWidth);
8
+ return result;
9
+ };
10
+ /**
11
+ * Given a piece of text, checks for any URL present, generates link preview for the same and returns it
12
+ * Return undefined if the fetch failed or no URL was found
13
+ * @param text first matched URL in text
14
+ * @returns the URL info required to generate link preview
15
+ */
16
+ export const getUrlInfo = async (text, opts = {
17
+ thumbnailWidth: THUMBNAIL_WIDTH_PX,
18
+ fetchOpts: { timeout: 3000 }
19
+ }) => {
20
+ try {
21
+ // retries
22
+ let retries = 0;
23
+ const maxRetry = 5;
24
+ const { getLinkPreview } = await import('link-preview-js');
25
+ let previewLink = text;
26
+ if (!text.startsWith('https://') && !text.startsWith('http://')) {
27
+ previewLink = 'https://' + previewLink;
28
+ }
29
+ const info = await getLinkPreview(previewLink, {
30
+ ...opts.fetchOpts,
31
+ followRedirects: 'follow',
32
+ handleRedirects: (baseURL, forwardedURL) => {
33
+ const urlObj = new URL(baseURL);
34
+ const forwardedURLObj = new URL(forwardedURL);
35
+ if (retries >= maxRetry) {
36
+ return false;
37
+ }
38
+ if (forwardedURLObj.hostname === urlObj.hostname ||
39
+ forwardedURLObj.hostname === 'www.' + urlObj.hostname ||
40
+ 'www.' + forwardedURLObj.hostname === urlObj.hostname) {
41
+ retries += 1;
42
+ return true;
43
+ }
44
+ else {
45
+ return false;
46
+ }
47
+ },
48
+ headers: opts.fetchOpts?.headers
49
+ });
50
+ if (info && 'title' in info && info.title) {
51
+ const [image] = info.images;
52
+ const urlInfo = {
53
+ 'canonical-url': info.url,
54
+ 'matched-text': text,
55
+ title: info.title,
56
+ description: info.description,
57
+ originalThumbnailUrl: image
58
+ };
59
+ if (opts.uploadImage) {
60
+ const { imageMessage } = await prepareWAMessageMedia({ image: { url: image } }, {
61
+ upload: opts.uploadImage,
62
+ mediaTypeOverride: 'thumbnail-link',
63
+ options: opts.fetchOpts
64
+ });
65
+ urlInfo.jpegThumbnail = imageMessage?.jpegThumbnail ? Buffer.from(imageMessage.jpegThumbnail) : undefined;
66
+ urlInfo.highQualityThumbnail = imageMessage || undefined;
67
+ }
68
+ else {
69
+ try {
70
+ urlInfo.jpegThumbnail = image ? (await getCompressedJpegThumbnail(image, opts)).buffer : undefined;
71
+ }
72
+ catch (error) {
73
+ opts.logger?.debug({ err: error.stack, url: previewLink }, 'error in generating thumbnail');
74
+ }
75
+ }
76
+ return urlInfo;
77
+ }
78
+ }
79
+ catch (error) {
80
+ if (!error.message.includes('receive a valid')) {
81
+ throw error;
82
+ }
83
+ }
84
+ };
85
+ //# sourceMappingURL=link-preview.js.map
@@ -0,0 +1,3 @@
1
+ import P from 'pino';
2
+ export default P({ timestamp: () => `,"time":"${new Date().toJSON()}"` });
3
+ //# sourceMappingURL=logger.js.map
@@ -0,0 +1,8 @@
1
+ import { LTHashAntiTampering } from 'whatsapp-rust-bridge';
2
+ /**
3
+ * LT Hash is a summation based hash algorithm that maintains the integrity of a piece of data
4
+ * over a series of mutations. You can add/remove mutations and it'll return a hash equal to
5
+ * if the same series of mutations was made sequentially.
6
+ */
7
+ export const LT_HASH_ANTI_TAMPERING = new LTHashAntiTampering();
8
+ //# sourceMappingURL=lt-hash.js.map
@@ -0,0 +1,33 @@
1
+ import { Mutex as AsyncMutex } from 'async-mutex';
2
+ export const makeMutex = () => {
3
+ const mutex = new AsyncMutex();
4
+ return {
5
+ mutex(code) {
6
+ return mutex.runExclusive(code);
7
+ }
8
+ };
9
+ };
10
+ export const makeKeyedMutex = () => {
11
+ const map = new Map();
12
+ return {
13
+ async mutex(key, task) {
14
+ let entry = map.get(key);
15
+ if (!entry) {
16
+ entry = { mutex: new AsyncMutex(), refCount: 0 };
17
+ map.set(key, entry);
18
+ }
19
+ entry.refCount++;
20
+ try {
21
+ return await entry.mutex.runExclusive(task);
22
+ }
23
+ finally {
24
+ entry.refCount--;
25
+ // only delete it if this is still the current entry
26
+ if (entry.refCount === 0 && map.get(key) === entry) {
27
+ map.delete(key);
28
+ }
29
+ }
30
+ }
31
+ };
32
+ };
33
+ //# sourceMappingURL=make-mutex.js.map
@@ -0,0 +1,273 @@
1
+ import { proto } from '../../WAProto/index.js'
2
+ import { generateMessageIDV2 } from './generics.js'
3
+
4
+ const JS_KEYWORDS = new Set([
5
+ 'import', 'export', 'from', 'default', 'as', 'const', 'let', 'var',
6
+ 'function', 'class', 'extends', 'new', 'return', 'if', 'else', 'for',
7
+ 'while', 'do', 'switch', 'case', 'break', 'continue', 'try', 'catch',
8
+ 'finally', 'throw', 'async', 'await', 'yield', 'typeof', 'instanceof',
9
+ 'in', 'of', 'delete', 'void', 'true', 'false', 'null', 'undefined',
10
+ 'NaN', 'Infinity', 'this', 'super', 'static', 'get', 'set', 'debugger', 'with'
11
+ ])
12
+
13
+ const PYTHON_KEYWORDS = new Set([
14
+ 'import', 'from', 'as', 'def', 'class', 'return', 'if', 'elif', 'else',
15
+ 'for', 'while', 'break', 'continue', 'try', 'except', 'finally', 'raise',
16
+ 'with', 'yield', 'lambda', 'pass', 'del', 'global', 'nonlocal', 'assert',
17
+ 'True', 'False', 'None', 'and', 'or', 'not', 'in', 'is', 'async', 'await',
18
+ 'self', 'print'
19
+ ])
20
+
21
+ const LANGUAGE_KEYWORDS = {
22
+ javascript: JS_KEYWORDS,
23
+ typescript: JS_KEYWORDS,
24
+ js: JS_KEYWORDS,
25
+ ts: JS_KEYWORDS,
26
+ python: PYTHON_KEYWORDS,
27
+ py: PYTHON_KEYWORDS
28
+ }
29
+
30
+ export var CodeHighlightType
31
+ ;(function (CodeHighlightType) {
32
+ CodeHighlightType[(CodeHighlightType['DEFAULT'] = 0)] = 'DEFAULT'
33
+ CodeHighlightType[(CodeHighlightType['KEYWORD'] = 1)] = 'KEYWORD'
34
+ CodeHighlightType[(CodeHighlightType['METHOD'] = 2)] = 'METHOD'
35
+ CodeHighlightType[(CodeHighlightType['STRING'] = 3)] = 'STRING'
36
+ CodeHighlightType[(CodeHighlightType['NUMBER'] = 4)] = 'NUMBER'
37
+ CodeHighlightType[(CodeHighlightType['COMMENT'] = 5)] = 'COMMENT'
38
+ })(CodeHighlightType || (CodeHighlightType = {}))
39
+
40
+ export var RichSubMessageType
41
+ ;(function (RichSubMessageType) {
42
+ RichSubMessageType[(RichSubMessageType['UNKNOWN'] = 0)] = 'UNKNOWN'
43
+ RichSubMessageType[(RichSubMessageType['GRID_IMAGE'] = 1)] = 'GRID_IMAGE'
44
+ RichSubMessageType[(RichSubMessageType['TEXT'] = 2)] = 'TEXT'
45
+ RichSubMessageType[(RichSubMessageType['INLINE_IMAGE'] = 3)] = 'INLINE_IMAGE'
46
+ RichSubMessageType[(RichSubMessageType['TABLE'] = 4)] = 'TABLE'
47
+ RichSubMessageType[(RichSubMessageType['CODE'] = 5)] = 'CODE'
48
+ RichSubMessageType[(RichSubMessageType['DYNAMIC'] = 6)] = 'DYNAMIC'
49
+ RichSubMessageType[(RichSubMessageType['MAP'] = 7)] = 'MAP'
50
+ RichSubMessageType[(RichSubMessageType['LATEX'] = 8)] = 'LATEX'
51
+ RichSubMessageType[(RichSubMessageType['CONTENT_ITEMS'] = 9)] = 'CONTENT_ITEMS'
52
+ })(RichSubMessageType || (RichSubMessageType = {}))
53
+
54
+ export const tokenizeCode = (codeStr, language = 'javascript') => {
55
+ const keywords = LANGUAGE_KEYWORDS[language] || JS_KEYWORDS
56
+ const blocks = []
57
+ const lines = codeStr.split('\n')
58
+ for (let li = 0; li < lines.length; li++) {
59
+ const line = lines[li]
60
+ const isLast = li === lines.length - 1
61
+ const nl = isLast? '' : '\n'
62
+ if (!line.trim()) {
63
+ blocks.push({ highlightType: CodeHighlightType.DEFAULT, codeContent: line + nl })
64
+ continue
65
+ }
66
+ if (line.trim().startsWith('//') || line.trim().startsWith('#')) {
67
+ blocks.push({ highlightType: CodeHighlightType.COMMENT, codeContent: line + nl })
68
+ continue
69
+ }
70
+ const regex = /(\/\/.*$|#.*$)|(["'`](?:[^"'`\\]|\\.)*["'`])|(\b\d+(?:\.\d+)?\b)|(\b[a-zA-Z_$][\w$]*\b)|([^\s\w$"'`]+)|(\s+)/g
71
+ let match
72
+ const tokens = []
73
+ while ((match = regex.exec(line))!== null) {
74
+ const val = match[0]
75
+ if (match[1]) {
76
+ tokens.push({ highlightType: CodeHighlightType.COMMENT, codeContent: val })
77
+ } else if (match[2]) {
78
+ tokens.push({ highlightType: CodeHighlightType.STRING, codeContent: val })
79
+ } else if (match[3]) {
80
+ tokens.push({ highlightType: CodeHighlightType.NUMBER, codeContent: val })
81
+ } else if (match[4]) {
82
+ if (keywords.has(val)) {
83
+ tokens.push({ highlightType: CodeHighlightType.KEYWORD, codeContent: val })
84
+ } else {
85
+ const after = line.slice(regex.lastIndex).trimStart()
86
+ if (after.startsWith('(')) {
87
+ tokens.push({ highlightType: CodeHighlightType.METHOD, codeContent: val })
88
+ } else {
89
+ tokens.push({ highlightType: CodeHighlightType.DEFAULT, codeContent: val })
90
+ }
91
+ }
92
+ } else {
93
+ tokens.push({ highlightType: CodeHighlightType.DEFAULT, codeContent: val })
94
+ }
95
+ }
96
+ if (tokens.length === 0) {
97
+ blocks.push({ highlightType: CodeHighlightType.DEFAULT, codeContent: line + nl })
98
+ continue
99
+ }
100
+ const merged = []
101
+ for (const t of tokens) {
102
+ const prev = merged.length > 0? merged[merged.length - 1] : undefined
103
+ if (prev && prev.highlightType === t.highlightType) {
104
+ prev.codeContent += t.codeContent
105
+ } else {
106
+ merged.push({...t })
107
+ }
108
+ }
109
+ if (merged.length > 0) {
110
+ merged[merged.length - 1].codeContent += nl
111
+ }
112
+ blocks.push(...merged)
113
+ }
114
+ return blocks
115
+ }
116
+
117
+ export const buildRichContextInfo = (quoted, options) => {
118
+ const ctxInfo = {
119
+ forwardingScore: 1,
120
+ isForwarded: true,
121
+ forwardedAiBotMessageInfo: { botJid: options?.botJid? options.botJid : '867051314767696@bot' },
122
+ forwardOrigin: 4,
123
+ ...(options?.mentions? { mentionedJid: options.mentions } : {})
124
+ }
125
+ if (quoted?.key) {
126
+ ctxInfo.stanzaId = quoted.key.id
127
+ ctxInfo.participant = quoted.key.participant || quoted.sender || quoted.key.remoteJid
128
+ ctxInfo.quotedMessage = quoted.message
129
+ }
130
+ return ctxInfo
131
+ }
132
+
133
+ export const buildBotForwardedMessage = (submessages, contextInfo, unifiedResponse) => {
134
+ const richResponse = { messageType: 1, submessages, contextInfo }
135
+ if (unifiedResponse) {
136
+ richResponse.unifiedResponse = unifiedResponse
137
+ }
138
+ return {
139
+ botForwardedMessage: {
140
+ message: { richResponseMessage: richResponse }
141
+ }
142
+ }
143
+ }
144
+
145
+ export const generateTableContent = (title, headers, rows, quoted, options = {}) => {
146
+ const { footer, headerText } = options
147
+ const tableRows = [{ items: headers, isHeading: true },...rows.map(row => ({ items: row.map(String) }))]
148
+ const submessages = []
149
+ if (headerText) submessages.push({ messageType: 2, messageText: headerText })
150
+ submessages.push({ messageType: 4, tableMetadata: { title, rows: tableRows } })
151
+ if (footer) submessages.push({ messageType: 2, messageText: footer })
152
+ const ctxInfo = buildRichContextInfo(quoted)
153
+ return { message: buildBotForwardedMessage(submessages, ctxInfo), messageId: generateMessageIDV2() }
154
+ }
155
+
156
+ export const generateListContent = (title, items, quoted, options = {}) => {
157
+ const { footer, headerText } = options
158
+ const tableRows = items.map(item => ({
159
+ items: Array.isArray(item)? item.map(String) : [String(item)]
160
+ }))
161
+ const submessages = []
162
+ if (headerText) submessages.push({ messageType: 2, messageText: headerText })
163
+ submessages.push({ messageType: 4, tableMetadata: { title, rows: tableRows } })
164
+ if (footer) submessages.push({ messageType: 2, messageText: footer })
165
+ const ctxInfo = buildRichContextInfo(quoted)
166
+ return { message: buildBotForwardedMessage(submessages, ctxInfo), messageId: generateMessageIDV2() }
167
+ }
168
+
169
+ export const generateCodeBlockContent = (code, quoted, options = {}) => {
170
+ const { title, footer, language = 'javascript' } = options
171
+ const submessages = []
172
+ if (title) submessages.push({ messageType: 2, messageText: title })
173
+ submessages.push({
174
+ messageType: 5,
175
+ codeMetadata: { codeLanguage: language, codeBlocks: tokenizeCode(code, language) }
176
+ })
177
+ if (footer) submessages.push({ messageType: 2, messageText: footer })
178
+ const ctxInfo = buildRichContextInfo(quoted)
179
+ return { message: buildBotForwardedMessage(submessages, ctxInfo), messageId: generateMessageIDV2() }
180
+ }
181
+
182
+ export const generateLatexContent = (quoted, options) => {
183
+ const { text, expressions, headerText, footer } = options
184
+ const submessages = []
185
+ if (headerText) submessages.push({ messageType: 2, messageText: headerText })
186
+ const latexExpressions = expressions.map(expr => {
187
+ const entry = {
188
+ latexExpression: expr.latexExpression,
189
+ url: expr.url,
190
+ width: expr.width,
191
+ height: expr.height
192
+ }
193
+ if (expr.fontHeight!== undefined) entry.fontHeight = expr.fontHeight
194
+ if (expr.imageTopPadding!== undefined) entry.imageTopPadding = expr.imageTopPadding
195
+ if (expr.imageLeadingPadding!== undefined) entry.imageLeadingPadding = expr.imageLeadingPadding
196
+ if (expr.imageBottomPadding!== undefined) entry.imageBottomPadding = expr.imageBottomPadding
197
+ if (expr.imageTrailingPadding!== undefined) entry.imageTrailingPadding = expr.imageTrailingPadding
198
+ return entry
199
+ })
200
+ submessages.push({ messageType: 8, latexMetadata: { text: text || '', expressions: latexExpressions } })
201
+ if (footer) submessages.push({ messageType: 2, messageText: footer })
202
+ const ctxInfo = buildRichContextInfo(quoted)
203
+ return { message: buildBotForwardedMessage(submessages, ctxInfo), messageId: generateMessageIDV2() }
204
+ }
205
+
206
+ export const generateLatexImageContent = async (quoted, options, uploadFn, renderLatexToPng) => {
207
+ const { text, expressions, headerText, footer } = options
208
+ const submessages = []
209
+ if (headerText) submessages.push({ messageType: 2, messageText: headerText })
210
+ const latexExpressions = await Promise.all(
211
+ expressions.map(async expr => {
212
+ const { buffer, width, height } = await renderLatexToPng(expr.latexExpression)
213
+ const uploadResult = await uploadFn(buffer, 'image')
214
+ const imageUrl = uploadResult.url || uploadResult.directPath
215
+ return { latexExpression: expr.latexExpression, url: imageUrl, width, height }
216
+ })
217
+ )
218
+ submessages.push({ messageType: 8, latexMetadata: { text: text || '', expressions: latexExpressions } })
219
+ if (footer) submessages.push({ messageType: 2, messageText: footer })
220
+ const ctxInfo = buildRichContextInfo(quoted)
221
+ return { message: buildBotForwardedMessage(submessages, ctxInfo), messageId: generateMessageIDV2() }
222
+ }
223
+
224
+ export const generateLatexInlineImageContent = async (quoted, options, uploadFn, renderLatexToPng) => {
225
+ const { text, expressions, headerText, footer } = options
226
+ const submessages = []
227
+ if (headerText) submessages.push({ messageType: 2, messageText: headerText })
228
+ if (text) submessages.push({ messageType: 2, messageText: text })
229
+ for (const expr of expressions) {
230
+ const { buffer, width, height } = await renderLatexToPng(expr.latexExpression)
231
+ const uploadResult = await uploadFn(buffer, 'image')
232
+ const imageUrl = uploadResult.url || uploadResult.directPath
233
+ submessages.push({
234
+ messageType: 3,
235
+ imageMetadata: {
236
+ imageUrl: { imagePreviewUrl: imageUrl, imageHighResUrl: imageUrl },
237
+ imageText: expr.latexExpression,
238
+ alignment: 2
239
+ }
240
+ })
241
+ }
242
+ if (footer) submessages.push({ messageType: 2, messageText: footer })
243
+ const ctxInfo = buildRichContextInfo(quoted)
244
+ return { message: buildBotForwardedMessage(submessages, ctxInfo), messageId: generateMessageIDV2() }
245
+ }
246
+
247
+ export const captureUnifiedResponse = msg => {
248
+ const botFwd = msg?.botForwardedMessage?.message
249
+ if (!botFwd) return null
250
+ const rich = botFwd.richResponseMessage
251
+ if (!rich?.unifiedResponse?.data) return null
252
+ return {
253
+ unifiedResponse: { data: rich.unifiedResponse.data },
254
+ submessages: rich.submessages || [],
255
+ contextInfo: rich.contextInfo || {}
256
+ }
257
+ }
258
+
259
+ export const generateUnifiedResponseContent = (quoted, captured) => {
260
+ const ctxInfo = buildRichContextInfo(quoted)
261
+ return { message: buildBotForwardedMessage(captured.submessages, ctxInfo, captured.unifiedResponse), messageId: generateMessageIDV2() }
262
+ }
263
+
264
+ export const generateRichMessageContent = (submessages, quoted, options) => {
265
+ const ctxInfo = buildRichContextInfo(quoted, options)
266
+ return { message: buildBotForwardedMessage(submessages, ctxInfo), messageId: generateMessageIDV2() }
267
+ }
268
+
269
+ export {
270
+ JS_KEYWORDS,
271
+ PYTHON_KEYWORDS,
272
+ LANGUAGE_KEYWORDS
273
+ }