summaryrefslogtreecommitdiff
path: root/packages/markdown/remark/src/remark-collect-images.ts
diff options
context:
space:
mode:
Diffstat (limited to 'packages/markdown/remark/src/remark-collect-images.ts')
-rw-r--r--packages/markdown/remark/src/remark-collect-images.ts24
1 files changed, 19 insertions, 5 deletions
diff --git a/packages/markdown/remark/src/remark-collect-images.ts b/packages/markdown/remark/src/remark-collect-images.ts
index afc61c468..470b770ed 100644
--- a/packages/markdown/remark/src/remark-collect-images.ts
+++ b/packages/markdown/remark/src/remark-collect-images.ts
@@ -1,17 +1,31 @@
import type { Image } from 'mdast';
import { visit } from 'unist-util-visit';
-import type { VFile } from 'vfile';
+import type { MarkdownVFile } from './types';
export default function toRemarkCollectImages() {
return () =>
- async function (tree: any, vfile: VFile) {
+ async function (tree: any, vfile: MarkdownVFile) {
if (typeof vfile?.path !== 'string') return;
const imagePaths = new Set<string>();
- visit(tree, 'image', function raiseError(node: Image) {
- imagePaths.add(node.url);
+ visit(tree, 'image', (node: Image) => {
+ if (shouldOptimizeImage(node.url)) imagePaths.add(node.url);
});
- vfile.data.imagePaths = Array.from(imagePaths);
+ vfile.data.imagePaths = imagePaths;
};
}
+
+function shouldOptimizeImage(src: string) {
+ // Optimize anything that is NOT external or an absolute path to `public/`
+ return !isValidUrl(src) && !src.startsWith('/');
+}
+
+function isValidUrl(str: string): boolean {
+ try {
+ new URL(str);
+ return true;
+ } catch {
+ return false;
+ }
+}