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: fix some possible issues with file paths #377

Merged
merged 3 commits into from
Nov 10, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
5 changes: 4 additions & 1 deletion src/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -184,10 +184,12 @@ async function loader(content) {
}
}

const isAbsolute = isAbsoluteURL(this.resourcePath);
let isAbsolute = isAbsoluteURL(this.resourcePath);

const filename = isAbsolute
? this.resourcePath
: path.relative(this.rootContext, this.resourcePath);

const minifyOptions =
/** @type {import("./index").InternalWorkerOptions<T>} */ ({
input: content,
Expand Down Expand Up @@ -243,6 +245,7 @@ async function loader(content) {
query = query.length > 0 ? `?${query}` : "";
}

isAbsolute = isAbsoluteURL(output.filename);
// Old approach for `file-loader` and other old loaders
changeResource(this, isAbsolute, output, query);

Expand Down
33 changes: 24 additions & 9 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,16 @@ const path = require("path");
* @typedef {() => Promise<T>} Task
*/

/**
* @param {string} filename file path without query params (e.g. `path/img.png`)
* @param {string} ext new file extension without `.` (e.g. `webp`)
*/
function replaceFileExtension(filename, ext) {
const dotIndex = filename.lastIndexOf(".");

return dotIndex > -1 ? `${filename.slice(0, dotIndex)}.${ext}` : filename;
}
RAX7 marked this conversation as resolved.
Show resolved Hide resolved

/**
* Run tasks with limited concurrency.
* @template T
Expand Down Expand Up @@ -79,7 +89,7 @@ const WINDOWS_PATH_REGEX = /^[a-zA-Z]:\\/;
*/
function isAbsoluteURL(url) {
if (WINDOWS_PATH_REGEX.test(url)) {
return false;
return true;
}

return ABSOLUTE_URL_REGEX.test(url);
Expand Down Expand Up @@ -592,10 +602,7 @@ async function imageminGenerate(original, minimizerOptions) {
let newFilename = original.filename;

if (extOutput && extInput !== extOutput) {
newFilename = original.filename.replace(
new RegExp(`${extInput}$`),
`${extOutput}`
);
newFilename = replaceFileExtension(original.filename, extOutput);
}

return {
Expand Down Expand Up @@ -795,8 +802,7 @@ async function squooshGenerate(original, minifyOptions) {
const { binary, extension } = await Object.values(image.encodedWith)[0];
const { width, height } = (await image.decoded).bitmap;

const { dir: fileDir, name: fileName } = path.parse(original.filename);
const filename = path.join(fileDir, `${fileName}.${extension}`);
const filename = replaceFileExtension(original.filename, extension);

return {
filename,
Expand Down Expand Up @@ -1040,13 +1046,22 @@ async function sharpTransform(
// ====== rename ======

const outputExt = targetFormat ? outputFormat : inputExt;
const { dir: fileDir, name: fileName } = path.parse(original.filename);
const { width, height } = result.info;

const sizeSuffix =
typeof minimizerOptions.sizeSuffix === "function"
? minimizerOptions.sizeSuffix(width, height)
: "";
const filename = path.join(fileDir, `${fileName}${sizeSuffix}.${outputExt}`);

const dotIndex = original.filename.lastIndexOf(".");
const filename =
dotIndex > -1
? `${original.filename.slice(0, dotIndex)}${sizeSuffix}.${outputExt}`
: original.filename;

// TODO use this then remove `sizeSuffix`
// const filename = replaceFileExtension(original.filename, outputExt);

const processedFlag = targetFormat ? "generated" : "minimized";
const processedBy = targetFormat ? "generatedBy" : "minimizedBy";

Expand Down
6 changes: 3 additions & 3 deletions test/ImageminPlugin.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -891,7 +891,7 @@ describe("imagemin plugin", () => {
const stringStats = stats.toString({ relatedAssets: true });

expect(stringStats).toMatch(
/asset loader-test.webp.+\[from: loader-test.png\] \[generated\]/
/asset loader-test.webp.+\[from: .*loader-test.png\] \[generated\]/
);
});

Expand Down Expand Up @@ -1358,7 +1358,7 @@ describe("imagemin plugin", () => {
expect(warnings).toHaveLength(0);
expect(errors).toHaveLength(1);
expect(errors[0].message).toMatch(
/Multiple values for the 'encodeOptions' option is not supported for 'loader-test.png', specify only one codec for the generator/
/Multiple values for the 'encodeOptions' option is not supported for '.*loader-test.png', specify only one codec for the generator/
);
});

Expand Down Expand Up @@ -1728,7 +1728,7 @@ describe("imagemin plugin", () => {
expect(warnings).toHaveLength(0);
expect(errors).toHaveLength(1);
expect(errors[0].message).toMatch(
/Error with 'loader-test.txt': Input file has an unsupported format/g
/Error with '.*loader-test.txt': Input file has an unsupported format/g
);
});

Expand Down
8 changes: 0 additions & 8 deletions types/utils.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,6 @@ export type SharpOptions = {
encodeOptions?: SharpEncodeOptions | undefined;
};
export type SizeSuffix = (width: number, height: number) => string;
/** @typedef {import("./index").WorkerResult} WorkerResult */
/** @typedef {import("./index").SquooshOptions} SquooshOptions */
/** @typedef {import("imagemin").Options} ImageminOptions */
/** @typedef {import("webpack").WebpackError} WebpackError */
/**
* @template T
* @typedef {() => Promise<T>} Task
*/
/**
* Run tasks with limited concurrency.
* @template T
Expand Down