discord-message-transcript 1.3.1-dev.1.46 → 1.3.1-dev.1.48

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 (40) hide show
  1. package/dist/core/{imageToBase64.js → assetResolver/base64/imageToBase64.js} +3 -2
  2. package/dist/core/assetResolver/cdn/cdnCustomError.d.ts +16 -0
  3. package/dist/core/assetResolver/cdn/cdnCustomError.js +28 -0
  4. package/dist/core/assetResolver/cdn/cdnResolver.d.ts +3 -0
  5. package/dist/core/assetResolver/cdn/cdnResolver.js +90 -0
  6. package/dist/core/assetResolver/cdn/cloudinaryCdnResolver.d.ts +1 -0
  7. package/dist/core/assetResolver/cdn/cloudinaryCdnResolver.js +120 -0
  8. package/dist/core/assetResolver/cdn/sanitizeFileName.d.ts +1 -0
  9. package/dist/core/assetResolver/cdn/sanitizeFileName.js +17 -0
  10. package/dist/core/assetResolver/cdn/uploadCareCdnResolver.d.ts +1 -0
  11. package/dist/core/assetResolver/cdn/uploadCareCdnResolver.js +137 -0
  12. package/dist/core/assetResolver/cdn/validateCdnUrl.d.ts +1 -0
  13. package/dist/core/assetResolver/cdn/validateCdnUrl.js +8 -0
  14. package/dist/core/assetResolver/contants.d.ts +1 -0
  15. package/dist/core/assetResolver/contants.js +1 -0
  16. package/dist/core/assetResolver/index.d.ts +5 -0
  17. package/dist/core/assetResolver/index.js +5 -0
  18. package/dist/core/assetResolver/url/authorUrlResolver.d.ts +3 -0
  19. package/dist/core/assetResolver/url/authorUrlResolver.js +10 -0
  20. package/dist/core/assetResolver/url/imageUrlResolver.d.ts +4 -0
  21. package/dist/core/{resolveImageUrl.js → assetResolver/url/imageUrlResolver.js} +1 -1
  22. package/dist/core/assetResolver/url/messageUrlResolver.d.ts +3 -0
  23. package/dist/core/{urlResolver.js → assetResolver/url/messageUrlResolver.js} +11 -42
  24. package/dist/core/assetResolver/url/urlResolver.d.ts +3 -0
  25. package/dist/core/assetResolver/url/urlResolver.js +24 -0
  26. package/dist/core/componentToJson.d.ts +1 -1
  27. package/dist/core/componentToJson.js +143 -129
  28. package/dist/index.d.ts +1 -1
  29. package/dist/index.js +2 -2
  30. package/dist/renderers/json/json.js +3 -4
  31. package/dist/utils/sleep.d.ts +1 -0
  32. package/dist/utils/sleep.js +3 -0
  33. package/package.json +2 -2
  34. package/dist/core/cdnResolver.d.ts +0 -5
  35. package/dist/core/cdnResolver.js +0 -213
  36. package/dist/core/resolveImageUrl.d.ts +0 -4
  37. package/dist/core/urlResolver.d.ts +0 -5
  38. /package/dist/core/{imageToBase64.d.ts → assetResolver/base64/imageToBase64.d.ts} +0 -0
  39. /package/dist/core/{limiter.d.ts → assetResolver/limiter.d.ts} +0 -0
  40. /package/dist/core/{limiter.js → assetResolver/limiter.js} +0 -0
@@ -3,137 +3,151 @@ import { mapButtonStyle, mapSelectorType, mapSeparatorSpacing } from "./mappers.
3
3
  import { JsonComponentType } from "discord-message-transcript-base";
4
4
  import { isValidHexColor } from "discord-message-transcript-base";
5
5
  export async function componentsToJson(components, options) {
6
- const processedComponents = await Promise.all(components.filter(component => !(!options.includeV2Components && component.type != ComponentType.ActionRow))
7
- .map(async (component) => {
8
- switch (component.type) {
9
- case ComponentType.ActionRow: {
10
- const actionRowComponents = await Promise.all(component.components.filter(c => {
11
- if (c.type == ComponentType.Button && !options.includeButtons)
12
- return false;
13
- if (c.type != ComponentType.Button && !options.includeComponents)
14
- return false;
15
- return true;
16
- }).map(async (c) => {
17
- if (c.type === ComponentType.Button) {
18
- return {
19
- type: JsonComponentType.Button,
20
- style: mapButtonStyle(c.style),
21
- label: c.label,
22
- emoji: c.emoji?.name ? c.emoji.name : null,
23
- url: c.url,
24
- disabled: c.disabled,
25
- };
26
- }
27
- else if (c.type === ComponentType.StringSelect) {
28
- return {
29
- type: JsonComponentType.StringSelect,
30
- placeholder: c.placeholder,
31
- disabled: c.disabled,
32
- options: c.options.map(option => ({
33
- label: option.label,
34
- description: option.description ?? null,
35
- emoji: option.emoji ? {
36
- id: option.emoji.id ?? null,
37
- name: option.emoji.name ?? null,
38
- animated: option.emoji.animated ?? false,
39
- } : null,
40
- }))
41
- };
42
- }
43
- else {
44
- return {
45
- type: mapSelectorType(c.type),
46
- placeholder: c.placeholder,
47
- disabled: c.disabled,
48
- };
49
- }
50
- }));
51
- if (actionRowComponents.length > 0)
52
- return { type: JsonComponentType.ActionRow, components: actionRowComponents };
53
- return null;
54
- }
55
- case ComponentType.Container: {
56
- const newOptions = { ...options, includeComponents: true, includeButtons: true };
57
- const componentsJson = await componentsToJson(component.components, newOptions);
58
- return {
59
- type: JsonComponentType.Container,
60
- components: componentsJson.filter(isJsonComponentInContainer), // Input components that are container-safe must always produce container-safe output.
61
- hexAccentColor: isValidHexColor(component.hexAccentColor, false),
62
- spoiler: component.spoiler,
63
- };
64
- }
65
- case ComponentType.File: {
66
- return {
67
- type: JsonComponentType.File,
68
- fileName: component.data.name ?? null,
69
- size: component.data.size ?? 0,
70
- url: component.file.url,
71
- spoiler: component.spoiler,
72
- };
73
- }
74
- case ComponentType.MediaGallery: {
75
- const mediaItems = component.items.map(item => {
76
- return {
77
- media: { url: item.media.url },
78
- spoiler: item.spoiler,
79
- };
80
- });
81
- return {
82
- type: JsonComponentType.MediaGallery,
83
- items: mediaItems,
84
- };
85
- }
86
- case ComponentType.Section: {
87
- let accessoryJson;
88
- if (component.accessory.type === ComponentType.Button) {
89
- accessoryJson = {
90
- type: JsonComponentType.Button,
91
- style: mapButtonStyle(component.accessory.style),
92
- label: component.accessory.label,
93
- emoji: component.accessory.emoji?.name ? component.accessory.emoji.name : null,
94
- url: component.accessory.url,
95
- disabled: component.accessory.disabled,
96
- };
97
- }
98
- else if (component.accessory.type === ComponentType.Thumbnail) {
99
- accessoryJson = {
100
- type: JsonComponentType.Thumbnail,
101
- media: {
102
- url: component.accessory.media.url,
103
- },
104
- spoiler: component.accessory.spoiler,
105
- };
106
- }
107
- else
108
- return null;
109
- const sectionComponents = component.components.map(c => ({
110
- type: JsonComponentType.TextDisplay,
111
- content: c.content,
112
- }));
113
- return {
114
- type: JsonComponentType.Section,
115
- accessory: accessoryJson,
116
- components: sectionComponents,
117
- };
118
- }
119
- case ComponentType.Separator: {
120
- return {
121
- type: JsonComponentType.Separator,
122
- spacing: mapSeparatorSpacing(component.spacing),
123
- divider: component.divider,
124
- };
125
- }
126
- case ComponentType.TextDisplay: {
127
- return {
128
- type: JsonComponentType.TextDisplay,
129
- content: component.content,
130
- };
131
- }
132
- default:
133
- return null;
6
+ const filtered = components.filter(c => options.includeV2Components || c.type === ComponentType.ActionRow);
7
+ const processed = await Promise.all(filtered.map(c => convertComponent(c, options)));
8
+ return processed.filter(c => c != null);
9
+ }
10
+ async function convertComponent(component, options) {
11
+ switch (component.type) {
12
+ case ComponentType.ActionRow:
13
+ return convertActionRow(component, options);
14
+ case ComponentType.Container:
15
+ return convertContainer(component, options);
16
+ case ComponentType.File:
17
+ return convertFile(component);
18
+ case ComponentType.MediaGallery:
19
+ return convertMediaGallery(component);
20
+ case ComponentType.Section:
21
+ return convertSection(component);
22
+ case ComponentType.Separator:
23
+ return convertSeparator(component);
24
+ case ComponentType.TextDisplay:
25
+ return convertTextDisplay(component);
26
+ default:
27
+ return null;
28
+ }
29
+ }
30
+ async function convertActionRow(component, options) {
31
+ const rowComponents = await Promise.all(component.components
32
+ .filter(c => (c.type === ComponentType.Button ? options.includeButtons : options.includeComponents))
33
+ .map(c => convertActionRowChild(c)));
34
+ if (rowComponents.length === 0)
35
+ return null;
36
+ return { type: JsonComponentType.ActionRow, components: rowComponents };
37
+ }
38
+ async function convertActionRowChild(component) {
39
+ switch (component.type) {
40
+ case ComponentType.Button: {
41
+ return {
42
+ type: JsonComponentType.Button,
43
+ style: mapButtonStyle(component.style),
44
+ label: component.label,
45
+ emoji: component.emoji?.name ?? null,
46
+ url: component.url,
47
+ disabled: component.disabled,
48
+ };
49
+ }
50
+ case ComponentType.StringSelect: {
51
+ return {
52
+ type: JsonComponentType.StringSelect,
53
+ placeholder: component.placeholder,
54
+ disabled: component.disabled,
55
+ options: component.options.map(option => ({
56
+ label: option.label,
57
+ description: option.description ?? null,
58
+ emoji: option.emoji ? { id: option.emoji.id ?? null, name: option.emoji.name ?? null, animated: option.emoji.animated ?? false } : null,
59
+ })),
60
+ };
61
+ }
62
+ default: {
63
+ return {
64
+ type: mapSelectorType(component.type),
65
+ placeholder: component.placeholder,
66
+ disabled: component.disabled,
67
+ };
68
+ }
69
+ }
70
+ }
71
+ async function convertContainer(component, options) {
72
+ const newOptions = { ...options, includeComponents: true, includeButtons: true };
73
+ const componentsJson = await componentsToJson(component.components, newOptions);
74
+ return {
75
+ type: JsonComponentType.Container,
76
+ components: componentsJson.filter(isJsonComponentInContainer), // Input components that are container-safe must always produce container-safe output.
77
+ hexAccentColor: isValidHexColor(component.hexAccentColor, false),
78
+ spoiler: component.spoiler,
79
+ };
80
+ }
81
+ function convertFile(component) {
82
+ return {
83
+ type: JsonComponentType.File,
84
+ fileName: component.data.name ?? null,
85
+ size: component.data.size ?? 0,
86
+ url: component.file.url,
87
+ spoiler: component.spoiler,
88
+ };
89
+ }
90
+ async function convertMediaGallery(component) {
91
+ const mediaItems = await Promise.all(component.items.map(item => {
92
+ return {
93
+ media: { url: item.media.url },
94
+ spoiler: item.spoiler,
95
+ };
96
+ }));
97
+ return {
98
+ type: JsonComponentType.MediaGallery,
99
+ items: mediaItems,
100
+ };
101
+ }
102
+ function convertSection(component) {
103
+ let accessoryJson = null;
104
+ switch (component.accessory.type) {
105
+ case ComponentType.Button: {
106
+ accessoryJson = {
107
+ type: JsonComponentType.Button,
108
+ style: mapButtonStyle(component.accessory.style),
109
+ label: component.accessory.label,
110
+ emoji: component.accessory.emoji?.name ? component.accessory.emoji.name : null,
111
+ url: component.accessory.url,
112
+ disabled: component.accessory.disabled,
113
+ };
114
+ break;
134
115
  }
116
+ case ComponentType.Thumbnail: {
117
+ accessoryJson = {
118
+ type: JsonComponentType.Thumbnail,
119
+ media: {
120
+ url: component.accessory.media.url,
121
+ },
122
+ spoiler: component.accessory.spoiler,
123
+ };
124
+ break;
125
+ }
126
+ default:
127
+ break;
128
+ }
129
+ const sectionComponents = component.components.map(c => ({
130
+ type: JsonComponentType.TextDisplay,
131
+ content: c.content,
135
132
  }));
136
- return processedComponents.filter(c => c != null);
133
+ return {
134
+ type: JsonComponentType.Section,
135
+ accessory: accessoryJson,
136
+ components: sectionComponents,
137
+ };
138
+ }
139
+ function convertSeparator(component) {
140
+ return {
141
+ type: JsonComponentType.Separator,
142
+ spacing: mapSeparatorSpacing(component.spacing),
143
+ divider: component.divider,
144
+ };
145
+ }
146
+ function convertTextDisplay(component) {
147
+ return {
148
+ type: JsonComponentType.TextDisplay,
149
+ content: component.content,
150
+ };
137
151
  }
138
152
  export function isJsonComponentInContainer(component) {
139
153
  return (component.type == JsonComponentType.ActionRow ||
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export { CreateTranscriptOptions, ConvertTranscriptOptions, TranscriptOptions, ReturnType, CDNOptions, MimeType } from "@/types";
2
2
  export { ReturnFormat, LocalDate, TimeZone } from "discord-message-transcript-base";
3
- export { setBase64Concurrency, setCDNConcurrency } from '@/core/limiter.js';
3
+ export { setBase64Concurrency, setCDNConcurrency } from '@/assetResolver';
4
4
  import { TextBasedChannel } from "discord.js";
5
5
  import { ConvertTranscriptOptions, CreateTranscriptOptions, OutputType, ReturnType } from "@/types";
6
6
  /**
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  export { ReturnType } from "@/types";
2
2
  export { ReturnFormat } from "discord-message-transcript-base";
3
- export { setBase64Concurrency, setCDNConcurrency } from '@/core/limiter.js';
3
+ export { setBase64Concurrency, setCDNConcurrency } from '@/assetResolver';
4
4
  import { AttachmentBuilder } from "discord.js";
5
5
  import { Json } from "@/renderers/json/json.js";
6
6
  import { fetchMessages } from "@/core/fetchMessages.js";
@@ -8,7 +8,7 @@ import { ReturnType } from "@/types";
8
8
  import { output } from "@/core/output.js";
9
9
  import { ReturnTypeBase, ReturnFormat, outputBase, CustomError, CustomWarn } from "discord-message-transcript-base";
10
10
  import { returnTypeMapper } from "@/core/mappers.js";
11
- import { authorUrlResolver, messagesUrlResolver } from "@/core/urlResolver.js";
11
+ import { authorUrlResolver, messagesUrlResolver } from "@/assetResolver";
12
12
  /**
13
13
  * Creates a transcript of a Discord channel's messages.
14
14
  * Depending on the `returnType` option, this function can return an `AttachmentBuilder`,
@@ -1,6 +1,5 @@
1
1
  import { BaseGuildTextChannel, DMChannel } from "discord.js";
2
- import { urlResolver } from "@/core/urlResolver.js";
3
- import { resolveImageURL } from "@/core/resolveImageUrl.js";
2
+ import { imageUrlResolver, urlResolver } from "@/assetResolver";
4
3
  export class Json {
5
4
  guild;
6
5
  channel;
@@ -44,9 +43,9 @@ export class Json {
44
43
  async toJson() {
45
44
  const channel = await this.channel.fetch();
46
45
  const channelImg = channel instanceof DMChannel ? channel.recipient?.displayAvatarURL() ?? "cdn.discordapp.com/embed/avatars/4.png" : channel.isDMBased() ? channel.iconURL() ?? (await channel.fetchOwner()).displayAvatarURL() : null;
47
- const safeChannelImg = await resolveImageURL(channelImg, this.options, true);
46
+ const safeChannelImg = await imageUrlResolver(channelImg, this.options, true);
48
47
  const guild = !channel.isDMBased() ? this.guild : null;
49
- const guildIcon = guild ? await resolveImageURL(guild.iconURL(), this.options, true) : null;
48
+ const guildIcon = guild ? await imageUrlResolver(guild.iconURL(), this.options, true) : null;
50
49
  const guildJson = !guild ? null : {
51
50
  name: guild.name,
52
51
  id: guild.id,
@@ -0,0 +1 @@
1
+ export declare function sleep(ms: number): Promise<unknown>;
@@ -0,0 +1,3 @@
1
+ export function sleep(ms) {
2
+ return new Promise(r => setTimeout(r, ms));
3
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "discord-message-transcript",
3
- "version": "1.3.1-dev.1.46",
3
+ "version": "1.3.1-dev.1.48",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -45,7 +45,7 @@
45
45
  },
46
46
  "homepage": "https://github.com/HenriqueMairesse/discord-message-transcript#readme",
47
47
  "dependencies": {
48
- "discord-message-transcript-base": "1.3.1-dev.1.46"
48
+ "discord-message-transcript-base": "1.3.1-dev.1.48"
49
49
  },
50
50
  "peerDependencies": {
51
51
  "discord.js": ">=14.19.0 <15"
@@ -1,5 +0,0 @@
1
- import { CDNOptions, safeUrlReturn } from "@/types";
2
- import { TranscriptOptionsBase } from "discord-message-transcript-base";
3
- export declare function cdnResolver(safeUrlObject: safeUrlReturn, options: TranscriptOptionsBase, cdnOptions: CDNOptions): Promise<string>;
4
- export declare function uploadCareResolver(url: string, publicKey: string, cdnDomain: string, disableWarnings: boolean): Promise<string>;
5
- export declare function cloudinaryResolver(url: string, fileName: string, cloudName: string, apiKey: string, apiSecret: string, disableWarnings: boolean): Promise<string>;
@@ -1,213 +0,0 @@
1
- import { CustomWarn } from "discord-message-transcript-base";
2
- import crypto from 'crypto';
3
- import { getCDNLimiter } from "./limiter.js";
4
- import https from 'https';
5
- import http from 'http';
6
- import { createLookup } from "@/networkSecurity";
7
- export async function cdnResolver(safeUrlObject, options, cdnOptions) {
8
- const url = safeUrlObject.url;
9
- const limit = getCDNLimiter();
10
- return limit(async () => {
11
- return new Promise((resolve, reject) => {
12
- const client = safeUrlObject.url.startsWith('https') ? https : http;
13
- const lookup = createLookup(safeUrlObject.safeIps);
14
- const request = client.get(url, {
15
- headers: { "User-Agent": "discord-message-transcript" },
16
- lookup: lookup
17
- }, async (response) => {
18
- if (response.statusCode !== 200) {
19
- response.destroy();
20
- CustomWarn(`This is not an issue with the package. Using the original URL as fallback instead of uploading to CDN.
21
- Failed to fetch attachment with status code: ${response.statusCode} from ${safeUrlObject.url}.`, options.disableWarnings);
22
- return resolve(url);
23
- }
24
- const contentType = response.headers["content-type"];
25
- const splitContentType = contentType ? contentType?.split('/') : [];
26
- if (!contentType || splitContentType.length != 2 || splitContentType[0].length == 0 || splitContentType[1].length == 0) {
27
- response.destroy();
28
- CustomWarn(`This is not an issue with the package. Using the original URL as fallback instead of uploading to CDN.
29
- Failed to receive a valid content-type from ${url}.`, options.disableWarnings);
30
- return resolve(url);
31
- }
32
- response.destroy();
33
- const isImage = contentType.startsWith('image/') && contentType !== 'image/gif';
34
- const isAudio = contentType.startsWith('audio/');
35
- const isVideo = contentType.startsWith('video/') || contentType === 'image/gif';
36
- if ((cdnOptions.includeImage && isImage) ||
37
- (cdnOptions.includeAudio && isAudio) ||
38
- (cdnOptions.includeVideo && isVideo) ||
39
- (cdnOptions.includeOthers && !isAudio && !isImage && !isVideo)) {
40
- return resolve(await cdnRedirectType(url, options, contentType, cdnOptions));
41
- }
42
- return resolve(url);
43
- });
44
- request.on('error', (err) => {
45
- CustomWarn(`This is not an issue with the package. Using the original URL as fallback instead of uploading to CDN.
46
- Error: ${err.message}`, options.disableWarnings);
47
- return resolve(url);
48
- });
49
- request.setTimeout(15000, () => {
50
- request.destroy();
51
- CustomWarn(`This is not an issue with the package. Using the original URL as fallback instead of uploading to CDN.
52
- Request timeout for ${url}.`, options.disableWarnings);
53
- return resolve(url);
54
- });
55
- request.end();
56
- });
57
- });
58
- }
59
- async function cdnRedirectType(url, options, contentType, cdnOptions) {
60
- let newUrl;
61
- switch (cdnOptions.provider) {
62
- case "CUSTOM": {
63
- try {
64
- newUrl = await cdnOptions.resolver(url, contentType, cdnOptions.customData);
65
- break;
66
- }
67
- catch (error) {
68
- CustomWarn(`Custom CDN resolver threw an error. Falling back to original URL.
69
- This is most likely an issue in the custom CDN implementation provided by the user.
70
- URL: ${url}
71
- Error: ${error?.message ?? error}`, options.disableWarnings);
72
- return url;
73
- }
74
- }
75
- case "CLOUDINARY": {
76
- newUrl = await cloudinaryResolver(url, options.fileName, cdnOptions.cloudName, cdnOptions.apiKey, cdnOptions.apiSecret, options.disableWarnings);
77
- break;
78
- }
79
- case "UPLOADCARE": {
80
- newUrl = await uploadCareResolver(url, cdnOptions.publicKey, cdnOptions.cdnDomain, options.disableWarnings);
81
- break;
82
- }
83
- }
84
- if (validateCdnUrl(newUrl, options.disableWarnings))
85
- return newUrl;
86
- return url;
87
- }
88
- function sleep(ms) {
89
- return new Promise(r => setTimeout(r, ms));
90
- }
91
- export async function uploadCareResolver(url, publicKey, cdnDomain, disableWarnings) {
92
- try {
93
- const form = new FormData();
94
- form.append("pub_key", publicKey);
95
- form.append("source_url", url);
96
- form.append("store", "1");
97
- form.append("check_URL_duplicates", "1");
98
- form.append("save_URL_duplicates", "1");
99
- const res = await fetch("https://upload.uploadcare.com/from_url/", {
100
- method: "POST",
101
- body: form,
102
- headers: {
103
- "User-Agent": "discord-message-transcript"
104
- }
105
- });
106
- if (!res.ok) {
107
- switch (res.status) {
108
- case 400:
109
- throw new Error(`Uploadcare initial request failed with status code ${res.status} - Request failed input parameters validation.`);
110
- case 403:
111
- throw new Error(`Uploadcare initial request failed with status code ${res.status} - Request was not allowed.`);
112
- case 429:
113
- throw new Error(`Uploadcare initial request failed with status code ${res.status} - Request was throttled.`);
114
- default:
115
- throw new Error(`Uploadcare initial request failed with status code ${res.status}`);
116
- }
117
- }
118
- const json = await res.json();
119
- if (json.uuid) {
120
- return `https://${cdnDomain}/${json.uuid}/`;
121
- }
122
- let delay = 200;
123
- let maxDelay = 2000;
124
- if (json.token) {
125
- for (let i = 0; i < 10; i++) {
126
- await sleep(delay);
127
- delay = Math.min(delay * 2, maxDelay);
128
- const resToken = await fetch(`https://upload.uploadcare.com/from_url/status/?token=${json.token}&pub_key=${publicKey}`, { headers: { "User-Agent": "discord-message-transcript" } });
129
- if (!resToken.ok)
130
- throw new Error(`Uploadcare status failed with status code ${resToken.status}`);
131
- const jsonToken = await resToken.json();
132
- if (jsonToken.status === "success" && jsonToken.file_id) {
133
- return `https://${cdnDomain}/${jsonToken.file_id}/`;
134
- }
135
- if (jsonToken.status === "error") {
136
- throw new Error(jsonToken.error || "Uploadcare failed");
137
- }
138
- }
139
- throw new Error("Uploadcare polling timeout");
140
- }
141
- return url;
142
- }
143
- catch (error) {
144
- CustomWarn(`Uploadcare CDN upload failed. Using original URL as fallback.
145
- Check Uploadcare public key, CDN domain, project settings, rate limits, and network access.
146
- URL: ${url}
147
- Error: ${error?.message ?? error}`, disableWarnings);
148
- return url;
149
- }
150
- }
151
- export async function cloudinaryResolver(url, fileName, cloudName, apiKey, apiSecret, disableWarnings) {
152
- try {
153
- const paramsToSign = {
154
- folder: `discord-message-transcript/${fileName}`,
155
- timestamp: Math.floor(Date.now() / 1000).toString(),
156
- unique_filename: "true",
157
- use_filename: "true",
158
- };
159
- const stringToSign = Object.keys(paramsToSign).sort().map(k => `${k}=${paramsToSign[k]}`).join("&");
160
- // signature SHA256
161
- const signature = crypto
162
- .createHash("sha256")
163
- .update(stringToSign + apiSecret)
164
- .digest("hex");
165
- const form = new FormData();
166
- form.append("folder", paramsToSign.folder);
167
- form.append("file", url);
168
- form.append("api_key", apiKey);
169
- form.append("timestamp", paramsToSign.timestamp);
170
- form.append("signature", signature);
171
- form.append("use_filename", paramsToSign.use_filename);
172
- form.append("unique_filename", paramsToSign.unique_filename);
173
- const res = await fetch(`https://api.cloudinary.com/v1_1/${cloudName}/auto/upload`, {
174
- method: "POST",
175
- body: form,
176
- headers: {
177
- "User-Agent": "discord-message-transcript"
178
- }
179
- });
180
- if (!res.ok) {
181
- switch (res.status) {
182
- case 400:
183
- throw new Error(`Cloudinary upload failed with status code ${res.status} - Bad request / invalid params.`);
184
- case 403:
185
- throw new Error(`Cloudinary upload failed with status code ${res.status} - Invalid credentials or unauthorized.`);
186
- case 429:
187
- throw new Error(`Cloudinary upload failed with status code ${res.status} - Rate limited.`);
188
- default:
189
- throw new Error(`Cloudinary upload failed with status code ${res.status}.`);
190
- }
191
- }
192
- const json = await res.json();
193
- if (!json.secure_url) {
194
- throw new Error("Cloudinary response missing secure_url");
195
- }
196
- return json.secure_url;
197
- }
198
- catch (error) {
199
- CustomWarn(`Failed to upload asset to Cloudinary CDN. Using original URL as fallback.
200
- Check Cloudinary configuration (cloud name, API key, API secret) and network access.
201
- URL: ${url}
202
- Error: ${error?.message ?? error}`, disableWarnings);
203
- return url;
204
- }
205
- }
206
- // Note: for debug use ${JSON.stringify(await res.json())} to understand the error
207
- function validateCdnUrl(url, disableWarnings) {
208
- if (url.includes('"') || url.includes('<') || url.includes('>')) {
209
- CustomWarn(`Unsafe URL received from CDN, using fallback.\nURL: ${url}`, disableWarnings);
210
- return false;
211
- }
212
- return true;
213
- }
@@ -1,4 +0,0 @@
1
- import { JsonAttachment, TranscriptOptionsBase } from "discord-message-transcript-base";
2
- import { safeUrlReturn } from "@/types";
3
- export declare function resolveImageURL(url: string, options: TranscriptOptionsBase, canReturnNull: false, attachments?: JsonAttachment[]): Promise<safeUrlReturn>;
4
- export declare function resolveImageURL(url: string | null, options: TranscriptOptionsBase, canReturnNull: true, attachments?: JsonAttachment[]): Promise<safeUrlReturn | null>;
@@ -1,5 +0,0 @@
1
- import { JsonAuthor, JsonMessage, TranscriptOptionsBase } from "discord-message-transcript-base";
2
- import { CDNOptions, safeUrlReturn } from "@/types";
3
- export declare function urlResolver(safeUrlObject: safeUrlReturn, options: TranscriptOptionsBase, cdnOptions: CDNOptions | null, urlCache: Map<string, Promise<string>>): Promise<string>;
4
- export declare function messagesUrlResolver(messages: JsonMessage[], options: TranscriptOptionsBase, cdnOptions: CDNOptions | null, urlCache: Map<string, Promise<string>>): Promise<JsonMessage[]>;
5
- export declare function authorUrlResolver(authors: Map<string, JsonAuthor>, options: TranscriptOptionsBase, cdnOptions: CDNOptions | null, urlCache: Map<string, Promise<string>>): Promise<JsonAuthor[]>;