@ruthless-imperium/baileys 1.0.2 → 1.0.3

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.
@@ -0,0 +1,89 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const __def = (m) => (m && m.__esModule) ? m.default : m;
4
+ const __exportStar = (m, e) => { for (const k in m) if (k !== "default" && !Object.prototype.hasOwnProperty.call(e, k)) e[k] = m[k]; };
5
+
6
+ const cacheManager = require("cache-manager");
7
+
8
+ const WAProto_1 = require("../../WAProto/index.js");
9
+ const Utils_1 = require("../Utils/index.js");
10
+ const logger = __def(require("../Utils/logger.js"));
11
+
12
+ async function makeCacheManagerAuthState(store, sessionKey) {
13
+ const defaultKey = (file) => `${sessionKey}:${file}`;
14
+ const databaseConn = await cacheManager.caching(store);
15
+
16
+ const writeData = async (file, data) => {
17
+ let ttl = undefined;
18
+ if (file === "creds") ttl = 63115200; // 2 years
19
+ await databaseConn.set(
20
+ defaultKey(file),
21
+ JSON.stringify(data, Utils_1.BufferJSON.replacer),
22
+ ttl
23
+ );
24
+ };
25
+
26
+ const readData = async (file) => {
27
+ try {
28
+ const data = await databaseConn.get(defaultKey(file));
29
+ if (data) return JSON.parse(data, Utils_1.BufferJSON.reviver);
30
+ return null;
31
+ } catch (error) {
32
+ logger.error(error);
33
+ return null;
34
+ }
35
+ };
36
+
37
+ const removeData = async (file) => {
38
+ try {
39
+ return await databaseConn.del(defaultKey(file));
40
+ } catch {
41
+ logger.error(`Error removing ${file} from session ${sessionKey}`);
42
+ }
43
+ };
44
+
45
+ const clearState = async () => {
46
+ try {
47
+ const result = await databaseConn.store.keys(`${sessionKey}*`);
48
+ await Promise.all(result.map(async (key) => databaseConn.del(key)));
49
+ } catch {}
50
+ };
51
+
52
+ const creds = (await readData("creds")) || Utils_1.initAuthCreds();
53
+
54
+ return {
55
+ clearState,
56
+ saveCreds: () => writeData("creds", creds),
57
+ state: {
58
+ creds,
59
+ keys: {
60
+ get: async (type, ids) => {
61
+ const data = {};
62
+ await Promise.all(
63
+ ids.map(async (id) => {
64
+ let value = await readData(`${type}-${id}`);
65
+ if (type === "app-state-sync-key" && value) {
66
+ value =
67
+ WAProto_1.proto.Message.AppStateSyncKeyData.fromObject(value);
68
+ }
69
+ data[id] = value;
70
+ })
71
+ );
72
+ return data;
73
+ },
74
+ set: async (data) => {
75
+ const tasks = [];
76
+ for (const category in data) {
77
+ for (const id in data[category]) {
78
+ const value = data[category][id];
79
+ const key = `${category}-${id}`;
80
+ tasks.push(value ? writeData(key, value) : removeData(key));
81
+ }
82
+ }
83
+ await Promise.all(tasks);
84
+ }
85
+ }
86
+ }
87
+ };
88
+ }
89
+ exports.default = makeCacheManagerAuthState;
@@ -0,0 +1,117 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const __def = (m) => (m && m.__esModule) ? m.default : m;
4
+ const __exportStar = (m, e) => { for (const k in m) if (k !== "default" && !Object.prototype.hasOwnProperty.call(e, k)) e[k] = m[k]; };
5
+ var XWAPaths;
6
+ (function (XWAPaths) {
7
+ XWAPaths["xwa2_newsletter_create"] = "xwa2_newsletter_create";
8
+ XWAPaths["xwa2_newsletter_subscribers"] = "xwa2_newsletter_subscribers";
9
+ XWAPaths["xwa2_newsletter_view"] = "xwa2_newsletter_view";
10
+ XWAPaths["xwa2_newsletter_metadata"] = "xwa2_newsletter";
11
+ XWAPaths["xwa2_newsletter_admin_count"] = "xwa2_newsletter_admin";
12
+ XWAPaths["xwa2_newsletter_mute_v2"] = "xwa2_newsletter_mute_v2";
13
+ XWAPaths["xwa2_newsletter_unmute_v2"] = "xwa2_newsletter_unmute_v2";
14
+ XWAPaths["xwa2_newsletter_follow"] = "xwa2_newsletter_follow";
15
+ XWAPaths["xwa2_newsletter_unfollow"] = "xwa2_newsletter_unfollow";
16
+ XWAPaths["xwa2_newsletter_join_v2"] = "xwa2_newsletter_join_v2";
17
+ XWAPaths["xwa2_newsletter_leave_v2"] = "xwa2_newsletter_leave_v2";
18
+ XWAPaths["xwa2_newsletter_change_owner"] = "xwa2_newsletter_change_owner";
19
+ XWAPaths["xwa2_newsletter_demote"] = "xwa2_newsletter_demote";
20
+ XWAPaths["xwa2_newsletter_delete_v2"] = "xwa2_newsletter_delete_v2";
21
+ XWAPaths["xwa2_fetch_account_reachout_timelock"] = "xwa2_fetch_account_reachout_timelock";
22
+ XWAPaths["xwa2_message_capping_info"] = "xwa2_message_capping_info";
23
+ XWAPaths["xwa2_newsletter_subscribed"] = "xwa2_newsletter_subscribed";
24
+ XWAPaths["xwa2_newsletter_update"] = "xwa2_newsletter_update";
25
+ XWAPaths["xwa2_newsletter_admin"] = "xwa2_newsletter_admin";
26
+ XWAPaths["xwa2_newsletter_admin_invite_create"] = "xwa2_newsletter_admin_invite_create";
27
+ XWAPaths["xwa2_newsletter_admin_invite_revoke"] = "xwa2_newsletter_admin_invite_revoke";
28
+ XWAPaths["xwa2_newsletter_admin_invite_accept"] = "xwa2_newsletter_admin_invite_accept";
29
+ XWAPaths["xwa2_newsletter_admin_profile_update"] = "xwa2_newsletter_admin_profile_update";
30
+ XWAPaths["xwa2_newsletter_admin_insights"] = "xwa2_newsletter_admin_insights";
31
+ XWAPaths["xwa2_newsletter_following"] = "xwa2_newsletter_following";
32
+ XWAPaths["xwa2_newsletter_create_verified"] = "xwa2_newsletter_create_verified";
33
+ XWAPaths["xwa2_newsletter_enforcements"] = "xwa2_newsletter_enforcements";
34
+ XWAPaths["xwa2_newsletter_user_reports"] = "xwa2_newsletter_user_reports";
35
+ XWAPaths["xwa2_newsletter_create_report_appeal"] = "xwa2_newsletter_create_report_appeal";
36
+ XWAPaths["xwa2_newsletter_link_preview_check"] = "xwa2_newsletter_link_preview_check";
37
+ XWAPaths["xwa2_newsletter_update_verification"] = "xwa2_newsletter_update_verification";
38
+ XWAPaths["xwa2_newsletter_label_paid_partnership"] = "xwa2_newsletter_label_paid_partnership";
39
+ XWAPaths["xwa2_newsletter_log_exposures"] = "xwa2_newsletter_log_exposures";
40
+ XWAPaths["xwa2_newsletter_update_user_setting"] = "xwa2_newsletter_update_user_setting";
41
+ XWAPaths["xwa2_newsletter_ranking_features"] = "xwa2_newsletter_ranking_features";
42
+ XWAPaths["xwa2_newsletter_block_user"] = "xwa2_newsletter_block_user";
43
+ XWAPaths["xwa2_newsletters_directory_list"] = "xwa2_newsletters_directory_list";
44
+ XWAPaths["xwa2_newsletters_directory_search"] = "xwa2_newsletters_directory_search";
45
+ XWAPaths["xwa2_newsletters_directory_category_preview"] = "xwa2_newsletters_directory_category_preview";
46
+ XWAPaths["xwa2_newsletters_search"] = "xwa2_newsletters_search";
47
+ XWAPaths["xwa2_newsletters_recommended"] = "xwa2_newsletters_recommended";
48
+ XWAPaths["xwa2_newsletters_similar"] = "xwa2_newsletters_similar";
49
+ XWAPaths["xwa2_newsletters_poll_voter_list"] = "xwa2_newsletters_poll_voter_list";
50
+ XWAPaths["xwa2_newsletters_reaction_sender_list"] = "xwa2_newsletters_reaction_sender_list";
51
+ XWAPaths["xwa2_wamo_afs_age_collection"] = "xwa2_wamo_afs_age_collection";
52
+ XWAPaths["xwa2_wamo_asset_collection"] = "xwa2_wamo_asset_collection";
53
+ XWAPaths["xwa2_wamo_fetch_adhoc_notice_by_id"] = "xwa2_wamo_fetch_adhoc_notice_by_id";
54
+ XWAPaths["xwa2_wamo_fetch_identity_token"] = "xwa2_wamo_fetch_identity_token";
55
+ XWAPaths["xwa2_wamo_sub_get_compliance_info"] = "xwa2_wamo_sub_get_compliance_info";
56
+ XWAPaths["xwa2_wamo_user_id_version"] = "xwa2_wamo_user_id_version";
57
+ XWAPaths["xwa2_wamo_set_user_id_version"] = "xwa2_wamo_set_user_id_version";
58
+ })(XWAPaths || (XWAPaths = {}));
59
+
60
+ var QueryIds;
61
+ (function (QueryIds) {
62
+ QueryIds["CREATE"] = "8823471724422422";
63
+ QueryIds["METADATA"] = "26099060629688646";
64
+ QueryIds["UPDATE_METADATA"] = "25976052865358570";
65
+ QueryIds["SUBSCRIBERS"] = "9783111038412085";
66
+ QueryIds["FOLLOW"] = "24404358912487870";
67
+ QueryIds["UNFOLLOW"] = "9767147403369991";
68
+ QueryIds["MUTE"] = "29766401636284406";
69
+ QueryIds["UNMUTE"] = "9864994326891137";
70
+ QueryIds["ADMIN_COUNT"] = "7130823597031706";
71
+ QueryIds["CHANGE_OWNER"] = "7341777602580933";
72
+ QueryIds["DEMOTE"] = "6551828931592903";
73
+ QueryIds["DELETE"] = "30062808666639665";
74
+ QueryIds["REACHOUT_TIMELOCK"] = "23983697327930364";
75
+ QueryIds["MESSAGE_CAPPING_INFO"] = "24503548349331633";
76
+ QueryIds["FETCH_SUBSCRIBE"] = "6388546374527196";
77
+ QueryIds["LEAVE"] = "9784043202933196";
78
+ QueryIds["ADMIN_INVITE"] = "7148599488585196";
79
+ QueryIds["ADMIN_INVITE_REVOKE"] = "6345824195482235";
80
+ QueryIds["ADMIN_INVITE_ACCEPT"] = "6345824195482236";
81
+ QueryIds["ADMIN_METADATA"] = "6895563180530100";
82
+ QueryIds["ADMIN_PROFILE_UPDATE"] = "6895563180530101";
83
+ QueryIds["INSIGHTS"] = "6243647912368353";
84
+ QueryIds["FOLLOWING_LIST"] = "6388546374527197";
85
+ QueryIds["CREATE_VERIFIED"] = "8823471724422423";
86
+ QueryIds["ENFORCEMENTS"] = "7130823597031707";
87
+ QueryIds["USER_REPORTS"] = "9783111038412086";
88
+ QueryIds["CREATE_REPORT_APPEAL"] = "6551828931592904";
89
+ QueryIds["LINK_PREVIEW_CHECK"] = "24404358912487871";
90
+ QueryIds["UPDATE_VERIFICATION"] = "25976052865358571";
91
+ QueryIds["LABEL_PAID_PARTNERSHIP"] = "7341777602580934";
92
+ QueryIds["LOG_EXPOSURES"] = "9864994326891138";
93
+ QueryIds["UPDATE_USER_SETTING"] = "29766401636284407";
94
+ QueryIds["RANKING_FEATURES"] = "7130823597031708";
95
+ QueryIds["BLOCK_USER"] = "6345824195482237";
96
+ QueryIds["DIRECTORY_LIST"] = "6388546374527198";
97
+ QueryIds["DIRECTORY_SEARCH"] = "6388546374527199";
98
+ QueryIds["DIRECTORY_CATEGORY_PREVIEW"] = "6388546374527200";
99
+ QueryIds["SEARCH"] = "26099060629688647";
100
+ QueryIds["RECOMMENDED"] = "26099060629688648";
101
+ QueryIds["SIMILAR"] = "26099060629688649";
102
+ QueryIds["POLL_VOTER_LIST"] = "9783111038412087";
103
+ QueryIds["REACTION_SENDERS_LIST"] = "9783111038412088";
104
+ QueryIds["WAMO_ENABLE_SUB"] = "7148599488585197";
105
+ QueryIds["WAMO_DISABLE_SUB"] = "7148599488585198";
106
+ QueryIds["WAMO_CHANGE_SUB"] = "7148599488585199";
107
+ QueryIds["WAMO_AFS_AGE_COLLECTION"] = "6895563180530102";
108
+ QueryIds["WAMO_ASSET_COLLECTION"] = "6895563180530103";
109
+ QueryIds["WAMO_FETCH_ADHOC_NOTICE"] = "6895563180530104";
110
+ QueryIds["WAMO_FETCH_IDENTITY_TOKEN"] = "6895563180530105";
111
+ QueryIds["WAMO_SUB_COMPLIANCE_INFO"] = "6895563180530106";
112
+ QueryIds["WAMO_USER_ID_VERSION"] = "6895563180530107";
113
+ QueryIds["WAMO_SET_USER_ID_VERSION"] = "6895563180530108";
114
+ })(QueryIds || (QueryIds = {}));
115
+
116
+ exports.XWAPaths = XWAPaths;
117
+ exports.QueryIds = QueryIds;
@@ -18,6 +18,7 @@ exports.DisconnectReason = void 0;
18
18
  __exportStar(require("./Auth"), exports);
19
19
  __exportStar(require("./GroupMetadata"), exports);
20
20
  __exportStar(require("./Newsletter"), exports);
21
+ __exportStar(require("./Mex"), exports);
21
22
  __exportStar(require("./Chat"), exports);
22
23
  __exportStar(require("./Contact"), exports);
23
24
  __exportStar(require("./State"), exports);
@@ -32,4 +32,7 @@ __exportStar(require("./link-preview"), exports);
32
32
  __exportStar(require("./event-buffer"), exports);
33
33
  __exportStar(require("./process-message"), exports);
34
34
  __exportStar(require("./message-retry-manager"), exports);
35
- __exportStar(require("./browser-utils"), exports);
35
+ __exportStar(require("./browser-utils"), exports);
36
+ __exportStar(require("./sticker"), exports);
37
+ __exportStar(require("./message-composer"), exports);
38
+ __exportStar(require("./use-sqlite-auth-state"), exports);
@@ -0,0 +1,290 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const __def = (m) => (m && m.__esModule) ? m.default : m;
4
+ const __exportStar = (m, e) => { for (const k in m) if (k !== "default" && !Object.prototype.hasOwnProperty.call(e, k)) e[k] = m[k]; };
5
+ const { proto } = require("../../WAProto/index.js");
6
+ const { generateMessageIDV2 } = require("./generics.js");
7
+
8
+ const JS_KEYWORDS = new Set([
9
+ 'import', 'export', 'from', 'default', 'as', 'const', 'let', 'var',
10
+ 'function', 'class', 'extends', 'new', 'return', 'if', 'else', 'for',
11
+ 'while', 'do', 'switch', 'case', 'break', 'continue', 'try', 'catch',
12
+ 'finally', 'throw', 'async', 'await', 'yield', 'typeof', 'instanceof',
13
+ 'in', 'of', 'delete', 'void', 'true', 'false', 'null', 'undefined',
14
+ 'NaN', 'Infinity', 'this', 'super', 'static', 'get', 'set', 'debugger', 'with'
15
+ ])
16
+
17
+ const PYTHON_KEYWORDS = new Set([
18
+ 'import', 'from', 'as', 'def', 'class', 'return', 'if', 'elif', 'else',
19
+ 'for', 'while', 'break', 'continue', 'try', 'except', 'finally', 'raise',
20
+ 'with', 'yield', 'lambda', 'pass', 'del', 'global', 'nonlocal', 'assert',
21
+ 'True', 'False', 'None', 'and', 'or', 'not', 'in', 'is', 'async', 'await',
22
+ 'self', 'print'
23
+ ])
24
+
25
+ const LANGUAGE_KEYWORDS = {
26
+ javascript: JS_KEYWORDS,
27
+ typescript: JS_KEYWORDS,
28
+ js: JS_KEYWORDS,
29
+ ts: JS_KEYWORDS,
30
+ python: PYTHON_KEYWORDS,
31
+ py: PYTHON_KEYWORDS
32
+ }
33
+
34
+ var CodeHighlightType
35
+ ;(function (CodeHighlightType) {
36
+ CodeHighlightType[(CodeHighlightType['DEFAULT'] = 0)] = 'DEFAULT'
37
+ CodeHighlightType[(CodeHighlightType['KEYWORD'] = 1)] = 'KEYWORD'
38
+ CodeHighlightType[(CodeHighlightType['METHOD'] = 2)] = 'METHOD'
39
+ CodeHighlightType[(CodeHighlightType['STRING'] = 3)] = 'STRING'
40
+ CodeHighlightType[(CodeHighlightType['NUMBER'] = 4)] = 'NUMBER'
41
+ CodeHighlightType[(CodeHighlightType['COMMENT'] = 5)] = 'COMMENT'
42
+ })(CodeHighlightType || (CodeHighlightType = {}))
43
+
44
+ var RichSubMessageType
45
+ ;(function (RichSubMessageType) {
46
+ RichSubMessageType[(RichSubMessageType['UNKNOWN'] = 0)] = 'UNKNOWN'
47
+ RichSubMessageType[(RichSubMessageType['GRID_IMAGE'] = 1)] = 'GRID_IMAGE'
48
+ RichSubMessageType[(RichSubMessageType['TEXT'] = 2)] = 'TEXT'
49
+ RichSubMessageType[(RichSubMessageType['INLINE_IMAGE'] = 3)] = 'INLINE_IMAGE'
50
+ RichSubMessageType[(RichSubMessageType['TABLE'] = 4)] = 'TABLE'
51
+ RichSubMessageType[(RichSubMessageType['CODE'] = 5)] = 'CODE'
52
+ RichSubMessageType[(RichSubMessageType['DYNAMIC'] = 6)] = 'DYNAMIC'
53
+ RichSubMessageType[(RichSubMessageType['MAP'] = 7)] = 'MAP'
54
+ RichSubMessageType[(RichSubMessageType['LATEX'] = 8)] = 'LATEX'
55
+ RichSubMessageType[(RichSubMessageType['CONTENT_ITEMS'] = 9)] = 'CONTENT_ITEMS'
56
+ })(RichSubMessageType || (RichSubMessageType = {}))
57
+
58
+ const tokenizeCode = (codeStr, language = 'javascript') => {
59
+ const keywords = LANGUAGE_KEYWORDS[language] || JS_KEYWORDS
60
+ const blocks = []
61
+ const lines = codeStr.split('\n')
62
+ for (let li = 0; li < lines.length; li++) {
63
+ const line = lines[li]
64
+ const isLast = li === lines.length - 1
65
+ const nl = isLast? '' : '\n'
66
+ if (!line.trim()) {
67
+ blocks.push({ highlightType: CodeHighlightType.DEFAULT, codeContent: line + nl })
68
+ continue
69
+ }
70
+ if (line.trim().startsWith('//') || line.trim().startsWith('#')) {
71
+ blocks.push({ highlightType: CodeHighlightType.COMMENT, codeContent: line + nl })
72
+ continue
73
+ }
74
+ const regex = /(\/\/.*$|#.*$)|(["'`](?:[^"'`\\]|\\.)*["'`])|(\b\d+(?:\.\d+)?\b)|(\b[a-zA-Z_$][\w$]*\b)|([^\s\w$"'`]+)|(\s+)/g
75
+ let match
76
+ const tokens = []
77
+ while ((match = regex.exec(line))!== null) {
78
+ const val = match[0]
79
+ if (match[1]) {
80
+ tokens.push({ highlightType: CodeHighlightType.COMMENT, codeContent: val })
81
+ } else if (match[2]) {
82
+ tokens.push({ highlightType: CodeHighlightType.STRING, codeContent: val })
83
+ } else if (match[3]) {
84
+ tokens.push({ highlightType: CodeHighlightType.NUMBER, codeContent: val })
85
+ } else if (match[4]) {
86
+ if (keywords.has(val)) {
87
+ tokens.push({ highlightType: CodeHighlightType.KEYWORD, codeContent: val })
88
+ } else {
89
+ const after = line.slice(regex.lastIndex).trimStart()
90
+ if (after.startsWith('(')) {
91
+ tokens.push({ highlightType: CodeHighlightType.METHOD, codeContent: val })
92
+ } else {
93
+ tokens.push({ highlightType: CodeHighlightType.DEFAULT, codeContent: val })
94
+ }
95
+ }
96
+ } else {
97
+ tokens.push({ highlightType: CodeHighlightType.DEFAULT, codeContent: val })
98
+ }
99
+ }
100
+ if (tokens.length === 0) {
101
+ blocks.push({ highlightType: CodeHighlightType.DEFAULT, codeContent: line + nl })
102
+ continue
103
+ }
104
+ const merged = []
105
+ for (const t of tokens) {
106
+ const prev = merged.length > 0? merged[merged.length - 1] : undefined
107
+ if (prev && prev.highlightType === t.highlightType) {
108
+ prev.codeContent += t.codeContent
109
+ } else {
110
+ merged.push({...t })
111
+ }
112
+ }
113
+ if (merged.length > 0) {
114
+ merged[merged.length - 1].codeContent += nl
115
+ }
116
+ blocks.push(...merged)
117
+ }
118
+ return blocks
119
+ }
120
+
121
+ const buildRichContextInfo = (quoted, options) => {
122
+ const ctxInfo = {
123
+ forwardingScore: 1,
124
+ isForwarded: true,
125
+ forwardedAiBotMessageInfo: { botJid: options?.botJid? options.botJid : '867051314767696@bot' },
126
+ forwardOrigin: 4,
127
+ ...(options?.mentions? { mentionedJid: options.mentions } : {})
128
+ }
129
+ if (quoted?.key) {
130
+ ctxInfo.stanzaId = quoted.key.id
131
+ ctxInfo.participant = quoted.key.participant || quoted.sender || quoted.key.remoteJid
132
+ ctxInfo.quotedMessage = quoted.message
133
+ }
134
+ return ctxInfo
135
+ }
136
+
137
+ const buildBotForwardedMessage = (submessages, contextInfo, unifiedResponse) => {
138
+ const richResponse = { messageType: 1, submessages, contextInfo }
139
+ if (unifiedResponse) {
140
+ richResponse.unifiedResponse = unifiedResponse
141
+ }
142
+ return {
143
+ botForwardedMessage: {
144
+ message: { richResponseMessage: richResponse }
145
+ }
146
+ }
147
+ }
148
+
149
+ const generateTableContent = (title, headers, rows, quoted, options = {}) => {
150
+ const { footer, headerText } = options
151
+ const tableRows = [{ items: headers, isHeading: true },...rows.map(row => ({ items: row.map(String) }))]
152
+ const submessages = []
153
+ if (headerText) submessages.push({ messageType: 2, messageText: headerText })
154
+ submessages.push({ messageType: 4, tableMetadata: { title, rows: tableRows } })
155
+ if (footer) submessages.push({ messageType: 2, messageText: footer })
156
+ const ctxInfo = buildRichContextInfo(quoted)
157
+ return { message: buildBotForwardedMessage(submessages, ctxInfo), messageId: generateMessageIDV2() }
158
+ }
159
+
160
+ const generateListContent = (title, items, quoted, options = {}) => {
161
+ const { footer, headerText } = options
162
+ const tableRows = items.map(item => ({
163
+ items: Array.isArray(item)? item.map(String) : [String(item)]
164
+ }))
165
+ const submessages = []
166
+ if (headerText) submessages.push({ messageType: 2, messageText: headerText })
167
+ submessages.push({ messageType: 4, tableMetadata: { title, rows: tableRows } })
168
+ if (footer) submessages.push({ messageType: 2, messageText: footer })
169
+ const ctxInfo = buildRichContextInfo(quoted)
170
+ return { message: buildBotForwardedMessage(submessages, ctxInfo), messageId: generateMessageIDV2() }
171
+ }
172
+
173
+ const generateCodeBlockContent = (code, quoted, options = {}) => {
174
+ const { title, footer, language = 'javascript' } = options
175
+ const submessages = []
176
+ if (title) submessages.push({ messageType: 2, messageText: title })
177
+ submessages.push({
178
+ messageType: 5,
179
+ codeMetadata: { codeLanguage: language, codeBlocks: tokenizeCode(code, language) }
180
+ })
181
+ if (footer) submessages.push({ messageType: 2, messageText: footer })
182
+ const ctxInfo = buildRichContextInfo(quoted)
183
+ return { message: buildBotForwardedMessage(submessages, ctxInfo), messageId: generateMessageIDV2() }
184
+ }
185
+
186
+ const generateLatexContent = (quoted, options) => {
187
+ const { text, expressions, headerText, footer } = options
188
+ const submessages = []
189
+ if (headerText) submessages.push({ messageType: 2, messageText: headerText })
190
+ const latexExpressions = expressions.map(expr => {
191
+ const entry = {
192
+ latexExpression: expr.latexExpression,
193
+ url: expr.url,
194
+ width: expr.width,
195
+ height: expr.height
196
+ }
197
+ if (expr.fontHeight!== undefined) entry.fontHeight = expr.fontHeight
198
+ if (expr.imageTopPadding!== undefined) entry.imageTopPadding = expr.imageTopPadding
199
+ if (expr.imageLeadingPadding!== undefined) entry.imageLeadingPadding = expr.imageLeadingPadding
200
+ if (expr.imageBottomPadding!== undefined) entry.imageBottomPadding = expr.imageBottomPadding
201
+ if (expr.imageTrailingPadding!== undefined) entry.imageTrailingPadding = expr.imageTrailingPadding
202
+ return entry
203
+ })
204
+ submessages.push({ messageType: 8, latexMetadata: { text: text || '', expressions: latexExpressions } })
205
+ if (footer) submessages.push({ messageType: 2, messageText: footer })
206
+ const ctxInfo = buildRichContextInfo(quoted)
207
+ return { message: buildBotForwardedMessage(submessages, ctxInfo), messageId: generateMessageIDV2() }
208
+ }
209
+
210
+ const generateLatexImageContent = async (quoted, options, uploadFn, renderLatexToPng) => {
211
+ const { text, expressions, headerText, footer } = options
212
+ const submessages = []
213
+ if (headerText) submessages.push({ messageType: 2, messageText: headerText })
214
+ const latexExpressions = await Promise.all(
215
+ expressions.map(async expr => {
216
+ const { buffer, width, height } = await renderLatexToPng(expr.latexExpression)
217
+ const uploadResult = await uploadFn(buffer, 'image')
218
+ const imageUrl = uploadResult.url || uploadResult.directPath
219
+ return { latexExpression: expr.latexExpression, url: imageUrl, width, height }
220
+ })
221
+ )
222
+ submessages.push({ messageType: 8, latexMetadata: { text: text || '', expressions: latexExpressions } })
223
+ if (footer) submessages.push({ messageType: 2, messageText: footer })
224
+ const ctxInfo = buildRichContextInfo(quoted)
225
+ return { message: buildBotForwardedMessage(submessages, ctxInfo), messageId: generateMessageIDV2() }
226
+ }
227
+
228
+ const generateLatexInlineImageContent = async (quoted, options, uploadFn, renderLatexToPng) => {
229
+ const { text, expressions, headerText, footer } = options
230
+ const submessages = []
231
+ if (headerText) submessages.push({ messageType: 2, messageText: headerText })
232
+ if (text) submessages.push({ messageType: 2, messageText: text })
233
+ for (const expr of expressions) {
234
+ const { buffer, width, height } = await renderLatexToPng(expr.latexExpression)
235
+ const uploadResult = await uploadFn(buffer, 'image')
236
+ const imageUrl = uploadResult.url || uploadResult.directPath
237
+ submessages.push({
238
+ messageType: 3,
239
+ imageMetadata: {
240
+ imageUrl: { imagePreviewUrl: imageUrl, imageHighResUrl: imageUrl },
241
+ imageText: expr.latexExpression,
242
+ alignment: 2
243
+ }
244
+ })
245
+ }
246
+ if (footer) submessages.push({ messageType: 2, messageText: footer })
247
+ const ctxInfo = buildRichContextInfo(quoted)
248
+ return { message: buildBotForwardedMessage(submessages, ctxInfo), messageId: generateMessageIDV2() }
249
+ }
250
+
251
+ const captureUnifiedResponse = msg => {
252
+ const botFwd = msg?.botForwardedMessage?.message
253
+ if (!botFwd) return null
254
+ const rich = botFwd.richResponseMessage
255
+ if (!rich?.unifiedResponse?.data) return null
256
+ return {
257
+ unifiedResponse: { data: rich.unifiedResponse.data },
258
+ submessages: rich.submessages || [],
259
+ contextInfo: rich.contextInfo || {}
260
+ }
261
+ }
262
+
263
+ const generateUnifiedResponseContent = (quoted, captured) => {
264
+ const ctxInfo = buildRichContextInfo(quoted)
265
+ return { message: buildBotForwardedMessage(captured.submessages, ctxInfo, captured.unifiedResponse), messageId: generateMessageIDV2() }
266
+ }
267
+
268
+ const generateRichMessageContent = (submessages, quoted, options) => {
269
+ const ctxInfo = buildRichContextInfo(quoted, options)
270
+ return { message: buildBotForwardedMessage(submessages, ctxInfo), messageId: generateMessageIDV2() }
271
+ }
272
+
273
+
274
+ exports.JS_KEYWORDS = JS_KEYWORDS;
275
+ exports.PYTHON_KEYWORDS = PYTHON_KEYWORDS;
276
+ exports.LANGUAGE_KEYWORDS = LANGUAGE_KEYWORDS;
277
+ exports.CodeHighlightType = CodeHighlightType;
278
+ exports.RichSubMessageType = RichSubMessageType;
279
+ exports.tokenizeCode = tokenizeCode;
280
+ exports.buildRichContextInfo = buildRichContextInfo;
281
+ exports.buildBotForwardedMessage = buildBotForwardedMessage;
282
+ exports.generateTableContent = generateTableContent;
283
+ exports.generateListContent = generateListContent;
284
+ exports.generateCodeBlockContent = generateCodeBlockContent;
285
+ exports.generateLatexContent = generateLatexContent;
286
+ exports.generateLatexImageContent = generateLatexImageContent;
287
+ exports.generateLatexInlineImageContent = generateLatexInlineImageContent;
288
+ exports.captureUnifiedResponse = captureUnifiedResponse;
289
+ exports.generateUnifiedResponseContent = generateUnifiedResponseContent;
290
+ exports.generateRichMessageContent = generateRichMessageContent;
@@ -0,0 +1,143 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const __def = (m) => (m && m.__esModule) ? m.default : m;
4
+ const __exportStar = (m, e) => { for (const k in m) if (k !== "default" && !Object.prototype.hasOwnProperty.call(e, k)) e[k] = m[k]; };
5
+ const { Boom } = require("@hapi/boom");
6
+ const { spawn } = require("child_process");
7
+ const { randomUUID } = require("crypto");
8
+
9
+ const runFfmpeg = (input, args) => new Promise((resolve, reject) => {
10
+ const proc = spawn('ffmpeg', ['-hide_banner', '-loglevel', 'error', '-i', 'pipe:0', ...args, 'pipe:1'], { stdio: ['pipe', 'pipe', 'pipe'] });
11
+ const outChunks = [];
12
+ const errChunks = [];
13
+ proc.stdout.on('data', chunk => outChunks.push(chunk));
14
+ proc.stderr.on('data', chunk => errChunks.push(chunk));
15
+ proc.on('error', err => reject(new Boom(`ffmpeg failed to start: ${err.message}`, { statusCode: 500 })));
16
+ proc.on('close', code => {
17
+ if (code !== 0) {
18
+ reject(new Boom(`ffmpeg exited with code ${code}: ${Buffer.concat(errChunks).toString('utf8').slice(0, 500)}`, { statusCode: 500 }));
19
+ return;
20
+ }
21
+ resolve(Buffer.concat(outChunks));
22
+ });
23
+ proc.stdin.on('error', () => { });
24
+ proc.stdin.end(input);
25
+ });
26
+ const isLikelyVideoBuffer = (buffer) => {
27
+ if (!Buffer.isBuffer(buffer) || buffer.length < 4) {
28
+ return false;
29
+ }
30
+ const header = buffer.subarray(0, 16).toString('ascii');
31
+ if (header.startsWith('RIFF') && /AVI|WEBM/.test(header)) {
32
+ return true;
33
+ }
34
+ if (buffer.subarray(0, 4).toString('hex') === '1a45dfa3') {
35
+ return true;
36
+ }
37
+ const ftyp = buffer.toString('ascii', 4, 12);
38
+ if (buffer.toString('ascii', 0, 4) === 'ftyp' || /^(ftyp)/.test(buffer.toString('ascii', 0, 8))) {
39
+ return /mp4|isom|M4V|M4A|qt\s/.test(ftyp);
40
+ }
41
+ return false;
42
+ };
43
+ const convertToWebp = async (buffer, { animated = false, quality = 60 } = {}) => {
44
+ const scalePad = "scale='min(512,iw)':'min(512,ih)':force_original_aspect_ratio=decrease,format=rgba,pad=512:512:-1:-1:color=#00000000";
45
+ const args = animated
46
+ ? ['-vf', `${scalePad},fps=15`, '-loop', '0', '-preset', 'default', '-an', '-vsync', '0', '-vcodec', 'libwebp', '-q:v', String(quality), '-f', 'webp']
47
+ : ['-vf', `${scalePad}`, '-vframes', '1', '-vcodec', 'libwebp', '-q:v', String(quality), '-f', 'webp'];
48
+ return runFfmpeg(buffer, args);
49
+ };
50
+ const convertToTrayIcon = async (buffer) => {
51
+ const scalePad = "scale='min(96,iw)':'min(96,ih)':force_original_aspect_ratio=decrease,format=rgba,pad=96:96:-1:-1:color=#00000000";
52
+ const args = ['-vf', scalePad, '-vframes', '1', '-vcodec', 'png', '-f', 'image2'];
53
+ return runFfmpeg(buffer, args);
54
+ };
55
+ const readChunks = (buf) => {
56
+ const chunks = [];
57
+ let offset = 12;
58
+ while (offset + 8 <= buf.length) {
59
+ const fourCC = buf.toString('ascii', offset, offset + 4);
60
+ const size = buf.readUInt32LE(offset + 4);
61
+ const dataStart = offset + 8;
62
+ const data = buf.subarray(dataStart, dataStart + size);
63
+ chunks.push({ fourCC, data });
64
+ offset = dataStart + size + (size % 2);
65
+ }
66
+ return chunks;
67
+ };
68
+ const buildChunk = (fourCC, data) => {
69
+ const header = Buffer.alloc(8);
70
+ header.write(fourCC, 0, 4, 'ascii');
71
+ header.writeUInt32LE(data.length, 4);
72
+ const pad = data.length % 2 === 1 ? Buffer.from([0]) : Buffer.alloc(0);
73
+ return Buffer.concat([header, data, pad]);
74
+ };
75
+ const buildExifChunkData = (json) => {
76
+ const header = Buffer.from([0x49, 0x49, 0x2a, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x41, 0x57, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00]);
77
+ const payload = Buffer.from(JSON.stringify(json), 'utf8');
78
+ header.writeUInt32LE(payload.length, 14);
79
+ return Buffer.concat([header, payload]);
80
+ };
81
+ const writeExifToWebp = (webpBuffer, { packId, packName = '', publisher = '', emojis = [], isAvatar = false } = {}) => {
82
+ if (webpBuffer.toString('ascii', 0, 4) !== 'RIFF' || webpBuffer.toString('ascii', 8, 12) !== 'WEBP') {
83
+ throw new Boom('writeExifToWebp: not a valid webp buffer', { statusCode: 400 });
84
+ }
85
+ const chunks = readChunks(webpBuffer);
86
+ const exifData = buildExifChunkData({
87
+ 'sticker-pack-id': packId || randomUUID(),
88
+ 'sticker-pack-name': packName,
89
+ 'sticker-pack-publisher': publisher,
90
+ emojis: emojis.length ? emojis : ['🤖'],
91
+ 'is-avatar-sticker': isAvatar ? 1 : 0
92
+ });
93
+ let vp8x = chunks.find(c => c.fourCC === 'VP8X');
94
+ const otherChunks = chunks.filter(c => c.fourCC !== 'VP8X' && c.fourCC !== 'EXIF');
95
+ if (!vp8x) {
96
+ const img = otherChunks.find(c => c.fourCC === 'VP8 ' || c.fourCC === 'VP8L');
97
+ if (!img) {
98
+ throw new Boom('writeExifToWebp: no VP8/VP8L image data found', { statusCode: 400 });
99
+ }
100
+ let width;
101
+ let height;
102
+ if (img.fourCC === 'VP8 ') {
103
+ width = (img.data.readUInt16LE(6) & 0x3fff);
104
+ height = (img.data.readUInt16LE(8) & 0x3fff);
105
+ }
106
+ else {
107
+ const b = img.data;
108
+ width = 1 + (((b[2] & 0x3f) << 8) | b[1]);
109
+ height = 1 + (((b[4] & 0xf) << 10) | (b[3] << 2) | ((b[2] & 0xc0) >> 6));
110
+ }
111
+ const flags = Buffer.alloc(4);
112
+ flags[0] = 0x08;
113
+ const dims = Buffer.alloc(6);
114
+ dims.writeUIntLE(width - 1, 0, 3);
115
+ dims.writeUIntLE(height - 1, 3, 3);
116
+ vp8x = { fourCC: 'VP8X', data: Buffer.concat([flags, dims]) };
117
+ }
118
+ else {
119
+ const flagsByte = vp8x.data[0] | 0x08;
120
+ vp8x = { fourCC: 'VP8X', data: Buffer.concat([Buffer.from([flagsByte]), vp8x.data.subarray(1)]) };
121
+ }
122
+ const rebuilt = [vp8x, ...otherChunks, { fourCC: 'EXIF', data: exifData }];
123
+ const chunkBuffers = rebuilt.map(c => buildChunk(c.fourCC, c.data));
124
+ const payload = Buffer.concat(chunkBuffers);
125
+ const riffSize = 4 + payload.length;
126
+ const out = Buffer.alloc(8 + 4 + payload.length);
127
+ out.write('RIFF', 0, 4, 'ascii');
128
+ out.writeUInt32LE(riffSize, 4);
129
+ out.write('WEBP', 8, 4, 'ascii');
130
+ payload.copy(out, 12);
131
+ return out;
132
+ };
133
+ const makeSticker = async (buffer, { pack = '', author = '', emojis = [], isPrivate = false, animated = false, quality = 60 } = {}) => {
134
+ const shouldAnimate = animated || isLikelyVideoBuffer(buffer);
135
+ const webp = await convertToWebp(buffer, { animated: shouldAnimate, quality });
136
+ return writeExifToWebp(webp, { packName: pack, publisher: author, emojis, isAvatar: isPrivate });
137
+ };
138
+
139
+ exports.isLikelyVideoBuffer = isLikelyVideoBuffer;
140
+ exports.convertToWebp = convertToWebp;
141
+ exports.convertToTrayIcon = convertToTrayIcon;
142
+ exports.writeExifToWebp = writeExifToWebp;
143
+ exports.makeSticker = makeSticker;