Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: Remote URLs with query params are skipped #23

Merged
merged 6 commits into from
Oct 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .eleventy.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ module.exports = {
/**
* Plugin config function
*
* @param {Object} eleventy The eleventy configuration object
* @param {object} eleventy The eleventy configuration object
* @param {Img2PictureOptions=} The options
*/
configFunction(eleventy, options) {
Expand Down
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ node_modules
package-lock.json
.nyc_output
.eslintcache
tests/output
tests/output
.cache
92 changes: 0 additions & 92 deletions lib/helpers.js

This file was deleted.

77 changes: 42 additions & 35 deletions lib/img2picture.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,22 @@ const cheerio = require("cheerio");
const Image = require("@11ty/eleventy-img");
const path = require("path");
const debug = require("debug")("img2picture");
const { removeObjectProperties } = require("./helpers");

/** @typedef { import('@11ty/eleventy-img').ImageFormatWithAliases } ImageFormatWithAliases */

const {
isUrl,
isAllowedExtension,
generateWidths,
parseStringToNumbers,
removeObjectProperties,
objectToAttributes,
} = require("./helpers.js");
} = require("./utils/object");
const { parseStringToNumbers } = require("./utils/number");
const { isRemoteUrl, getPathFromUrl } = require("./utils/url");
const { generateWidths } = require("./utils/image");
const { isAllowedExtension } = require("./utils/file");

/** @typedef { import('@11ty/eleventy-img').ImageFormatWithAliases } ImageFormatWithAliases */

/**
* @typedef {object} Img2PictureOptions
* @property {string=} eleventyInputDir
* @property {string=} imagesOutputDir
* @property {string=} urlPath
* @property {string} eleventyInputDir
* @property {string} imagesOutputDir
* @property {string} urlPath
* @property {Array<string>=} extensions
* @property {Array<ImageFormatWithAliases>=} formats
* @property {string=} sizes
Expand Down Expand Up @@ -63,22 +62,20 @@ const defaultOptions = {
};

/**
* @typedef {(id?: string, src?: string, width?: number, format?: string, options?: object) => string} filenameFormatFn
* @typedef {(id: string, src: unknown, width: number, format: string) => string} filenameFormatFn
*/

/* eslint-disable max-params */
/**
* Default function to generate image filenames
*
* @type {filenameFormatFn}
*/
const filenameFormatter = function (id, src, width, format, _options) {
const extension = path.extname(src);
const name = path.basename(src, extension);
const filenameFormatter = function (id, src, width, format) {
const extension = path.extname(/** @type {string} */ (src));
const name = path.basename(/** @type {string} */ (src), extension);

return `${name}-${id}-${width}w.${format}`;
};
/* eslint-enable max-params */

/**
*
Expand All @@ -90,7 +87,7 @@ const filenameFormatter = function (id, src, width, format, _options) {
* @return {object} The the last from metadata
*/
const getFallbackFormat = (metadata, options) => {
const { formats } = options;
const { formats = ["jpeg"] } = options;
const fallbackFormat = formats[formats.length - 1];

return metadata[fallbackFormat];
Expand Down Expand Up @@ -170,22 +167,22 @@ async function generateImage(attrs, options) {
filenameFormat,
formats,
imagesOutputDir,
maxWidth,
minWidth,
maxWidth = 1500,
minWidth = 150,
sharpAvifOptions,
sharpJpegOptions,
sharpOptions,
sharpPngOptions,
sharpWebpOptions,
urlPath,
widthStep,
widthStep = 150,
} = options;
const { src, "data-img2picture-widths": imgAttrWidths } = attrs;

const widths = imgAttrWidths
? parseStringToNumbers(imgAttrWidths)
: generateWidths(minWidth, maxWidth, widthStep);
const filePath = isUrl(src) ? src : path.join(eleventyInputDir, src);
const filePath = isRemoteUrl(src) ? src : path.join(eleventyInputDir, src);

const filenameFormatFn =
typeof filenameFormat === "function" ? filenameFormat : filenameFormatter;
Expand Down Expand Up @@ -220,30 +217,40 @@ 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 <picture>
.not("[data-img2picture-ignore]") // Ignore excluded images
.filter((i, el) => {
const src = $(el).attr("src");
return isAllowedExtension(src, extensions);
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");
return !isUrl(src);
});
}

const promises = [];
for (let i = 0; i < images.length; i++) {
const img = images[i];
const attrs = $(img).attr();

debug(`Optimizing: ${attrs.src}`);
if (attrs) {
debug(`Optimizing: ${attrs.src}`);

promises[i] = generateImage(attrs, options);
promises[i] = generateImage(attrs, options);
}
}

const pictures = await Promise.all(promises);
Expand Down
20 changes: 20 additions & 0 deletions lib/utils/file.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// @ts-check

/**
* Checks if the file path matches a whitelist of extensions
*
* @param {string} path The path
* @param {Array<string>} extensions The extensions
* @return {boolean} `True` if matches, `False` otherwise.
*/
function isAllowedExtension(path, extensions) {
const lowerCaseExtensions = extensions.map((x) => x.toLowerCase());

return Boolean(
lowerCaseExtensions.find((ext) => path.toLowerCase().endsWith(ext)),
);
}

module.exports = {
isAllowedExtension,
};
22 changes: 22 additions & 0 deletions lib/utils/image.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// @ts-check

/**
* Generate Widths for Image
*
* @param {number} min The minimum
* @param {number} max The maximum
* @param {number} step The step
* @return {Array<number>} Widths
*/
function generateWidths(min, max, step) {
const sizes = [];
for (let i = min; i < max; i += step) {
sizes.push(i);
}

return sizes;
}

module.exports = {
generateWidths,
};
15 changes: 15 additions & 0 deletions lib/utils/number.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// @ts-check

/**
* Parse string with comma separated numbers into array of numbers
*
* @param {string} str The string to parse
* @return {Array<number>} An array of numbers
*/
function parseStringToNumbers(str) {
return str.split(",").map((s) => Number(s));
}

module.exports = {
parseStringToNumbers,
};
36 changes: 36 additions & 0 deletions lib/utils/object.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// @ts-check

/**
* Converts object to HTML attributes string
*
* @param {object} obj The object
* @return {string}
*/
function objectToAttributes(obj) {
return Object.keys(obj).reduce((acc, key) => {
// Ignore empty class attribute
if (key === "class" && !obj[key]) return acc;

return `${acc} ${key}="${obj[key]}"`;
}, "");
}

/**
* Removes object properties.
*
* @param {object} obj The object
* @param {Array<string>} props The properties
* @return {object} Shallow cloned object without properties
*/
function removeObjectProperties(obj, props = []) {
const copy = { ...obj };

props.forEach((key) => delete copy[key]);

return copy;
}

module.exports = {
objectToAttributes,
removeObjectProperties,
};
4 changes: 2 additions & 2 deletions tests/helpers.js → lib/utils/object.test.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
const test = require("ava");

const { removeObjectProperties } = require("../lib/helpers");
const { removeObjectProperties } = require("./object");

test("Should remove name and age properties from object", async (t) => {
test("removeObjectProperties: should remove name and age properties from object", async (t) => {
const obj = {
name: "Jane Doe",
age: 20,
Expand Down
Loading