UNPKG

@mintlify/common

Version:

Commonly shared code within Mintlify

49 lines (48 loc) 1.89 kB
import isAbsoluteUrl from 'is-absolute-url'; import path from 'path'; import { visit } from 'unist-util-visit'; import { removeBasePath } from '../../../fs/removeBasePath.js'; import { getS3URI } from '../../../services/aws.js'; export const getImageUri = (imagePath, subdomain, filePath, basePath) => { if (imagePath.startsWith('/')) { const path = removeBasePath(imagePath, basePath); return getS3URI(subdomain, path); } const beforeFilePath = path.join(filePath, '../'); const relativePath = removeBasePath(path.join(beforeFilePath, imagePath), basePath); return getS3URI(subdomain, relativePath); }; export const remarkReplaceAllImages = (subdomain, filePath, basePath) => { return (tree) => { visit(tree, 'mdxJsxFlowElement', (node) => { if (node.name === 'img' || node.name === 'source' || node.name === 'video') { const srcAttr = node.attributes.find(isSrcAttr); if (!srcAttr) return; const nodeUrl = srcAttr.value; if (typeof nodeUrl !== 'string') return; if ( // <img/> component !isAbsoluteUrl(nodeUrl) && !isDataString(nodeUrl)) { srcAttr.value = getImageUri(nodeUrl, subdomain, filePath, basePath); } } }); visit(tree, 'image', (node) => { if ( // ![]() format node.url && !isAbsoluteUrl(node.url) && !isDataString(node.url)) { node.url = getImageUri(node.url, subdomain, filePath, basePath); } }); return tree; }; }; function isSrcAttr(attr) { return attr.type === 'mdxJsxAttribute' && attr.name === 'src'; } const isDataString = (str) => str.startsWith('data:');