Skip to content
Open
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
23 changes: 17 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

61 changes: 49 additions & 12 deletions src/worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ import fs from 'fs';
import NativeModule from 'module';

import querystring from 'querystring';
import util from 'util';

import loaderRunner from 'loader-runner';
import asyncQueue from 'neo-async/queue';
import parseJson from 'json-parse-better-errors';
import { validate } from 'schema-utils';

import readBuffer from './readBuffer';
import { replacer, reviver } from './serializer';
Expand Down Expand Up @@ -210,12 +210,13 @@ const queue = asyncQueue(({ id, data }, taskCallback) => {
}
},
// Not an arrow function because it uses this
getOptions(schema) {
getOptions(schema, configurationOrCheck, precompiledCheck) {
// loaders, loaderIndex will be defined by runLoaders
const loader = this.loaders[this.loaderIndex];

// Verbatim copy from
// https://github.com/webpack/webpack/blob/v5.31.2/lib/NormalModule.js#L471-L508
// https://github.com/webpack/webpack/blob/v5.113.0/lib/module/NormalModule.js
// and lib/util/validateSchema.js
// except eslint/prettier differences
// -- unfortunate result of getOptions being synchronous functions.

Expand All @@ -241,17 +242,53 @@ const queue = asyncQueue(({ id, data }, taskCallback) => {
}

if (schema) {
let name = 'Loader';
let baseDataPath = 'options';
// A configuration is an object and a check a function, so the
// check can come last or in the configuration's place
const check =
typeof configurationOrCheck === 'function'
? configurationOrCheck
: precompiledCheck;
const configuration =
typeof configurationOrCheck === 'function'
? // eslint-disable-next-line no-undefined
undefined
: configurationOrCheck;

// A precompiled check that passes skips the schema, so valid
// options never load `schema-utils` or compile it
if (check && check(options)) {
return options;
}

const resolvedSchema =
typeof schema === 'function' ? schema() : schema;
let title;
let match;
// eslint-disable-next-line no-cond-assign
if (schema.title && (match = /^(.+) (.+)$/.exec(schema.title))) {
[, name, baseDataPath] = match;
if (
typeof resolvedSchema.title === 'string' &&
// eslint-disable-next-line no-cond-assign
(match = /^(.+) (.+)$/.exec(resolvedSchema.title))
) {
title = { name: match[1], baseDataPath: match[2] };
}
const resolvedConfiguration = {
...(title || { name: 'Loader', baseDataPath: 'options' }),
...configuration,
};

// eslint-disable-next-line global-require
const { validate } = require('schema-utils');

validate(resolvedSchema, options, resolvedConfiguration);

// The schema accepts what the check rejected, so the check is stale
if (check) {
util.deprecate(
() => {},
`${resolvedConfiguration.name} pre-compiled schema reports error while real schema is happy. This has performance drawbacks.`,
'DEP_WEBPACK_PRE_COMPILED_SCHEMA_INVALID',
)();
}
validate(schema, options, {
name,
baseDataPath,
});
}

return options;
Expand Down
119 changes: 119 additions & 0 deletions test/options-check.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import os from 'os';
import path from 'path';

import webpack from 'webpack';

const threadLoader = require('../dist');

const loader = require.resolve('./options-check/options-check-loader');

const run = (options, mode = 'check') =>
new Promise((resolve, reject) => {
webpack(
{
mode: 'none',
context: path.resolve(__dirname, 'options-check'),
devtool: false,
entry: `./file.js?${mode}`,
output: {
path: path.join(os.tmpdir(), 'thread-loader-options-check', mode),
},
module: {
rules: [
{
test: /file\.js$/,
use: [
{
loader: path.resolve(__dirname, '../dist/index.js'),
options: { workers: 1, poolTimeout: 2000 },
},
{ loader, options },
],
},
],
},
},
(err, stats) => (err ? reject(err) : resolve(stats)),
);
});

beforeAll(() => {
threadLoader.warmup({ workers: 1, poolTimeout: 2000 }, [loader]);
});

test('skips the schema when the precompiled check passes', async () => {
const stats = await run({ trusted: true });

expect(stats.compilation.errors).toHaveLength(0);
});

test('validates against the schema when the precompiled check fails', async () => {
const stats = await run({ name: 1 });

expect(stats.compilation.errors).toHaveLength(1);
expect(stats.compilation.errors[0].message).toMatch(
/Invalid options object\. Loader has been initialized using an options object that does not match the API schema\.\n - options\.name should be a string/,
);
});

test('takes the check after the configuration', async () => {
expect(
(await run({ trusted: true }, 'configuration')).compilation.errors,
).toHaveLength(0);

const stats = await run({ name: 1 }, 'configuration');

expect(stats.compilation.errors).toHaveLength(1);
expect(stats.compilation.errors[0].message).toMatch(
/Invalid query object\. Named Loader has been initialized.*\n - query\.name should be a string/,
);
});

test('reads a schema function only when the check fails', async () => {
expect(
(await run({ trusted: true }, 'lazy')).compilation.errors,
).toHaveLength(0);

const stats = await run({ name: 1 }, 'lazy');

expect(stats.compilation.errors).toHaveLength(1);
expect(stats.compilation.errors[0].message).toMatch(
/options\.name should be a string/,
);
});

test('names the loader by the schema title', async () => {
const stats = await run({ name: 1 }, 'title');

expect(stats.compilation.errors).toHaveLength(1);
expect(stats.compilation.errors[0].message).toMatch(
/Invalid query object\. Titled Loader has been initialized.*\n - query\.name should be a string/,
);
});

test('reports a check that rejects what the schema accepts', async () => {
const write = jest.spyOn(process.stderr, 'write');
// The worker's stderr reaches this process on its own pipe, so the warning
// can arrive after the compilation finished
const warned = () =>
/\[DEP_WEBPACK_PRE_COMPILED_SCHEMA_INVALID\] DeprecationWarning: Loader pre-compiled schema reports error while real schema is happy/.test(
write.mock.calls.join(''),
);

try {
const stats = await run({ name: 'valid' }, 'stale');

expect(stats.compilation.errors).toHaveLength(0);

for (let i = 0; i < 50 && !warned(); i++) {
// eslint-disable-next-line no-await-in-loop
await new Promise((resolve) => {
setTimeout(resolve, 20);
});
}

expect(warned()).toBe(true);
} finally {
write.mockRestore();
}
});
1 change: 1 addition & 0 deletions test/options-check/file.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = 'file';
39 changes: 39 additions & 0 deletions test/options-check/options-check-loader.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
const schema = {
type: 'object',
properties: { name: { type: 'string' } },
additionalProperties: false,
};

const titledSchema = { ...schema, title: 'Titled Loader query' };

const trusting = (value) => value.trusted === true;

const modes = {
// the check in the configuration's place
check: (context) => context.getOptions(schema, trusting),
// the check last, after the configuration
configuration: (context) =>
context.getOptions(
schema,
{ name: 'Named Loader', baseDataPath: 'query' },
trusting,
),
// a function returning the schema, read only when the check fails
lazy: (context) =>
context.getOptions(() => {
if (context.getOptions().trusted === true) {
throw new Error('the schema was read although the check passed');
}

return schema;
}, trusting),
title: (context) => context.getOptions(titledSchema),
// a check that rejects what the schema accepts
stale: (context) => context.getOptions(schema, () => false),
};

module.exports = function optionsCheckLoader() {
const options = modes[this.resourceQuery.slice(1)](this);

return `module.exports = ${JSON.stringify(options)};`;
};
Loading