From 4e231e5388e89d31dfb3e7004d675f8c9465a19c Mon Sep 17 00:00:00 2001 From: Saneef Ansari Date: Mon, 23 Oct 2023 02:25:32 +0530 Subject: [PATCH] fix: remote URLs with query are skipped Fixes #22 --- lib/img2picture.js | 27 +++++++++++++-------------- tests/remote.js | 15 +++++++++++++++ 2 files changed, 28 insertions(+), 14 deletions(-) diff --git a/lib/img2picture.js b/lib/img2picture.js index 817d198..947c1c7 100644 --- a/lib/img2picture.js +++ b/lib/img2picture.js @@ -217,31 +217,30 @@ async function generateImage(attrs, options) { async function replaceImages(content, options) { const { extensions, fetchRemote } = options; const $ = cheerio.load(content); - let images = $("img") + const images = $("img") .not("picture img") // Ignore images wrapped in .not("[data-img2picture-ignore]") // Ignore excluded images .filter((i, el) => { const src = $(el).attr("src"); if (src && extensions) { + // Exclude remote URLs when fetchRemote=false + const pathFromUrl = getPathFromUrl(src); + if (pathFromUrl) { + // Is remote URL + if (fetchRemote) { + return isAllowedExtension(pathFromUrl, extensions); + } + + return false; + } + + // Exclude paths with extensions other than provided return isAllowedExtension(src, extensions); } return false; }); - // Ignore remote images if fetchRemote is false - if (!fetchRemote) { - images = images.filter((i, el) => { - const src = $(el).attr("src"); - - if (src) { - return !isRemoteUrl(src); - } - - return false; - }); - } - const promises = []; for (let i = 0; i < images.length; i++) { const img = images[i]; diff --git a/tests/remote.js b/tests/remote.js index 094c9fb..1604d6a 100644 --- a/tests/remote.js +++ b/tests/remote.js @@ -47,3 +47,18 @@ test("Fetch a remote image, generates AVIF, WebP, JPEG formats, and puts them in t.is(smallestWebPWidth, 150); t.is(largestWebPWidth, 1350); }); + +test("Fetch a remote image with query params in URL", async (t) => { + const input = + 'Shapes'; + const outputPath = "file.html"; + const output = + 'Shapes'; + + const transformer = img2picture({ + ...baseOptions, + fetchRemote: true, + }); + const result = await transformer(input, outputPath); + t.is(result, output); +});