erudit 4.3.1 → 4.3.3-dev.1

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/app/app.vue +1 -0
  2. package/app/components/aside/major/PaneHolder.vue +3 -3
  3. package/app/components/aside/major/contentNav/items/Flags.vue +4 -8
  4. package/app/components/main/MainBreadcrumbs.vue +27 -19
  5. package/app/components/main/MainKeyLinks.vue +13 -7
  6. package/app/components/main/MainSubTitle.vue +4 -3
  7. package/app/components/main/MainTopicPartPage.vue +3 -1
  8. package/app/components/main/connections/MainConnections.vue +47 -40
  9. package/app/components/main/contentStats/MainContentStats.vue +16 -17
  10. package/app/composables/analytics.ts +15 -8
  11. package/app/composables/favicon.ts +63 -16
  12. package/app/composables/formatText.ts +9 -9
  13. package/app/composables/jsonLd.ts +123 -0
  14. package/app/composables/lastmod.ts +6 -0
  15. package/app/composables/og.ts +23 -0
  16. package/app/pages/book/[...bookId].vue +3 -1
  17. package/app/pages/group/[...groupId].vue +3 -1
  18. package/app/pages/page/[...pageId].vue +3 -1
  19. package/app/plugins/prerender.server.ts +1 -0
  20. package/modules/erudit/setup/runtimeConfig.ts +39 -3
  21. package/nuxt.config.ts +1 -1
  22. package/package.json +12 -11
  23. package/server/api/main/content/[...contentTypePath].ts +2 -0
  24. package/server/api/prerender/favicons.ts +31 -0
  25. package/server/erudit/build.ts +2 -0
  26. package/server/erudit/content/lastmod.ts +206 -0
  27. package/server/erudit/content/repository/lastmod.ts +12 -0
  28. package/server/erudit/db/schema/content.ts +1 -0
  29. package/server/erudit/favicon/convertToPng.ts +48 -0
  30. package/server/erudit/favicon/loadSource.ts +139 -0
  31. package/server/erudit/favicon/shared.ts +48 -0
  32. package/server/erudit/language/list/en.ts +1 -9
  33. package/server/erudit/language/list/ru.ts +3 -11
  34. package/server/erudit/repository.ts +2 -0
  35. package/server/routes/favicon/[...path].ts +89 -0
  36. package/server/routes/sitemap.xml.ts +19 -10
  37. package/shared/types/language.ts +1 -6
  38. package/shared/types/mainContent.ts +1 -0
  39. package/shared/types/runtimeConfig.ts +4 -1
  40. package/app/composables/lastChanged.ts +0 -61
@@ -1,6 +1,8 @@
1
1
  import type { ContentSeo } from '@erudit-js/core/content/seo';
2
2
  import { toSeoSnippet } from '@erudit-js/prose';
3
3
 
4
+ import type { Breadcrumbs } from '../../shared/types/breadcrumbs';
5
+
4
6
  export function initOgSiteName() {
5
7
  const siteTitle =
6
8
  ERUDIT.config.seo?.siteTitle || ERUDIT.config.asideMajor?.siteInfo?.title;
@@ -91,6 +93,8 @@ export async function useContentSeo(args: {
91
93
  description?: string;
92
94
  seo?: ContentSeo;
93
95
  snippets?: ElementSnippet[];
96
+ breadcrumbs?: Breadcrumbs;
97
+ lastmod?: string;
94
98
  }) {
95
99
  const canUseBookTitle = ERUDIT.config.seo?.useBookSiteTitle;
96
100
 
@@ -142,6 +146,25 @@ export async function useContentSeo(args: {
142
146
  });
143
147
  }
144
148
 
149
+ //
150
+ // JSON-LD structured data
151
+ //
152
+
153
+ useContentBreadcrumbsJsonLd(args.breadcrumbs);
154
+
155
+ useContentArticleJsonLd({
156
+ title: args.seo?.title || args.title,
157
+ description: args.seo?.description || args.description,
158
+ urlPath: canonicalPath,
159
+ contentType:
160
+ args.contentTypePath.type === 'topic'
161
+ ? 'article'
162
+ : args.contentTypePath.type,
163
+ lastmod: args.lastmod,
164
+ keyElements: args.snippets?.filter((snippet) => !!snippet.key),
165
+ breadcrumbs: args.breadcrumbs,
166
+ });
167
+
145
168
  //
146
169
  // SEO snippets
147
170
  //
@@ -19,7 +19,7 @@ if (ERUDIT.config.contributors?.enabled) {
19
19
  }
20
20
 
21
21
  const phrase = await usePhrases('begin_learning');
22
- const lastChangedDate = useLastChanged(() => mainContent.contentRelativePath);
22
+ const lastChangedDate = useLastChanged(() => mainContent.lastmod);
23
23
 
24
24
  await useContentSeo({
25
25
  title: mainContent.title,
@@ -29,6 +29,8 @@ await useContentSeo({
29
29
  contentId: mainContent.shortId,
30
30
  },
31
31
  seo: mainContent.seo,
32
+ breadcrumbs: mainContent.breadcrumbs,
33
+ lastmod: mainContent.lastmod,
32
34
  });
33
35
  </script>
34
36
 
@@ -19,7 +19,7 @@ if (ERUDIT.config.contributors?.enabled) {
19
19
  }
20
20
 
21
21
  const phrase = await usePhrases('group', 'begin_learning');
22
- const lastChangedDate = useLastChanged(() => mainContent.contentRelativePath);
22
+ const lastChangedDate = useLastChanged(() => mainContent.lastmod);
23
23
 
24
24
  await useContentSeo({
25
25
  title: mainContent.title,
@@ -31,6 +31,8 @@ await useContentSeo({
31
31
  contentId: mainContent.shortId,
32
32
  },
33
33
  seo: mainContent.seo,
34
+ breadcrumbs: mainContent.breadcrumbs,
35
+ lastmod: mainContent.lastmod,
34
36
  });
35
37
  </script>
36
38
 
@@ -17,7 +17,7 @@ async function proseMounted() {
17
17
  );
18
18
  }
19
19
 
20
- const lastChangedDate = useLastChanged(() => mainContent.contentRelativePath);
20
+ const lastChangedDate = useLastChanged(() => mainContent.lastmod);
21
21
 
22
22
  await useContentSeo({
23
23
  title: mainContent.title,
@@ -29,6 +29,8 @@ await useContentSeo({
29
29
  },
30
30
  seo: mainContent.seo,
31
31
  snippets: mainContent.snippets,
32
+ breadcrumbs: mainContent.breadcrumbs,
33
+ lastmod: mainContent.lastmod,
32
34
  });
33
35
  </script>
34
36
 
@@ -26,6 +26,7 @@ export default defineNuxtPlugin({
26
26
  '/api/prerender/quotes',
27
27
  '/api/prerender/news',
28
28
  '/api/prerender/ogImages',
29
+ '/api/prerender/favicons',
29
30
  ];
30
31
 
31
32
  for (const provider of routeProviders) {
@@ -1,6 +1,7 @@
1
1
  import { existsSync } from 'node:fs';
2
2
  import type { Nuxt } from '@nuxt/schema';
3
3
  import { sn } from 'unslash';
4
+ import { findPath } from 'nuxt/kit';
4
5
  import type { EruditConfig } from '@erudit-js/core/eruditConfig/config';
5
6
  import { isDevLikeMode } from '@erudit-js/core/mode';
6
7
 
@@ -31,6 +32,7 @@ export async function setupEruditRuntimeConfig(nuxt: Nuxt) {
31
32
  elements: eruditConfig.elements || [],
32
33
  countElements: eruditConfig.countElements || [],
33
34
  indexPage: eruditConfig.indexPage,
35
+ lastmod: await resolveLastmodConfig(eruditConfig),
34
36
  }) satisfies EruditRuntimeConfig;
35
37
 
36
38
  //
@@ -46,9 +48,6 @@ export async function setupEruditRuntimeConfig(nuxt: Nuxt) {
46
48
  repository:
47
49
  eruditConfig.debug?.fakeApi?.repository ??
48
50
  (nuxt.options.dev || isDevLikeMode(ERUDIT_MODE)),
49
- lastChanged:
50
- eruditConfig.debug?.fakeApi?.lastChanged ??
51
- (nuxt.options.dev || isDevLikeMode(ERUDIT_MODE)),
52
51
  },
53
52
  analytics: eruditConfig.debug?.analytics,
54
53
  },
@@ -106,3 +105,40 @@ export async function setupEruditRuntimeConfig(nuxt: Nuxt) {
106
105
  nuxtAugmentations: eruditConfig.nuxtAugmentations,
107
106
  };
108
107
  }
108
+
109
+ async function resolveLastmodConfig(
110
+ eruditConfig: EruditConfig,
111
+ ): Promise<EruditRuntimeConfig['lastmod']> {
112
+ const lastmod = eruditConfig.lastmod;
113
+
114
+ if (!lastmod || lastmod.enabled === false) {
115
+ return undefined;
116
+ }
117
+
118
+ if (lastmod.type === 'git') {
119
+ return { type: 'git' };
120
+ }
121
+
122
+ if (lastmod.type === 'custom') {
123
+ if (!lastmod.scriptPath) {
124
+ throw new Error(
125
+ 'Lastmod config with type "custom" requires a "scriptPath"!',
126
+ );
127
+ }
128
+
129
+ const absPath = await findPath(lastmod.scriptPath, {
130
+ cwd: PROJECT_PATH,
131
+ extensions: ['.ts', '.js'],
132
+ });
133
+
134
+ if (!absPath) {
135
+ throw new Error(
136
+ `Failed to resolve lastmod provider path "${lastmod.scriptPath}"!`,
137
+ );
138
+ }
139
+
140
+ return { type: 'custom', scriptPath: absPath };
141
+ }
142
+
143
+ return undefined;
144
+ }
package/nuxt.config.ts CHANGED
@@ -53,7 +53,7 @@ export default defineNuxtConfig({
53
53
  rollupConfig: {
54
54
  // Prevent inlining some packages
55
55
  external(source) {
56
- const ignore = ['jiti', 'tsprose', '@resvg/resvg-js'];
56
+ const ignore = ['jiti', 'tsprose', '@resvg/resvg-js', 'sharp'];
57
57
 
58
58
  for (const ignoreItem of ignore) {
59
59
  if (source.includes(ignoreItem)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "erudit",
3
- "version": "4.3.1",
3
+ "version": "4.3.3-dev.1",
4
4
  "type": "module",
5
5
  "description": "🤓 CMS for perfect educational sites.",
6
6
  "license": "MIT",
@@ -24,32 +24,33 @@
24
24
  }
25
25
  },
26
26
  "dependencies": {
27
- "@erudit-js/cli": "4.3.1",
28
- "@erudit-js/core": "4.3.1",
29
- "@erudit-js/prose": "4.3.1",
30
- "unslash": "^2.0.0",
27
+ "@erudit-js/cli": "4.3.3-dev.1",
28
+ "@erudit-js/core": "4.3.3-dev.1",
29
+ "@erudit-js/prose": "4.3.3-dev.1",
31
30
  "@floating-ui/vue": "^1.1.11",
32
- "tsprose": "^1.0.1",
31
+ "@resvg/resvg-js": "^2.6.2",
33
32
  "@tailwindcss/vite": "^4.2.1",
34
33
  "better-sqlite3": "^12.8.0",
35
34
  "chokidar": "^5.0.0",
36
35
  "consola": "^3.4.2",
37
- "drizzle-kit": "^0.31.9",
36
+ "drizzle-kit": "^0.31.10",
38
37
  "drizzle-orm": "^0.45.1",
39
38
  "esbuild": "^0.27.4",
40
39
  "flexsearch": "^0.8.212",
41
40
  "glob": "^13.0.6",
42
41
  "image-size": "^2.0.2",
43
- "@resvg/resvg-js": "^2.6.2",
44
- "satori": "^0.25.0",
45
42
  "jiti": "^2.6.1",
46
43
  "nuxt": "4.4.2",
47
44
  "nuxt-my-icons": "1.2.2",
48
45
  "perfect-debounce": "^2.1.0",
46
+ "satori": "^0.26.0",
47
+ "sharp": "^0.34.5",
49
48
  "tailwindcss": "^4.2.1",
49
+ "ts-xor": "^1.3.0",
50
+ "tsprose": "^1.0.1",
51
+ "unslash": "^2.0.0",
50
52
  "vue": "latest",
51
- "vue-router": "latest",
52
- "ts-xor": "^1.3.0"
53
+ "vue-router": "latest"
53
54
  },
54
55
  "devDependencies": {
55
56
  "@types/better-sqlite3": "^7.6.13"
@@ -20,6 +20,7 @@ export default defineEventHandler<Promise<MainContent>>(async (event) => {
20
20
  ['topic', 'page'].includes(contentTypePath.type),
21
21
  );
22
22
  const seo = await ERUDIT.repository.content.seo(fullId);
23
+ const lastmod = await ERUDIT.repository.content.lastmod(fullId);
23
24
 
24
25
  const bookNode = ERUDIT.contentNav.getBookFor(fullId);
25
26
  const bookTitle = bookNode
@@ -37,6 +38,7 @@ export default defineEventHandler<Promise<MainContent>>(async (event) => {
37
38
  bookTitle,
38
39
  breadcrumbs: await ERUDIT.repository.content.breadcrumbs(fullId),
39
40
  seo,
41
+ lastmod,
40
42
  };
41
43
 
42
44
  if (description) {
@@ -0,0 +1,31 @@
1
+ import { loadFaviconSource } from '#layers/erudit/server/erudit/favicon/loadSource';
2
+ import {
3
+ FAVICON_KEYS,
4
+ FAVICON_SIZES,
5
+ getFaviconHref,
6
+ extFromHref,
7
+ } from '#layers/erudit/server/erudit/favicon/shared';
8
+
9
+ export default defineEventHandler(async () => {
10
+ const routes: string[] = [];
11
+
12
+ for (const key of FAVICON_KEYS) {
13
+ const href = getFaviconHref(key);
14
+ if (!href) continue;
15
+
16
+ const source = await loadFaviconSource(href);
17
+ if (!source) continue;
18
+
19
+ const ext = extFromHref(href);
20
+ if (ext) {
21
+ routes.push(`/favicon/${key}/source${ext}`);
22
+ }
23
+
24
+ for (const size of FAVICON_SIZES) {
25
+ if (source.width !== undefined && source.width < size) continue;
26
+ routes.push(`/favicon/${key}/${size}.png`);
27
+ }
28
+ }
29
+
30
+ return routes;
31
+ });
@@ -9,6 +9,7 @@ import { buildSponsors } from './sponsors/build';
9
9
  import { buildCameos } from './cameos/build';
10
10
  import { buildContentNav } from './content/nav/build';
11
11
  import { requestFullContentResolve, resolveContent } from './content/resolve';
12
+ import { buildContentLastmod } from './content/lastmod';
12
13
  import { buildGlobalContent } from './content/global/build';
13
14
  import { buildNews } from './news/build';
14
15
  import { triggerReload } from './reloadSignal';
@@ -29,6 +30,7 @@ export async function buildServerErudit() {
29
30
  await buildContentNav();
30
31
  await buildGlobalContent();
31
32
  await resolveContent();
33
+ await buildContentLastmod();
32
34
  ERUDIT.log.success(styleText('green', 'Build Complete!'));
33
35
  } catch (buildError) {
34
36
  requestFullContentResolve();
@@ -0,0 +1,206 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { eq } from 'drizzle-orm';
3
+ import type { LastmodProvider } from '@erudit-js/core/eruditConfig/lastmod';
4
+
5
+ export async function buildContentLastmod() {
6
+ const lastmodConfig = ERUDIT.config.lastmod;
7
+
8
+ if (!lastmodConfig) {
9
+ return;
10
+ }
11
+
12
+ ERUDIT.log.debug.start('Collecting lastmod dates...');
13
+
14
+ let collected = false;
15
+
16
+ if (lastmodConfig.type === 'git') {
17
+ collected = await collectGitLastmod();
18
+ } else if (lastmodConfig.type === 'custom' && lastmodConfig.scriptPath) {
19
+ collected = await collectCustomLastmod(lastmodConfig.scriptPath);
20
+ }
21
+
22
+ if (collected) {
23
+ ERUDIT.log.success('Lastmod dates collected!');
24
+ }
25
+ }
26
+
27
+ function getGitContentPrefix(): string | undefined {
28
+ const projectRoot = ERUDIT.paths.project();
29
+
30
+ const result = spawnSync('git', ['rev-parse', '--show-prefix'], {
31
+ cwd: projectRoot,
32
+ encoding: 'utf-8',
33
+ });
34
+
35
+ if (result.status !== 0) return undefined;
36
+
37
+ // gitPrefix is e.g. "playground/" or "" (if project is at repo root)
38
+ return result.stdout.trim() + 'content/';
39
+ }
40
+
41
+ async function collectGitLastmod(): Promise<boolean> {
42
+ const projectRoot = ERUDIT.paths.project();
43
+ const contentPrefix = getGitContentPrefix();
44
+
45
+ if (!contentPrefix) {
46
+ ERUDIT.log.warn(
47
+ 'Failed to detect git prefix — lastmod dates will be unavailable. ' +
48
+ 'Is this a git repository?',
49
+ );
50
+ return false;
51
+ }
52
+
53
+ const result = spawnSync(
54
+ 'git',
55
+ ['log', '--format=format:%cI', '--name-only', '--', contentPrefix],
56
+ {
57
+ cwd: projectRoot,
58
+ encoding: 'utf-8',
59
+ maxBuffer: 50 * 1024 * 1024,
60
+ },
61
+ );
62
+
63
+ if (result.status !== 0) {
64
+ ERUDIT.log.warn(
65
+ 'Failed to run git log — lastmod dates will be unavailable. ' +
66
+ 'Is this a git repository?',
67
+ );
68
+ return false;
69
+ }
70
+
71
+ const stdout = result.stdout;
72
+
73
+ if (!stdout.trim()) {
74
+ return false;
75
+ }
76
+
77
+ // Parse git log output: blocks separated by double newlines
78
+ // Each block: first line = ISO date, remaining lines = file paths
79
+ const dateMap = new Map<string, string>();
80
+ const blocks = stdout.split('\n\n');
81
+
82
+ for (const block of blocks) {
83
+ const lines = block.split('\n').filter(Boolean);
84
+ if (lines.length < 2) continue;
85
+
86
+ const date = lines[0]!;
87
+ for (let i = 1; i < lines.length; i++) {
88
+ const filePath = lines[i]!;
89
+ if (!filePath.startsWith(contentPrefix)) continue;
90
+
91
+ // Strip the prefix to get the content-relative path
92
+ // e.g. "playground/content/1-test/page.tsx" → "1-test"
93
+ const relPath = filePath.slice(contentPrefix.length);
94
+ const lastSlash = relPath.lastIndexOf('/');
95
+ const contentRelPath =
96
+ lastSlash > 0 ? relPath.slice(0, lastSlash) : relPath;
97
+
98
+ // Keep only the first (most recent) date per path
99
+ if (!dateMap.has(contentRelPath)) {
100
+ dateMap.set(contentRelPath, date);
101
+ }
102
+ }
103
+ }
104
+
105
+ // Detect shallow clone: if all dates are identical, warn
106
+ if (dateMap.size > 1) {
107
+ const dates = new Set(dateMap.values());
108
+ if (dates.size === 1) {
109
+ ERUDIT.log.warn(
110
+ 'All git lastmod dates are identical — this likely means a shallow clone. ' +
111
+ 'Use "fetch-depth: 0" in GitHub Actions checkout for accurate dates.',
112
+ );
113
+ }
114
+ }
115
+
116
+ // Build a map keyed by fullId from the contentRelPath-keyed dateMap
117
+ const ownDates = new Map<string, string>();
118
+ for (const [, navNode] of ERUDIT.contentNav.id2Node) {
119
+ const date = dateMap.get(navNode.contentRelPath);
120
+ if (date) {
121
+ ownDates.set(navNode.fullId, date);
122
+ }
123
+ }
124
+
125
+ await propagateAndSave(ownDates);
126
+ return true;
127
+ }
128
+
129
+ async function collectCustomLastmod(absPath: string): Promise<boolean> {
130
+ let provider: LastmodProvider;
131
+
132
+ try {
133
+ const module = await ERUDIT.import(absPath);
134
+ provider = (module as any).default;
135
+ } catch (error) {
136
+ ERUDIT.log.warn(
137
+ `Failed to import lastmod provider from "${absPath}":\n${error}`,
138
+ );
139
+ return false;
140
+ }
141
+
142
+ if (typeof provider !== 'function') {
143
+ ERUDIT.log.warn(
144
+ `Lastmod provider at "${absPath}" does not have a default-exported function!`,
145
+ );
146
+ return false;
147
+ }
148
+
149
+ // Collect dates from custom provider
150
+ const customDates = new Map<string, string>();
151
+
152
+ for (const [, navNode] of ERUDIT.contentNav.id2Node) {
153
+ try {
154
+ const date = await provider({
155
+ fullId: navNode.fullId,
156
+ mode: ERUDIT.mode,
157
+ projectPath: ERUDIT.paths.project(),
158
+ });
159
+ if (date instanceof Date && !isNaN(date.getTime())) {
160
+ customDates.set(navNode.fullId, date.toISOString());
161
+ }
162
+ } catch (error) {
163
+ ERUDIT.log.warn(
164
+ `Lastmod provider error for "${navNode.fullId}": ${error}`,
165
+ );
166
+ }
167
+ }
168
+
169
+ await propagateAndSave(customDates);
170
+ return true;
171
+ }
172
+
173
+ /**
174
+ * Propagate dates upward through the nav tree (parents inherit the most
175
+ * recent date from their children) and write resolved dates to the DB.
176
+ */
177
+ async function propagateAndSave(ownDates: Map<string, string>) {
178
+ // Process deepest nodes first so child dates are finalized before parents
179
+ const sortedNodes = Array.from(ERUDIT.contentNav.id2Node.values()).sort(
180
+ (a, b) => b.fullId.split('/').length - a.fullId.split('/').length,
181
+ );
182
+
183
+ const resolvedDates = new Map<string, string>();
184
+
185
+ for (const navNode of sortedNodes) {
186
+ let bestDate = ownDates.get(navNode.fullId);
187
+
188
+ for (const child of navNode.children ?? []) {
189
+ const childDate = resolvedDates.get(child.fullId);
190
+ if (childDate && (!bestDate || childDate > bestDate)) {
191
+ bestDate = childDate;
192
+ }
193
+ }
194
+
195
+ if (bestDate) {
196
+ resolvedDates.set(navNode.fullId, bestDate);
197
+ }
198
+ }
199
+
200
+ for (const [fullId, date] of resolvedDates) {
201
+ await ERUDIT.db
202
+ .update(ERUDIT.db.schema.content)
203
+ .set({ lastmod: date })
204
+ .where(eq(ERUDIT.db.schema.content.fullId, fullId));
205
+ }
206
+ }
@@ -0,0 +1,12 @@
1
+ import { eq } from 'drizzle-orm';
2
+
3
+ export async function getContentLastmod(
4
+ fullId: string,
5
+ ): Promise<string | undefined> {
6
+ const result = await ERUDIT.db.query.content.findFirst({
7
+ columns: { lastmod: true },
8
+ where: eq(ERUDIT.db.schema.content.fullId, fullId),
9
+ });
10
+
11
+ return result?.lastmod ?? undefined;
12
+ }
@@ -15,4 +15,5 @@ export const content = sqliteTable('content', {
15
15
  decorationExtension: text(),
16
16
  externals: text({ mode: 'json' }).$type<ContentExternalItem[]>(),
17
17
  seo: text({ mode: 'json' }).$type<ContentSeo>(),
18
+ lastmod: text(),
18
19
  });
@@ -0,0 +1,48 @@
1
+ import sharp from 'sharp';
2
+ import { Resvg } from '@resvg/resvg-js';
3
+ import type { FaviconSource } from './loadSource';
4
+
5
+ const cache = new Map<string, Buffer>();
6
+
7
+ export async function convertFaviconToPng(
8
+ faviconKey: string,
9
+ source: FaviconSource,
10
+ size: number,
11
+ ): Promise<Buffer> {
12
+ const cacheKey = `${faviconKey}:${size}`;
13
+ const cached = cache.get(cacheKey);
14
+ if (cached) return cached;
15
+
16
+ const png =
17
+ source.mime === 'image/svg+xml'
18
+ ? await svgToPng(source.buffer, size)
19
+ : await rasterToPng(source.buffer, size);
20
+
21
+ cache.set(cacheKey, png);
22
+ return png;
23
+ }
24
+
25
+ async function svgToPng(svgBuffer: Buffer, size: number): Promise<Buffer> {
26
+ const resvg = new Resvg(svgBuffer.toString('utf-8'), {
27
+ fitTo: { mode: 'width', value: size },
28
+ });
29
+ const rendered = Buffer.from(resvg.render().asPng());
30
+
31
+ return sharp(rendered)
32
+ .resize(size, size, {
33
+ fit: 'contain',
34
+ background: { r: 0, g: 0, b: 0, alpha: 0 },
35
+ })
36
+ .png()
37
+ .toBuffer();
38
+ }
39
+
40
+ async function rasterToPng(buffer: Buffer, size: number): Promise<Buffer> {
41
+ return sharp(buffer)
42
+ .resize(size, size, {
43
+ fit: 'contain',
44
+ background: { r: 0, g: 0, b: 0, alpha: 0 },
45
+ })
46
+ .png()
47
+ .toBuffer();
48
+ }