rehype-og-card 1.1.1 → 2.0.0

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.
package/README.md CHANGED
@@ -115,6 +115,14 @@ Path to save the build cache. For Astro projects, specify the `./node_modules/.a
115
115
  - Type: `string`
116
116
  - Default: `"./.cache/og-card"`
117
117
 
118
+ ### `buildCacheMaxAge`
119
+
120
+ Cache expiration time for build cache in milliseconds. Set to `false` to disable expiration.
121
+ Expiration is calculated using the cached timestamp stored in the cache itself.
122
+
123
+ - Type: `number | false`
124
+ - Default: `2592000000` (30 days)
125
+
118
126
  ### `crawlerUserAgent`
119
127
 
120
128
  User agent to use for fetching the OG metadata and images.
@@ -171,6 +179,14 @@ Path to save the server cache. Specify the directory whose contents will be copi
171
179
  - Type: `string`
172
180
  - Default: `"./public"`
173
181
 
182
+ ### `serverCacheMaxAge`
183
+
184
+ Cache expiration time for server cache in milliseconds. Set to `false` to disable expiration.
185
+ Expiration is calculated using the cached timestamp stored in the cache itself.
186
+
187
+ - Type: `number | false`
188
+ - Default: `2592000000` (30 days)
189
+
174
190
  ### `shortenURL`
175
191
 
176
192
  Whether to shorten the displayed URL.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rehype-og-card",
3
- "version": "1.1.1",
3
+ "version": "2.0.0",
4
4
  "description": "Rehype plugin to convert text links to link cards",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -43,8 +43,8 @@
43
43
  "@changesets/changelog-github": "^0.5.0",
44
44
  "@changesets/cli": "^2.27.7",
45
45
  "@robot-inventor/eslint-config": "^11.0.0",
46
- "@robot-inventor/tsconfig-base": "^6.0.0",
47
- "@types/node": "^24.2.1",
46
+ "@robot-inventor/tsconfig-base": "^7.0.0",
47
+ "@types/node": "^25.0.2",
48
48
  "eslint": "^9.7.0",
49
49
  "hast-util-to-html": "^9.0.1",
50
50
  "prettier": "^3.3.3",
@@ -57,6 +57,7 @@
57
57
  },
58
58
  "dependencies": {
59
59
  "@types/hast": "^3.0.4",
60
+ "arktype": "^2.1.29",
60
61
  "hast-util-is-element": "^3.0.0",
61
62
  "hastscript": "^9.0.0",
62
63
  "node-fetch": "^3.3.2",
package/dist/index.d.ts DELETED
@@ -1,11 +0,0 @@
1
- import type { Plugin } from "unified";
2
- import type { RehypeOGCardOptions } from "./types.js";
3
- import type { Root } from "hast";
4
- /**
5
- * Rehype plugin to create OG card from bare links.
6
- * @param options Plugin options.
7
- * @returns Transformer function.
8
- */
9
- declare const rehypeOGCard: Plugin<[RehypeOGCardOptions | undefined], Root>;
10
- export default rehypeOGCard;
11
- export type { RehypeOGCardOptions };
package/dist/index.js DELETED
@@ -1,152 +0,0 @@
1
- import { convertTextToAnchorElement, createOGCard, isAnchorElement, isTextNode } from "./util/hast.js";
2
- import { checkFileExistsSync, createDirectorySync } from "./util/file.js";
3
- import { downloadImage, getOGData, isValidURL } from "./util/network.js";
4
- import { restoreBuildCache, restoreOGDataBuildCache, saveBuildCacheFile, saveOGDataBuildCache } from "./util/cache.js";
5
- import { isElement } from "hast-util-is-element";
6
- import path from "path";
7
- import { visitParents } from "unist-util-visit-parents";
8
- const DEFAULT_OPTIONS = {
9
- buildCache: false,
10
- buildCachePath: "./node_modules/.cache",
11
- crawlerUserAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
12
- decoding: "async",
13
- enableSameTextURLConversion: false,
14
- excludeDomains: [],
15
- loading: "lazy",
16
- openInNewTab: false,
17
- serverCache: true,
18
- serverCachePath: "./public",
19
- shortenURL: true
20
- };
21
- /**
22
- * Rehype plugin to create OG card from bare links.
23
- * @param options Plugin options.
24
- * @returns Transformer function.
25
- */
26
- // eslint-disable-next-line max-lines-per-function, max-statements
27
- const rehypeOGCard = (options) => {
28
- const mergedOptions = {
29
- ...DEFAULT_OPTIONS,
30
- ...options
31
- };
32
- if (mergedOptions.buildCache && !mergedOptions.serverCache) {
33
- throw new Error("[rehype-og-card] `buildCache` option requires `serverCache` option to be enabled.");
34
- }
35
- mergedOptions.serverCachePath = path.posix.join(mergedOptions.serverCachePath, "./rehype-og-card/");
36
- mergedOptions.buildCachePath = path.posix.join(mergedOptions.buildCachePath, "./rehype-og-card/");
37
- const buildCacheExists = checkFileExistsSync(mergedOptions.buildCachePath);
38
- if (mergedOptions.buildCache) {
39
- if (buildCacheExists) {
40
- restoreBuildCache(mergedOptions.buildCachePath, mergedOptions.serverCachePath);
41
- }
42
- else {
43
- createDirectorySync(mergedOptions.buildCachePath);
44
- }
45
- }
46
- /**
47
- * Transform function to create OG card from bare links.
48
- * @param tree Root node of the HAST tree.
49
- */
50
- // eslint-disable-next-line max-lines-per-function
51
- const transform = async (tree) => {
52
- const linkCardPromises = [];
53
- // eslint-disable-next-line max-statements, max-lines-per-function
54
- visitParents(tree, ["element", "text"], (node, ancestors) => {
55
- let anchorNode = null;
56
- const isBareLink = node.type === "text" && isValidURL(node.value.trim());
57
- const isValidAnchor = isAnchorElement(node) && isValidURL(node.properties.href);
58
- if (isBareLink) {
59
- anchorNode = convertTextToAnchorElement(node);
60
- }
61
- else if (mergedOptions.enableSameTextURLConversion && isValidAnchor) {
62
- const isSameTextURL =
63
- // eslint-disable-next-line no-magic-numbers
64
- node.children.length === 1 &&
65
- node.children[0] &&
66
- isTextNode(node.children[0]) &&
67
- node.children[0].value.trim() === node.properties.href;
68
- if (!isSameTextURL)
69
- return;
70
- anchorNode = node;
71
- }
72
- else {
73
- return;
74
- }
75
- // eslint-disable-next-line no-magic-numbers
76
- const parent = ancestors[ancestors.length - 1];
77
- if (!parent)
78
- return;
79
- if (!isElement(parent, "p"))
80
- return;
81
- const shouldSkip = ancestors.some((ancestor) => isElement(ancestor) && ["ul", "ol"].includes(ancestor.tagName));
82
- if (shouldSkip)
83
- return;
84
- // eslint-disable-next-line no-magic-numbers
85
- const isTheOnlyChild = parent.children.length === 1;
86
- if (!isTheOnlyChild)
87
- return;
88
- const targetURL = new URL(anchorNode.properties.href);
89
- if (mergedOptions.excludeDomains.includes(targetURL.hostname))
90
- return;
91
- // eslint-disable-next-line jsdoc/require-jsdoc, max-statements, max-lines-per-function
92
- const linkCardPromise = async () => {
93
- let OGData = mergedOptions.buildCache
94
- ? await restoreOGDataBuildCache(anchorNode.properties.href, mergedOptions.buildCachePath)
95
- : null;
96
- if (!OGData) {
97
- OGData = await getOGData(anchorNode.properties.href, mergedOptions.crawlerUserAgent);
98
- if (!OGData)
99
- return;
100
- if (mergedOptions.buildCache) {
101
- void saveOGDataBuildCache(anchorNode.properties.href, OGData, mergedOptions.buildCachePath);
102
- }
103
- }
104
- if (OGData.OGImageURL && mergedOptions.serverCache) {
105
- const filename = await downloadImage({
106
- directory: mergedOptions.serverCachePath,
107
- url: OGData.OGImageURL,
108
- userAgent: mergedOptions.crawlerUserAgent
109
- });
110
- if (filename) {
111
- OGData.OGImageURL = path.posix.join("/rehype-og-card", filename);
112
- }
113
- if (filename && mergedOptions.buildCache) {
114
- const downloadedFilePath = path.join(mergedOptions.serverCachePath, filename);
115
- const buildCachePath = path.join(mergedOptions.buildCachePath, filename);
116
- void saveBuildCacheFile(downloadedFilePath, buildCachePath);
117
- }
118
- }
119
- if (OGData.faviconURL && mergedOptions.serverCache) {
120
- const filename = await downloadImage({
121
- directory: mergedOptions.serverCachePath,
122
- url: OGData.faviconURL,
123
- userAgent: mergedOptions.crawlerUserAgent
124
- });
125
- if (filename) {
126
- OGData.faviconURL = path.posix.join("/rehype-og-card", filename);
127
- }
128
- if (filename && mergedOptions.buildCache) {
129
- const downloadedFilePath = path.join(mergedOptions.serverCachePath, filename);
130
- const buildCachePath = path.join(mergedOptions.buildCachePath, filename);
131
- void saveBuildCacheFile(downloadedFilePath, buildCachePath);
132
- }
133
- }
134
- if (mergedOptions.shortenURL) {
135
- const shortenedURL = new URL(anchorNode.properties.href);
136
- OGData.displayURL = shortenedURL.hostname;
137
- }
138
- const OGCard = createOGCard(OGData, mergedOptions);
139
- const index = parent.children.indexOf(node);
140
- // eslint-disable-next-line no-magic-numbers
141
- if (index === -1)
142
- return;
143
- // eslint-disable-next-line no-magic-numbers
144
- parent.children.splice(index, 1, OGCard);
145
- };
146
- linkCardPromises.push(linkCardPromise());
147
- });
148
- await Promise.all(linkCardPromises);
149
- };
150
- return transform;
151
- };
152
- export default rehypeOGCard;
package/dist/types.d.ts DELETED
@@ -1,73 +0,0 @@
1
- interface RehypeOGCardOptions {
2
- /**
3
- * Domains to exclude from conversion.
4
- */
5
- excludeDomains?: string[];
6
- /**
7
- * `decoding` attribute of the image element.
8
- * @default "async"
9
- */
10
- decoding?: HTMLImageElement["decoding"];
11
- /**
12
- * `loading` attribute of the image element.
13
- * @default "lazy"
14
- */
15
- loading?: HTMLImageElement["loading"];
16
- /**
17
- * Whether to shorten the displayed URL.
18
- * @default true
19
- */
20
- shortenURL?: boolean;
21
- /**
22
- * Whether to open the link in a new tab.
23
- * @default false
24
- */
25
- openInNewTab?: boolean;
26
- /**
27
- * Whether to enable converting the links
28
- * that have the same URL and text (e.g., `[https://example.com](https://example.com)`).
29
- * @default false
30
- */
31
- enableSameTextURLConversion?: boolean;
32
- /**
33
- * Whether to cache the OG data on the server.
34
- * @default true
35
- */
36
- serverCache?: boolean;
37
- /**
38
- * Path to save the server cache.
39
- * Specify the directory whose contents will be copied to the root.
40
- * For example, for an Astro project, specify the `public` directory.
41
- * @default "./public"
42
- */
43
- serverCachePath?: string;
44
- /**
45
- * Whether to cache the OG metadata and images for the next build.
46
- * `buildCache` option requires `serverCache` option to be enabled.
47
- * @default false
48
- */
49
- buildCache?: boolean;
50
- /**
51
- * Path to save the build cache.
52
- * For Astro projects, specify the `./node_modules/.astro` directory.
53
- * @default "./node_modules/.cache"
54
- */
55
- buildCachePath?: string;
56
- /**
57
- * User agent to use for fetching the OG metadata and images.
58
- * @default "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"
59
- */
60
- crawlerUserAgent?: string;
61
- }
62
- interface OGCardData {
63
- url: string;
64
- title: string;
65
- description?: string | undefined;
66
- displayURL: string;
67
- faviconURL?: string | undefined;
68
- OGImageURL?: string | undefined;
69
- OGImageAlt?: string | undefined;
70
- OGImageWidth?: number | undefined;
71
- OGImageHeight?: number | undefined;
72
- }
73
- export type { RehypeOGCardOptions, OGCardData };
package/dist/types.js DELETED
@@ -1 +0,0 @@
1
- export {};
@@ -1,28 +0,0 @@
1
- import type { OGCardData } from "../types.js";
2
- /**
3
- * Save build cache if server cache exists.
4
- * @param serverCachePath Server cache path.
5
- * @param buildCachePath Build cache path.
6
- */
7
- declare const saveBuildCacheFile: (serverCachePath: string, buildCachePath: string) => Promise<void>;
8
- /**
9
- * Restore build cache if it exists.
10
- * @param buildCachePath Build cache path.
11
- * @param serverCachePath Server cache path.
12
- */
13
- declare const restoreBuildCache: (buildCachePath: string, serverCachePath: string) => void;
14
- /**
15
- * Save OG data to build cache.
16
- * @param url URL of the OG data.
17
- * @param OGData OG data to save.
18
- * @param buildCachePath Build cache path.
19
- */
20
- declare const saveOGDataBuildCache: (url: string, OGData: OGCardData, buildCachePath: string) => Promise<void>;
21
- /**
22
- * Restore OG data from build cache.
23
- * @param url URL of the OG data.
24
- * @param buildCachePath Build cache path.
25
- * @returns Restored OG data. If not found, returns `null`.
26
- */
27
- declare const restoreOGDataBuildCache: (url: string, buildCachePath: string) => Promise<OGCardData | null>;
28
- export { saveBuildCacheFile, restoreBuildCache, saveOGDataBuildCache, restoreOGDataBuildCache };
@@ -1,56 +0,0 @@
1
- import { checkFileExists, copyDirectory, generateFilename } from "./file.js";
2
- import fs from "fs/promises";
3
- import path from "path";
4
- /**
5
- * Save build cache if server cache exists.
6
- * @param serverCachePath Server cache path.
7
- * @param buildCachePath Build cache path.
8
- */
9
- const saveBuildCacheFile = async (serverCachePath, buildCachePath) => {
10
- const serverCacheExists = await checkFileExists(serverCachePath);
11
- const buildCacheExists = await checkFileExists(buildCachePath);
12
- if (serverCacheExists && !buildCacheExists) {
13
- await fs.copyFile(serverCachePath, buildCachePath);
14
- }
15
- };
16
- /**
17
- * Restore build cache if it exists.
18
- * @param buildCachePath Build cache path.
19
- * @param serverCachePath Server cache path.
20
- */
21
- const restoreBuildCache = (buildCachePath, serverCachePath) => {
22
- copyDirectory(buildCachePath, serverCachePath);
23
- };
24
- /**
25
- * Save OG data to build cache.
26
- * @param url URL of the OG data.
27
- * @param OGData OG data to save.
28
- * @param buildCachePath Build cache path.
29
- */
30
- const saveOGDataBuildCache = async (url, OGData, buildCachePath) => {
31
- const filename = generateFilename(url, false);
32
- const savePath = `${path.join(buildCachePath, filename)}.json`;
33
- const cacheDirectoryExists = await checkFileExists(buildCachePath);
34
- if (!cacheDirectoryExists) {
35
- await fs.mkdir(buildCachePath, { recursive: true });
36
- }
37
- await fs.writeFile(savePath, JSON.stringify(OGData));
38
- };
39
- /**
40
- * Restore OG data from build cache.
41
- * @param url URL of the OG data.
42
- * @param buildCachePath Build cache path.
43
- * @returns Restored OG data. If not found, returns `null`.
44
- */
45
- const restoreOGDataBuildCache = async (url, buildCachePath) => {
46
- const filename = generateFilename(url, false);
47
- const savePath = `${path.join(buildCachePath, filename)}.json`;
48
- try {
49
- const data = await fs.readFile(savePath, "utf-8");
50
- return JSON.parse(data);
51
- }
52
- catch {
53
- return null;
54
- }
55
- };
56
- export { saveBuildCacheFile, restoreBuildCache, saveOGDataBuildCache, restoreOGDataBuildCache };
@@ -1,31 +0,0 @@
1
- /**
2
- * Check if the file exists.
3
- * @param filePath Path to check.
4
- * @returns `true` if the file exists, `false` otherwise.
5
- */
6
- declare const checkFileExists: (filePath: string) => Promise<boolean>;
7
- /**
8
- * Check if the file exists.
9
- * @param filePath Path to check.
10
- * @returns `true` if the file exists, `false` otherwise.
11
- */
12
- declare const checkFileExistsSync: (filePath: string) => boolean;
13
- /**
14
- * Create directory.
15
- * @param dir Directory path.
16
- */
17
- declare const createDirectorySync: (dir: string) => void;
18
- /**
19
- * Copy directory from source to destination.
20
- * @param source Source directory.
21
- * @param destination Destination directory.
22
- */
23
- declare const copyDirectory: (source: string, destination: string) => void;
24
- /**
25
- * Generate filename from URL.
26
- * @param url URL to generate filename.
27
- * @param extension Include extension in the filename.
28
- * @returns Generated filename.
29
- */
30
- declare const generateFilename: (url: string, extension?: boolean) => string;
31
- export { checkFileExists, checkFileExistsSync, createDirectorySync, copyDirectory, generateFilename };
package/dist/util/file.js DELETED
@@ -1,78 +0,0 @@
1
- import { createHash } from "crypto";
2
- import fs from "fs";
3
- import path from "path";
4
- /**
5
- * Check if the file exists.
6
- * @param filePath Path to check.
7
- * @returns `true` if the file exists, `false` otherwise.
8
- */
9
- const checkFileExists = async (filePath) => {
10
- try {
11
- await fs.promises.access(filePath);
12
- return true;
13
- }
14
- catch {
15
- return false;
16
- }
17
- };
18
- /**
19
- * Check if the file exists.
20
- * @param filePath Path to check.
21
- * @returns `true` if the file exists, `false` otherwise.
22
- */
23
- const checkFileExistsSync = (filePath) => {
24
- let result = false;
25
- fs.access(filePath, (error) => {
26
- result = !error;
27
- });
28
- return result;
29
- };
30
- /**
31
- * Create directory.
32
- * @param dir Directory path.
33
- */
34
- const createDirectorySync = (dir) => {
35
- fs.mkdir(dir, { recursive: true }, (error) => {
36
- if (error) {
37
- // eslint-disable-next-line no-console
38
- console.error("[rehype-og-card] Failed to copy files: ", error);
39
- }
40
- });
41
- };
42
- /**
43
- * Copy directory from source to destination.
44
- * @param source Source directory.
45
- * @param destination Destination directory.
46
- */
47
- const copyDirectory = (source, destination) => {
48
- const sourceExists = checkFileExistsSync(source);
49
- if (!sourceExists)
50
- return;
51
- const destinationExists = checkFileExistsSync(destination);
52
- if (!destinationExists) {
53
- createDirectorySync(destination);
54
- }
55
- fs.cp(source, destination, { recursive: true }, (error) => {
56
- if (error) {
57
- // eslint-disable-next-line no-console
58
- console.error("[rehype-og-card] Failed to copy files: ", error);
59
- }
60
- });
61
- };
62
- /**
63
- * Generate filename from URL.
64
- * @param url URL to generate filename.
65
- * @param extension Include extension in the filename.
66
- * @returns Generated filename.
67
- */
68
- const generateFilename = (url, extension = true) => {
69
- const hash = createHash("sha256").update(url).digest("hex");
70
- const possibleExtension = path.extname(new URL(url).pathname).toLowerCase();
71
- const allowedExtensions = [".png", ".jpg", ".jpeg", ".webp", ".gif", ".avif", ".svg"];
72
- const extensionString = allowedExtensions.includes(possibleExtension)
73
- ? possibleExtension
74
- : "";
75
- const filename = extension ? hash + extensionString : hash;
76
- return filename;
77
- };
78
- export { checkFileExists, checkFileExistsSync, createDirectorySync, copyDirectory, generateFilename };
@@ -1,38 +0,0 @@
1
- import type { Element, ElementContent, Text } from "hast";
2
- import type { OGCardData, RehypeOGCardOptions } from "../types.js";
3
- interface AnchorElement extends Element {
4
- tagName: "a";
5
- properties: {
6
- href: string;
7
- };
8
- }
9
- /**
10
- * Check if the node is a text node.
11
- * @param node Node to check.
12
- * @returns `true` if the node is a text node, `false` otherwise.
13
- */
14
- declare const isTextNode: (node: ElementContent) => node is Text;
15
- /**
16
- * Check if the node is an anchor element.
17
- * @param node Node to check.
18
- * @returns `true` if the node is an anchor element, `false` otherwise.
19
- */
20
- declare const isAnchorElement: (node: unknown) => node is AnchorElement;
21
- /**
22
- * Convert text node to anchor element. **This function does not check if the text is a valid URL.**
23
- * @param text Text node to convert.
24
- * @returns Anchor element.
25
- */
26
- declare const convertTextToAnchorElement: (text: Text) => AnchorElement;
27
- /**
28
- * Create OG card element from given data.
29
- * @param data Data to create OG card.
30
- * @param options Options to create OG card.
31
- * @returns OG card element.
32
- */
33
- declare const createOGCard: (data: OGCardData, options: Required<{
34
- loading: RehypeOGCardOptions["loading"];
35
- decoding: RehypeOGCardOptions["decoding"];
36
- openInNewTab: RehypeOGCardOptions["openInNewTab"];
37
- }>) => Element;
38
- export { type AnchorElement, isTextNode, isAnchorElement, convertTextToAnchorElement, createOGCard };
package/dist/util/hast.js DELETED
@@ -1,73 +0,0 @@
1
- import { h } from "hastscript";
2
- import { isElement } from "hast-util-is-element";
3
- /**
4
- * Check if the node is a text node.
5
- * @param node Node to check.
6
- * @returns `true` if the node is a text node, `false` otherwise.
7
- */
8
- const isTextNode = (node) => Boolean(node) && typeof node === "object" && "type" in node && node.type === "text";
9
- /**
10
- * Check if the node is an anchor element.
11
- * @param node Node to check.
12
- * @returns `true` if the node is an anchor element, `false` otherwise.
13
- */
14
- const isAnchorElement = (node) => Boolean(node) && isElement(node, "a") && "href" in node.properties && typeof node.properties["href"] === "string";
15
- /**
16
- * Convert text node to anchor element. **This function does not check if the text is a valid URL.**
17
- * @param text Text node to convert.
18
- * @returns Anchor element.
19
- */
20
- const convertTextToAnchorElement = (text) => ({
21
- children: [text],
22
- properties: {
23
- href: text.value.trim()
24
- },
25
- tagName: "a",
26
- type: "element"
27
- });
28
- /**
29
- * Create OG card element from given data.
30
- * @param data Data to create OG card.
31
- * @param options Options to create OG card.
32
- * @returns OG card element.
33
- */
34
- const createOGCard = (data, options) => {
35
- const openInNewTab = {
36
- rel: "noopener noreferrer",
37
- target: "_blank"
38
- };
39
- const card = h("div.og-card-container", [
40
- h("a", { href: data.url, ...(options.openInNewTab ? openInNewTab : {}) }, [
41
- h("div.og-card-info", [
42
- h("div.og-card-title", data.title),
43
- data.description ? h("div.og-card-description", data.description) : null,
44
- h("div.og-card-url-container", [
45
- h("img.og-card-favicon", {
46
- alt: "favicon",
47
- decoding: options.decoding,
48
- height: 16,
49
- loading: options.loading,
50
- src: data.faviconURL,
51
- width: 16
52
- }),
53
- h("span.og-card-url", data.displayURL)
54
- ])
55
- ]),
56
- data.OGImageURL
57
- ? h("div.og-card-image-container", [
58
- h("img.og-card-image", {
59
- // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
60
- alt: data.OGImageAlt || data.OGImageURL,
61
- decoding: options.decoding,
62
- height: data.OGImageHeight,
63
- loading: options.loading,
64
- src: data.OGImageURL,
65
- width: data.OGImageWidth
66
- })
67
- ])
68
- : null
69
- ])
70
- ]);
71
- return card;
72
- };
73
- export { isTextNode, isAnchorElement, convertTextToAnchorElement, createOGCard };
@@ -1,35 +0,0 @@
1
- import type { OGCardData } from "../types.js";
2
- /**
3
- * Check if the URL is valid.
4
- * @param url URL to check.
5
- * @returns `true` if the URL is valid, `false` otherwise.
6
- */
7
- declare const isValidURL: (url: string) => boolean;
8
- /**
9
- * Get OG card data from given URL.
10
- * @param url URL to get OG card data.
11
- * @param userAgent User agent to use for fetching.
12
- * @returns OG card data.
13
- */
14
- declare const getOGData: (url: string, userAgent: string) => Promise<OGCardData | null>;
15
- interface DownloadImageOptions {
16
- /**
17
- * URL to download image.
18
- */
19
- url: string;
20
- /**
21
- * Directory to save the downloaded image.
22
- */
23
- directory: string;
24
- /**
25
- * User agent to use for fetching the image.
26
- */
27
- userAgent: string;
28
- }
29
- /**
30
- * Download image from given URL. If the image already exists, return the filename.
31
- * @param options Options to download image.
32
- * @returns Filename of the downloaded image.
33
- */
34
- declare const downloadImage: (options: DownloadImageOptions) => Promise<string | null>;
35
- export { isValidURL, getOGData, downloadImage };
@@ -1,112 +0,0 @@
1
- import { checkFileExists, generateFilename } from "./file.js";
2
- import fetch from "node-fetch";
3
- import fs from "fs/promises";
4
- import path from "path";
5
- import scraper from "open-graph-scraper";
6
- /**
7
- * Check if the URL is valid.
8
- * @param url URL to check.
9
- * @returns `true` if the URL is valid, `false` otherwise.
10
- */
11
- const isValidURL = (url) => {
12
- const ALLOWED_PROTOCOLS = ["http:", "https:"];
13
- const parsedUrl = URL.parse(url);
14
- return Boolean(parsedUrl && ALLOWED_PROTOCOLS.includes(parsedUrl.protocol));
15
- };
16
- /**
17
- * Resolve an absolute URL from a raw URL and a base URL.
18
- * @param rawURL Raw URL to resolve.
19
- * @param baseURL Base URL to resolve against.
20
- * @returns Resolved absolute URL or `undefined` if the raw URL is invalid.
21
- */
22
- const resolveAbsoluteURL = (rawURL, baseURL) => {
23
- // eslint-disable-next-line no-undefined
24
- if (!rawURL)
25
- return undefined;
26
- const parsedUrl = URL.parse(rawURL, baseURL);
27
- // eslint-disable-next-line no-undefined
28
- return parsedUrl ? parsedUrl.href : undefined;
29
- };
30
- /**
31
- * Get OG card data from given URL.
32
- * @param url URL to get OG card data.
33
- * @param userAgent User agent to use for fetching.
34
- * @returns OG card data.
35
- */
36
- const getOGData = async (url, userAgent) => {
37
- try {
38
- const { result } = await scraper({
39
- fetchOptions: {
40
- headers: {
41
- "user-agent": userAgent
42
- }
43
- },
44
- url
45
- });
46
- const OGImage = result.ogImage ? result.ogImage[0] : null;
47
- const OGImageURL = resolveAbsoluteURL(OGImage?.url, url);
48
- const faviconURL = result.favicon
49
- ? `https://www.google.com/s2/favicons?domain=${new URL(url).hostname}`
50
- : // eslint-disable-next-line no-undefined
51
- undefined;
52
- return {
53
- OGImageAlt: OGImage?.alt,
54
- OGImageHeight: OGImage?.height,
55
- OGImageURL,
56
- OGImageWidth: OGImage?.width,
57
- description: result.ogDescription,
58
- displayURL: url,
59
- faviconURL,
60
- // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
61
- title: result.ogTitle || url,
62
- url
63
- };
64
- }
65
- catch (error) {
66
- // eslint-disable-next-line no-console
67
- console.error("[rehype-og-card] Error fetching OG data:", error);
68
- return null;
69
- }
70
- };
71
- /**
72
- * Download image from given URL. If the image already exists, return the filename.
73
- * @param options Options to download image.
74
- * @returns Filename of the downloaded image.
75
- */
76
- // eslint-disable-next-line max-statements
77
- const downloadImage = async (options) => {
78
- if (!isValidURL(options.url)) {
79
- // eslint-disable-next-line no-console
80
- console.error("[rehype-og-card] Invalid thumbnail URL:", options.url);
81
- return null;
82
- }
83
- try {
84
- const filename = generateFilename(options.url);
85
- const savePath = path.posix.join(options.directory, filename);
86
- // If the file already exists, return the filename.
87
- const fileExists = await checkFileExists(savePath);
88
- if (fileExists)
89
- return filename;
90
- const response = await fetch(options.url, {
91
- headers: {
92
- "user-agent": options.userAgent
93
- },
94
- // eslint-disable-next-line no-magic-numbers
95
- signal: AbortSignal.timeout(10 * 1000)
96
- });
97
- const arrayBuffer = await response.arrayBuffer();
98
- const buffer = Buffer.from(arrayBuffer);
99
- const saveDirectoryExists = await checkFileExists(options.directory);
100
- if (!saveDirectoryExists) {
101
- await fs.mkdir(options.directory, { recursive: true });
102
- }
103
- await fs.writeFile(savePath, buffer);
104
- return filename;
105
- }
106
- catch (error) {
107
- // eslint-disable-next-line no-console
108
- console.error("[rehype-og-card] Error downloading image:", error);
109
- return null;
110
- }
111
- };
112
- export { isValidURL, getOGData, downloadImage };