Skip to content

Commit

Permalink
fix: better fix for #334 (#343)
Browse files Browse the repository at this point in the history
  • Loading branch information
RAX7 authored Sep 9, 2022
1 parent 667863d commit 78dcac9
Show file tree
Hide file tree
Showing 6 changed files with 139 additions and 86 deletions.
58 changes: 19 additions & 39 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -557,7 +557,7 @@ async function imageminNormalizeConfig(imageminConfig) {
* @template T
* @param {WorkerResult} original
* @param {T} minimizerOptions
* @returns {Promise<WorkerResult>}
* @returns {Promise<WorkerResult | null>}
*/
async function imageminGenerate(original, minimizerOptions) {
const minimizerOptionsNormalized = /** @type {ImageminOptions} */ (
Expand All @@ -582,10 +582,8 @@ async function imageminGenerate(original, minimizerOptions) {
`Error with '${original.filename}': ${originalError.message}`
);

original.info.original = true;
original.errors.push(newError);

return original;
return null;
}

const { ext: extOutput } = fileTypeFromBuffer(result) || {};
Expand Down Expand Up @@ -617,7 +615,7 @@ async function imageminGenerate(original, minimizerOptions) {
* @template T
* @param {WorkerResult} original
* @param {T} options
* @returns {Promise<WorkerResult>}
* @returns {Promise<WorkerResult | null>}
*/
async function imageminMinify(original, options) {
const minimizerOptionsNormalized = /** @type {ImageminOptions} */ (
Expand All @@ -642,25 +640,22 @@ async function imageminMinify(original, options) {
`Error with '${original.filename}': ${originalError.message}`
);

original.info.original = true;
original.errors.push(newError);

return original;
return null;
}

if (!isAbsoluteURL(original.filename)) {
const extInput = path.extname(original.filename).slice(1).toLowerCase();
const { ext: extOutput } = fileTypeFromBuffer(result) || {};

if (extOutput && extInput !== extOutput) {
original.info.original = true;
original.warnings.push(
new Error(
`"imageminMinify" function do not support generate to "${extOutput}" from "${original.filename}". Please use "imageminGenerate" function.`
)
);

return original;
return null;
}
}

Expand Down Expand Up @@ -729,7 +724,7 @@ async function squooshImagePoolTeardown() {
* @template T
* @param {WorkerResult} original
* @param {T} minifyOptions
* @returns {Promise<WorkerResult>}
* @returns {Promise<WorkerResult | null>}
*/
async function squooshGenerate(original, minifyOptions) {
// eslint-disable-next-line node/no-unpublished-require
Expand Down Expand Up @@ -774,38 +769,32 @@ async function squooshGenerate(original, minifyOptions) {
`Error with '${original.filename}': ${originalError.message}`
);

original.info.original = true;
original.errors.push(newError);

return original;
return null;
}

if (!isReusePool) {
await imagePool.close();
}

if (Object.keys(image.encodedWith).length === 0) {
// eslint-disable-next-line require-atomic-updates
original.info.original = true;
original.errors.push(
new Error(
`No result from 'squoosh' for '${original.filename}', please configure the 'encodeOptions' option to generate images`
)
);

return original;
return null;
}

if (Object.keys(image.encodedWith).length > 1) {
// eslint-disable-next-line require-atomic-updates
original.info.original = true;
original.errors.push(
new Error(
`Multiple values for the 'encodeOptions' option is not supported for '${original.filename}', specify only one codec for the generator`
)
);

return original;
return null;
}

const { binary, extension } = await Object.values(image.encodedWith)[0];
Expand Down Expand Up @@ -833,7 +822,7 @@ squooshGenerate.teardown = squooshImagePoolTeardown;
* @template T
* @param {WorkerResult} original
* @param {T} options
* @returns {Promise<WorkerResult>}
* @returns {Promise<WorkerResult | null>}
*/
async function squooshMinify(original, options) {
// eslint-disable-next-line node/no-unpublished-require
Expand All @@ -859,15 +848,14 @@ async function squooshMinify(original, options) {
const targetCodec = targets[ext];

if (!targetCodec) {
original.info.original = true;

return original;
return null;
}

const isReusePool = Boolean(pool);
const imagePool = pool || squooshImagePoolCreate();
const image = imagePool.ingestImage(new Uint8Array(original.data));
const squooshOptions = /** @type {SquooshOptions} */ (options || {});

/**
* @type {undefined | Object.<string, any>}
*/
Expand Down Expand Up @@ -906,10 +894,8 @@ async function squooshMinify(original, options) {
`Error with '${original.filename}': ${originalError.message}`
);

original.info.original = true;
original.errors.push(newError);

return original;
return null;
}

if (!isReusePool) {
Expand Down Expand Up @@ -993,7 +979,7 @@ const SHARP_FORMATS = new Map([
* @param {WorkerResult} original
* @param {SharpOptions} minimizerOptions
* @param {SharpFormat | null} targetFormat
* @returns {Promise<WorkerResult>}
* @returns {Promise<WorkerResult | null>}
*/
async function sharpTransform(
original,
Expand All @@ -1003,9 +989,7 @@ async function sharpTransform(
const inputExt = path.extname(original.filename).slice(1).toLowerCase();

if (!SHARP_FORMATS.has(inputExt)) {
original.info.original = true;

return original;
return null;
}

/** @type {SharpLib} */
Expand Down Expand Up @@ -1080,7 +1064,7 @@ async function sharpTransform(
* @template T
* @param {WorkerResult} original
* @param {T} minimizerOptions
* @returns {Promise<WorkerResult>}
* @returns {Promise<WorkerResult | null>}
*/
function sharpGenerate(original, minimizerOptions) {
const sharpOptions = /** @type {SharpOptions} */ (minimizerOptions ?? {});
Expand All @@ -1094,21 +1078,17 @@ function sharpGenerate(original, minimizerOptions) {
`No result from 'sharp' for '${original.filename}', please configure the 'encodeOptions' option to generate images`
);

original.info.original = true;
original.errors.push(error);

return Promise.resolve(original);
return Promise.resolve(null);
}

if (targetFormats.length > 1) {
const error = new Error(
`Multiple values for the 'encodeOptions' option is not supported for '${original.filename}', specify only one codec for the generator`
);

original.info.original = true;
original.errors.push(error);

return Promise.resolve(original);
return Promise.resolve(null);
}

const [targetFormat] = targetFormats;
Expand All @@ -1120,7 +1100,7 @@ function sharpGenerate(original, minimizerOptions) {
* @template T
* @param {WorkerResult} original
* @param {T} minimizerOptions
* @returns {Promise<WorkerResult>}
* @returns {Promise<WorkerResult | null>}
*/
function sharpMinify(original, minimizerOptions) {
return sharpTransform(
Expand Down
78 changes: 45 additions & 33 deletions src/worker.js
Original file line number Diff line number Diff line change
@@ -1,40 +1,43 @@
/** @typedef {import("./index").WorkerResult} WorkerResult */
/** @typedef {import("./index").FilenameFn} FilenameFn */

const isFilenameProcessed = Symbol("isFilenameProcessed");

/**
* @template T
* @param {WorkerResult} result
* @param {import("./index").InternalWorkerOptions<T>} options
* @param {WorkerResult} item
* @param {undefined | string | FilenameFn} filename
* @returns {WorkerResult}
* @param {undefined | string | FilenameFn} filenameTemplate
*/
function normalizeProcessedResult(options, item, filename) {
item.info ??= {};
item.filename ??= options.filename;
item.errors ??= [];
item.warnings ??= [];

if (options.severityError === "off") {
item.warnings = [];
item.errors = [];
} else if (options.severityError === "warning") {
item.warnings = [...item.warnings, ...item.errors];
item.errors = [];
}

function processFilenameTemplate(result, options, filenameTemplate) {
if (
typeof filename !== "undefined" &&
typeof options.generateFilename === "function" &&
!item.info.original
// @ts-ignore
!result.info[isFilenameProcessed] &&
typeof filenameTemplate !== "undefined" &&
typeof options.generateFilename === "function"
) {
item.filename = options.generateFilename(filename, {
filename: item.filename,
result.filename = options.generateFilename(filenameTemplate, {
filename: result.filename,
});
}

delete item.info.original;
// @ts-ignore
result.info[isFilenameProcessed] = true;
}
}

return item;
/**
* @template T
* @param {WorkerResult} result
* @param {import("./index").InternalWorkerOptions<T>} options
*/
function processSeverityError(result, options) {
if (options.severityError === "off") {
result.warnings = [];
result.errors = [];
} else if (options.severityError === "warning") {
result.warnings = [...result.warnings, ...result.errors];
result.errors = [];
}
}

/**
Expand All @@ -54,14 +57,16 @@ async function worker(options) {

if (!result.data) {
result.errors.push(new Error("Empty input"));

return result;
}

const transformers = Array.isArray(options.transformer)
? options.transformer
: [options.transformer];

/** @type {undefined | string | FilenameFn} */
let filenameTemplate;

for (const transformer of transformers) {
if (
typeof transformer.filter === "function" &&
Expand All @@ -70,7 +75,7 @@ async function worker(options) {
continue;
}

/** @type {WorkerResult} */
/** @type {WorkerResult | null} */
let processedResult;

try {
Expand All @@ -89,7 +94,7 @@ async function worker(options) {
return result;
}

if (!processedResult || !Buffer.isBuffer(processedResult.data)) {
if (processedResult && !Buffer.isBuffer(processedResult.data)) {
result.errors.push(
new Error(
"minimizer function doesn't return the 'data' property or result is not a 'Buffer' value"
Expand All @@ -99,13 +104,20 @@ async function worker(options) {
return result;
}

result = normalizeProcessedResult(
options,
processedResult,
transformer.filename
);
if (processedResult) {
result = processedResult;
filenameTemplate ??= transformer.filename;
}
}

result.info ??= {};
result.errors ??= [];
result.warnings ??= [];
result.filename ??= options.filename;

processSeverityError(result, options);
processFilenameTemplate(result, options, filenameTemplate);

return result;
}

Expand Down
2 changes: 2 additions & 0 deletions test/loader-generator-option.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import ImageMinimizerPlugin from "../src";

import { runWebpack, fixturesPath } from "./helpers";

jest.setTimeout(10000);

describe("loader generator option", () => {
it("should work", async () => {
const stats = await runWebpack({
Expand Down
Loading

0 comments on commit 78dcac9

Please sign in to comment.