Socket
Socket
Sign inDemoInstall

webpack

Package Overview
Dependencies
77
Maintainers
4
Versions
834
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 5.81.0 to 5.82.0

15

bin/webpack.js

@@ -81,4 +81,15 @@ #!/usr/bin/env node

const pkg = require(pkgPath);
// eslint-disable-next-line node/no-missing-require
require(path.resolve(path.dirname(pkgPath), pkg.bin[cli.binName]));
if (pkg.type === "module" || /\.mjs/i.test(pkg.bin[cli.binName])) {
// eslint-disable-next-line node/no-unsupported-features/es-syntax
import(path.resolve(path.dirname(pkgPath), pkg.bin[cli.binName])).catch(
error => {
console.error(error);
process.exitCode = 1;
}
);
} else {
// eslint-disable-next-line node/no-missing-require
require(path.resolve(path.dirname(pkgPath), pkg.bin[cli.binName]));
}
};

@@ -85,0 +96,0 @@

@@ -37,2 +37,4 @@ /*

let lastClearedIdentifier;
// Avoid coverage problems due indirect changes
/* istanbul ignore next */
for (const [identifier, entry] of oldCache) {

@@ -39,0 +41,0 @@ if (entry.until > generation) break;

@@ -964,2 +964,3 @@ /*

);
D(trustedTypes, "onPolicyCreationFailure", "stop");
}

@@ -966,0 +967,0 @@

@@ -35,2 +35,3 @@ /*

const source = new ReplaceSource(originalSource);
/** @type {InitFragment[]} */
const initFragments = [];

@@ -55,2 +56,5 @@ const cssExports = new Map();

/**
* @param {Dependency} dependency dependency
*/
const handleDependency = dependency => {

@@ -57,0 +61,0 @@ const constructor = /** @type {new (...args: any[]) => Dependency} */ (

@@ -17,2 +17,3 @@ /*

/** @typedef {import("../Chunk")} Chunk */
/** @typedef {import("../Compilation").RuntimeRequirementsContext} RuntimeRequirementsContext */

@@ -48,7 +49,9 @@ /**

constructor(runtimeRequirements, runtimeOptions) {
/**
* @param {Set<string>} runtimeRequirements runtime requirements
*/
constructor(runtimeRequirements) {
super("css loading", 10);
this._runtimeRequirements = runtimeRequirements;
this.runtimeOptions = runtimeOptions;
}

@@ -81,6 +84,9 @@

hasCssMatcher !== false;
/** @type {boolean} */
const withHmr = _runtimeRequirements.has(
RuntimeGlobals.hmrDownloadUpdateHandlers
);
/** @type {Set<number | string | null>} */
const initialChunkIdsWithCss = new Set();
/** @type {Set<number | string | null>} */
const initialChunkIdsWithoutCss = new Set();

@@ -126,2 +132,3 @@ for (const c of chunk.getAllInitialChunks()) {

/** @type {(str: string) => number} */
const cc = str => str.charCodeAt(0);

@@ -128,0 +135,0 @@

@@ -18,2 +18,3 @@ /*

const SelfModuleFactory = require("../SelfModuleFactory");
const WebpackError = require("../WebpackError");
const CssExportDependency = require("../dependencies/CssExportDependency");

@@ -36,5 +37,10 @@ const CssImportDependency = require("../dependencies/CssImportDependency");

/** @typedef {import("../../declarations/WebpackOptions").CssExperimentOptions} CssExperimentOptions */
/** @typedef {import("../../declarations/WebpackOptions").Output} OutputOptions */
/** @typedef {import("../Chunk")} Chunk */
/** @typedef {import("../ChunkGraph")} ChunkGraph */
/** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */
/** @typedef {import("../Compilation")} Compilation */
/** @typedef {import("../Compiler")} Compiler */
/** @typedef {import("../Module")} Module */
/** @typedef {import("../util/memoize")} Memoize */

@@ -70,2 +76,7 @@ const getCssLoadingRuntimeModule = memoize(() =>

/**
* @param {string} str string
* @param {boolean=} omitOptionalUnderscore if true, optional underscore is not added
* @returns {string} escaped string
*/
const escapeCss = (str, omitOptionalUnderscore) => {

@@ -176,8 +187,52 @@ const escaped = `${str}`.replace(

return new CssModule({
...createData,
cssLayer: dependency.layer,
supports: dependency.supports,
media: dependency.media
});
if (dependency instanceof CssImportDependency) {
const parent =
/** @type {CssModule} */
(compilation.moduleGraph.getParentModule(dependency));
if (parent instanceof CssModule) {
/** @type {import("../CssModule").Inheritance | undefined} */
let inheritance;
if (
(parent.cssLayer !== null &&
parent.cssLayer !== undefined) ||
parent.supports ||
parent.media
) {
if (!inheritance) {
inheritance = [];
}
inheritance.push([
parent.cssLayer,
parent.supports,
parent.media
]);
}
if (parent.inheritance) {
if (!inheritance) {
inheritance = [];
}
inheritance.push(...parent.inheritance);
}
return new CssModule({
...createData,
cssLayer: dependency.layer,
supports: dependency.supports,
media: dependency.media,
inheritance
});
}
return new CssModule({
...createData,
cssLayer: dependency.layer,
supports: dependency.supports,
media: dependency.media
});
}
}

@@ -226,2 +281,3 @@

/** @type {CssModule[] | undefined} */
const modules = orderedCssModulesPerChunk.get(chunk);

@@ -283,5 +339,12 @@ if (modules !== undefined) {

/**
* @param {Chunk} chunk chunk
* @param {Iterable<Module>} modules unordered modules
* @param {Compilation} compilation compilation
* @returns {Module[]} ordered modules
*/
getModulesInOrder(chunk, modules, compilation) {
if (!modules) return [];
/** @type {Module[]} */
const modulesList = [...modules];

@@ -320,2 +383,3 @@

/** @type {Module[]} */
const finalModules = [];

@@ -330,2 +394,3 @@

}
/** @type {Module} */
let selectedModule = list[list.length - 1];

@@ -356,9 +421,8 @@ let hasFailed = undefined;

compilation.warnings.push(
new Error(
`chunk ${
chunk.name || chunk.id
}\nConflicting order between ${hasFailed.readableIdentifier(
new WebpackError(
`chunk ${chunk.name || chunk.id}\nConflicting order between ${
/** @type {Module} */
(hasFailed).readableIdentifier(compilation.requestShortener)
} and ${selectedModule.readableIdentifier(
compilation.requestShortener
)} and ${selectedModule.readableIdentifier(
compilation.requestShortener
)}`

@@ -368,3 +432,3 @@ )

}
selectedModule = hasFailed;
selectedModule = /** @type {Module} */ (hasFailed);
}

@@ -387,2 +451,8 @@ // Insert the selected module into the final modules list

/**
* @param {Chunk} chunk chunk
* @param {ChunkGraph} chunkGraph chunk graph
* @param {Compilation} compilation compilation
* @returns {Module[]} ordered css modules
*/
getOrderedChunkCssModules(chunk, chunkGraph, compilation) {

@@ -411,2 +481,11 @@ return [

/**
* @param {Object} options options
* @param {string | undefined} options.uniqueName unique name
* @param {Chunk} options.chunk chunk
* @param {ChunkGraph} options.chunkGraph chunk graph
* @param {CodeGenerationResults} options.codeGenerationResults code generation results
* @param {CssModule[]} options.modules ordered css modules
* @returns {Source} generated source
*/
renderChunk({

@@ -420,2 +499,3 @@ uniqueName,

const source = new ConcatSource();
/** @type {string[]} */
const metaData = [];

@@ -430,25 +510,37 @@ for (const module of modules) {

if (module.media) {
moduleSource = new ConcatSource(
`@media ${module.media} {\n`,
new PrefixSource("\t", moduleSource),
"}"
);
}
let inheritance = [[module.cssLayer, module.supports, module.media]];
if (module.supports) {
moduleSource = new ConcatSource(
`@supports (${module.supports}) {\n`,
new PrefixSource("\t", moduleSource),
"}"
);
if (module.inheritance) {
inheritance.push(...module.inheritance);
}
// Layer can be anonymous
if (module.cssLayer !== undefined && module.cssLayer !== null) {
moduleSource = new ConcatSource(
`@layer${module.cssLayer ? ` (${module.cssLayer})` : ""} {\n`,
new PrefixSource("\t", moduleSource),
"}"
);
for (let i = 0; i < inheritance.length; i++) {
const layer = inheritance[i][0];
const supports = inheritance[i][1];
const media = inheritance[i][2];
if (media) {
moduleSource = new ConcatSource(
`@media ${media} {\n`,
new PrefixSource("\t", moduleSource),
"}\n"
);
}
if (supports) {
moduleSource = new ConcatSource(
`@supports (${supports}) {\n`,
new PrefixSource("\t", moduleSource),
"}\n"
);
}
// Layer can be anonymous
if (layer !== undefined && layer !== null) {
moduleSource = new ConcatSource(
`@layer${layer ? ` ${layer}` : ""} {\n`,
new PrefixSource("\t", moduleSource),
"}\n"
);
}
}

@@ -460,2 +552,3 @@

}
/** @type {Map<string, string> | undefined} */
const exports =

@@ -500,2 +593,7 @@ codeGenResult.data && codeGenResult.data.get("css-exports");

/**
* @param {Chunk} chunk chunk
* @param {OutputOptions} outputOptions output options
* @returns {Chunk["cssFilenameTemplate"] | OutputOptions["cssFilename"] | OutputOptions["cssChunkFilename"]} used filename template
*/
static getChunkFilenameTemplate(chunk, outputOptions) {

@@ -511,2 +609,7 @@ if (chunk.cssFilenameTemplate) {

/**
* @param {Chunk} chunk chunk
* @param {ChunkGraph} chunkGraph chunk graph
* @returns {boolean} true, when the chunk has css
*/
static chunkHasCss(chunk, chunkGraph) {

@@ -513,0 +616,0 @@ return (

224

lib/css/CssParser.js

@@ -8,3 +8,5 @@ /*

const ModuleDependencyWarning = require("../ModuleDependencyWarning");
const Parser = require("../Parser");
const WebpackError = require("../WebpackError");
const ConstDependency = require("../dependencies/ConstDependency");

@@ -38,2 +40,7 @@ const CssExportDependency = require("../dependencies/CssExportDependency");

/**
* @param {string} str url string
* @param {boolean} isString is url wrapped in quotes
* @returns {string} normalized url
*/
const normalizeUrl = (str, isString) => {

@@ -76,2 +83,5 @@ // Remove extra spaces and newlines:

class LocConverter {
/**
* @param {string} input input
*/
constructor(input) {

@@ -84,2 +94,6 @@ this._input = input;

/**
* @param {number} pos position
* @returns {LocConverter} location converter
*/
get(pos) {

@@ -117,23 +131,5 @@ if (this.pos !== pos) {

const CSS_MODE_AT_IMPORT_EXPECT_LAYER_OR_SUPPORTS_OR_MEDIA = 4;
const CSS_MODE_AT_OTHER = 5;
const CSS_MODE_AT_IMPORT_INVALID = 5;
const CSS_MODE_AT_NAMESPACE_INVALID = 6;
const explainMode = mode => {
switch (mode) {
case CSS_MODE_TOP_LEVEL:
return "parsing top level css";
case CSS_MODE_IN_RULE:
return "parsing css rule content (global)";
case CSS_MODE_IN_LOCAL_RULE:
return "parsing css rule content (local)";
case CSS_MODE_AT_IMPORT_EXPECT_URL:
return "parsing @import (expecting url)";
case CSS_MODE_AT_IMPORT_EXPECT_LAYER_OR_SUPPORTS_OR_MEDIA:
return "parsing @import (expecting optionally layer, supports or media query)";
case CSS_MODE_AT_OTHER:
return "parsing at-rule";
default:
return mode;
}
};
class CssParser extends Parser {

@@ -152,2 +148,21 @@ constructor({

/**
* @param {ParserState} state parser state
* @param {string} message warning message
* @param {LocConverter} locConverter location converter
* @param {number} start start offset
* @param {number} end end offset
*/
_emitWarning(state, message, locConverter, start, end) {
const { line: sl, column: sc } = locConverter.get(start);
const { line: el, column: ec } = locConverter.get(end);
state.current.addWarning(
new ModuleDependencyWarning(state.module, new WebpackError(message), {
start: { line: sl, column: sc },
end: { line: el, column: ec }
})
);
}
/**
* @param {string | Buffer | PreparsedAst} source the source to parse

@@ -172,7 +187,14 @@ * @param {ParserState} state the parser state

const locConverter = new LocConverter(source);
/** @type {number} */
let mode = CSS_MODE_TOP_LEVEL;
/** @type {number} */
let modeNestingLevel = 0;
/** @type {boolean} */
let allowImportAtRule = true;
let modeData = undefined;
/** @type {string | boolean | undefined} */
let singleClassSelector = undefined;
/** @type {[number, number] | undefined} */
let lastIdentifier = undefined;
/** @type {boolean} */
let awaitRightParenthesis = false;

@@ -186,14 +208,2 @@ /** @type [string, number, number][] */

(this.defaultMode === "local" && modeData === undefined);
const eatWhiteLine = (input, pos) => {
for (;;) {
const cc = input.charCodeAt(pos);
if (cc === 32 || cc === 9) {
pos++;
continue;
}
if (cc === 10) pos++;
break;
}
return pos;
};
const eatUntil = chars => {

@@ -249,6 +259,12 @@ const charCodes = Array.from({ length: chars.length }, (_, i) =>

const cc = input.charCodeAt(pos);
if (cc !== CC_LEFT_CURLY)
throw new Error(
`Unexpected ${input[pos]} at ${pos} during parsing of ':export' (expected '{')`
if (cc !== CC_LEFT_CURLY) {
this._emitWarning(
state,
`Unexpected '${input[pos]}' at ${pos} during parsing of ':export' (expected '{')`,
locConverter,
pos,
pos
);
return pos;
}
pos++;

@@ -265,5 +281,10 @@ pos = walkCssTokens.eatWhitespaceAndComments(input, pos);

if (input.charCodeAt(pos) !== CC_COLON) {
throw new Error(
`Unexpected ${input[pos]} at ${pos} during parsing of export name in ':export' (expected ':')`
this._emitWarning(
state,
`Unexpected '${input[pos]}' at ${pos} during parsing of export name in ':export' (expected ':')`,
locConverter,
start,
pos
);
return pos;
}

@@ -284,5 +305,10 @@ pos++;

} else if (cc !== CC_RIGHT_CURLY) {
throw new Error(
`Unexpected ${input[pos]} at ${pos} during parsing of export value in ':export' (expected ';' or '}')`
this._emitWarning(
state,
`Unexpected '${input[pos]}' at ${pos} during parsing of export value in ':export' (expected ';' or '}')`,
locConverter,
start,
pos
);
return pos;
}

@@ -297,3 +323,3 @@ const dep = new CssExportDependency(name, value);

if (pos === input.length) return pos;
pos = eatWhiteLine(input, pos);
pos = walkCssTokens.eatWhiteLine(input, pos);
return pos;

@@ -354,10 +380,9 @@ };

mode !== CSS_MODE_AT_IMPORT_EXPECT_URL &&
mode !== CSS_MODE_AT_IMPORT_EXPECT_LAYER_OR_SUPPORTS_OR_MEDIA
mode !== CSS_MODE_AT_IMPORT_EXPECT_LAYER_OR_SUPPORTS_OR_MEDIA &&
mode !== CSS_MODE_AT_IMPORT_INVALID &&
mode !== CSS_MODE_AT_NAMESPACE_INVALID
);
},
url: (input, start, end, contentStart, contentEnd, isString) => {
let value = normalizeUrl(
input.slice(contentStart, contentEnd),
isString
);
url: (input, start, end, contentStart, contentEnd) => {
let value = normalizeUrl(input.slice(contentStart, contentEnd), false);
switch (mode) {

@@ -374,9 +399,10 @@ case CSS_MODE_AT_IMPORT_EXPECT_URL: {

}
// Do not parse URLs in import between rules
case CSS_MODE_AT_NAMESPACE_INVALID:
case CSS_MODE_AT_IMPORT_INVALID: {
break;
}
default: {
if (
// Ignore `url(#highlight)` URLs
/^#/.test(value) ||
// Ignore `url()`, `url('')` and `url("")`, they are valid by spec
value.length === 0
) {
// Ignore `url()`, `url('')` and `url("")`, they are valid by spec
if (value.length === 0) {
break;

@@ -425,8 +451,4 @@ }

if (
// Ignore `url(#highlight)` URLs
/^#/.test(value) ||
// Ignore `url()`, `url('')` and `url("")`, they are valid by spec
value.length === 0
) {
// Ignore `url()`, `url('')` and `url("")`, they are valid by spec
if (value.length === 0) {
break;

@@ -454,10 +476,24 @@ }

if (name === "@namespace") {
throw new Error("@namespace is not supported in bundled CSS");
}
if (name === "@import") {
if (mode !== CSS_MODE_TOP_LEVEL) {
throw new Error(
`Unexpected @import at ${start} during ${explainMode(mode)}`
mode = CSS_MODE_AT_NAMESPACE_INVALID;
this._emitWarning(
state,
"@namespace is not supported in bundled CSS",
locConverter,
start,
end
);
return end;
} else if (name === "@import") {
if (!allowImportAtRule) {
mode = CSS_MODE_AT_IMPORT_INVALID;
this._emitWarning(
state,
"Any @import rules must precede all other rules",
locConverter,
start,
end
);
return end;
}
mode = CSS_MODE_AT_IMPORT_EXPECT_URL;

@@ -472,4 +508,6 @@ modeData = {

};
}
if (OPTIONALLY_VENDOR_PREFIXED_KEYFRAMES_AT_RULE.test(name)) {
} else if (
isTopLevelLocal() &&
OPTIONALLY_VENDOR_PREFIXED_KEYFRAMES_AT_RULE.test(name)
) {
let pos = end;

@@ -479,2 +517,14 @@ pos = walkCssTokens.eatWhitespaceAndComments(input, pos);

const [newPos, name] = eatText(input, pos, eatKeyframes);
if (newPos === input.length) return newPos;
if (input.charCodeAt(newPos) !== CC_LEFT_CURLY) {
this._emitWarning(
state,
`Unexpected '${input[newPos]}' at ${newPos} during parsing of @keyframes (expected '{')`,
locConverter,
start,
end
);
return newPos;
}
const { line: sl, column: sc } = locConverter.get(pos);

@@ -486,13 +536,7 @@ const { line: el, column: ec } = locConverter.get(newPos);

pos = newPos;
if (pos === input.length) return pos;
if (input.charCodeAt(pos) !== CC_LEFT_CURLY) {
throw new Error(
`Unexpected ${input[pos]} at ${pos} during parsing of @keyframes (expected '{')`
);
}
mode = CSS_MODE_IN_LOCAL_RULE;
modeNestingLevel = 1;
return pos + 1;
}
if (name === "@media" || name === "@supports") {
} else if (name === "@media" || name === "@supports") {
// TODO handle nested CSS syntax
let pos = end;

@@ -503,5 +547,10 @@ const [newPos] = eatText(input, pos, eatAtRuleNested);

if (input.charCodeAt(pos) !== CC_LEFT_CURLY) {
throw new Error(
`Unexpected ${input[pos]} at ${pos} during parsing of @media or @supports (expected '{')`
this._emitWarning(
state,
`Unexpected ${input[pos]} at ${pos} during parsing of @media or @supports (expected '{')`,
locConverter,
start,
pos
);
return pos;
}

@@ -514,11 +563,25 @@ return pos + 1;

switch (mode) {
case CSS_MODE_AT_IMPORT_EXPECT_URL:
throw new Error(`Expected URL for @import at ${start}`);
case CSS_MODE_AT_IMPORT_EXPECT_URL: {
this._emitWarning(
state,
`Expected URL for @import at ${start}`,
locConverter,
start,
end
);
return end;
}
case CSS_MODE_AT_IMPORT_EXPECT_LAYER_OR_SUPPORTS_OR_MEDIA: {
if (modeData.url === undefined) {
throw new Error(
`Expected URL for @import at ${modeData.atRuleStart}`
this._emitWarning(
state,
`Expected URL for @import at ${modeData.atRuleStart}`,
locConverter,
modeData.atRuleStart,
modeData.lastPos
);
return end;
}
const semicolonPos = end;
end = walkCssTokens.eatWhiteLine(input, end + 1);
const { line: sl, column: sc } = locConverter.get(

@@ -569,2 +632,3 @@ modeData.atRuleStart

case CSS_MODE_TOP_LEVEL:
allowImportAtRule = false;
mode = isTopLevelLocal()

@@ -571,0 +635,0 @@ ? CSS_MODE_IN_LOCAL_RULE

@@ -79,2 +79,6 @@ /*

/**
* @param {number} cc char code
* @returns {boolean} true, if cc is a newline
*/
const _isNewLine = cc => {

@@ -88,2 +92,3 @@ return (

const consumeSpace = (input, pos, callbacks) => {
/** @type {number} */
let cc;

@@ -97,12 +102,32 @@ do {

const _isWhiteSpace = cc => {
/**
* @param {number} cc char code
* @returns {boolean} true, if cc is a newline
*/
const _isNewline = cc => {
return (
cc === CC_LINE_FEED ||
cc === CC_CARRIAGE_RETURN ||
cc === CC_FORM_FEED ||
cc === CC_TAB ||
cc === CC_SPACE
cc === CC_LINE_FEED || cc === CC_CARRIAGE_RETURN || cc === CC_FORM_FEED
);
};
/**
* @param {number} cc char code
* @returns {boolean} true, if cc is a space (U+0009 CHARACTER TABULATION or U+0020 SPACE)
*/
const _isSpace = cc => {
return cc === CC_TAB || cc === CC_SPACE;
};
/**
* @param {number} cc char code
* @returns {boolean} true, if cc is a whitespace
*/
const _isWhiteSpace = cc => {
return _isNewline(cc) || _isSpace(cc);
};
/**
* @param {number} cc char code
* @returns {boolean} true, if cc is a start code point of an identifier
*/
const _isIdentStartCodePoint = cc => {

@@ -151,5 +176,5 @@ return (

/** @type {function(number): CharHandler} */
const consumeString = end => (input, pos, callbacks) => {
const consumeString = quote_cc => (input, pos, callbacks) => {
const start = pos;
pos = _consumeString(input, pos, end);
pos = _consumeString(input, pos, quote_cc);
if (callbacks.string !== undefined) {

@@ -161,3 +186,9 @@ pos = callbacks.string(input, start, pos);

const _consumeString = (input, pos, end) => {
/**
* @param {string} input input
* @param {number} pos position
* @param {number} quote_cc quote char code
* @returns {number} new position
*/
const _consumeString = (input, pos, quote_cc) => {
pos++;

@@ -167,3 +198,3 @@ for (;;) {

const cc = input.charCodeAt(pos);
if (cc === end) return pos + 1;
if (cc === quote_cc) return pos + 1;
if (_isNewLine(cc)) {

@@ -185,2 +216,6 @@ // bad string

/**
* @param {number} cc char code
* @returns {boolean} is identifier start code
*/
const _isIdentifierStartCode = cc => {

@@ -195,2 +230,7 @@ return (

/**
* @param {number} first first code point
* @param {number} second second code point
* @returns {boolean} true if two code points are a valid escape
*/
const _isTwoCodePointsAreValidEscape = (first, second) => {

@@ -202,2 +242,6 @@ if (first !== CC_REVERSE_SOLIDUS) return false;

/**
* @param {number} cc char code
* @returns {boolean} is digit
*/
const _isDigit = cc => {

@@ -207,2 +251,7 @@ return cc >= CC_0 && cc <= CC_9;

/**
* @param {string} input input
* @param {number} pos position
* @returns {boolean} true, if input at pos starts an identifier
*/
const _startsIdentifier = (input, pos) => {

@@ -233,3 +282,3 @@ const cc = input.charCodeAt(pos);

if (callbacks.isSelector(input, pos) && _startsIdentifier(input, pos)) {
pos = _consumeIdentifier(input, pos);
pos = _consumeIdentifier(input, pos, callbacks);
if (callbacks.id !== undefined) {

@@ -258,3 +307,3 @@ return callbacks.id(input, start, pos);

} else {
pos = _consumeIdentifier(input, pos);
pos = _consumeIdentifier(input, pos, callbacks);
if (callbacks.identifier !== undefined) {

@@ -268,3 +317,3 @@ return callbacks.identifier(input, start, pos);

if (_isNewLine(cc)) return pos;
pos = _consumeIdentifier(input, pos);
pos = _consumeIdentifier(input, pos, callbacks);
if (callbacks.identifier !== undefined) {

@@ -288,3 +337,3 @@ return callbacks.identifier(input, start, pos);

return pos;
pos = _consumeIdentifier(input, pos);
pos = _consumeIdentifier(input, pos, callbacks);
if (callbacks.class !== undefined) return callbacks.class(input, start, pos);

@@ -296,5 +345,6 @@ return pos;

const consumeNumericToken = (input, pos, callbacks) => {
pos = _consumeNumber(input, pos);
pos = _consumeNumber(input, pos, callbacks);
if (pos === input.length) return pos;
if (_startsIdentifier(input, pos)) return _consumeIdentifier(input, pos);
if (_startsIdentifier(input, pos))
return _consumeIdentifier(input, pos, callbacks);
const cc = input.charCodeAt(pos);

@@ -308,3 +358,3 @@ if (cc === CC_PERCENTAGE) return pos + 1;

const start = pos;
pos = _consumeIdentifier(input, pos);
pos = _consumeIdentifier(input, pos, callbacks);
if (

@@ -330,3 +380,3 @@ pos !== input.length &&

const start = pos;
pos = _consumeIdentifier(input, pos);
pos = _consumeIdentifier(input, pos, callbacks);
const nextPos = pos + 1;

@@ -351,2 +401,3 @@ if (

const contentStart = pos;
/** @type {number} */
let contentEnd;

@@ -401,3 +452,3 @@ for (;;) {

return pos;
pos = _consumeIdentifier(input, pos);
pos = _consumeIdentifier(input, pos, callbacks);
let cc = input.charCodeAt(pos);

@@ -471,2 +522,3 @@ if (cc === CC_LEFT_PARENTHESIS) {

/** @type {CharHandler} */
const _consumeIdentifier = (input, pos) => {

@@ -491,2 +543,3 @@ for (;;) {

/** @type {CharHandler} */
const _consumeNumber = (input, pos) => {

@@ -550,2 +603,3 @@ pos++;

/** @type {CharHandler} */
const consumeAt = (input, pos, callbacks) => {

@@ -556,3 +610,3 @@ const start = pos;

if (_startsIdentifier(input, pos)) {
pos = _consumeIdentifier(input, pos);
pos = _consumeIdentifier(input, pos, callbacks);
if (callbacks.atKeyword !== undefined) {

@@ -723,1 +777,23 @@ pos = callbacks.atKeyword(input, start, pos);

};
/**
* @param {string} input input
* @param {number} pos position
* @returns {number} position after whitespace
*/
module.exports.eatWhiteLine = (input, pos) => {
for (;;) {
const cc = input.charCodeAt(pos);
if (_isSpace(cc)) {
pos++;
continue;
}
if (_isNewLine(cc)) pos++;
// For `\r\n`
if (cc === CC_CARRIAGE_RETURN && input.charCodeAt(pos + 1) === CC_LINE_FEED)
pos++;
break;
}
return pos;
};

@@ -17,4 +17,10 @@ /*

/** @typedef {NormalModuleCreateData & { cssLayer: string|undefined|null, supports: string|undefined|null, media: string|undefined|null }} CSSModuleCreateData */
/** @typedef {string|undefined} CssLayer */
/** @typedef {string|undefined} Supports */
/** @typedef {string|undefined} Media */
/** @typedef {[CssLayer?, Supports?, Media?]} InheritanceItem */
/** @typedef {Array<InheritanceItem>} Inheritance */
/** @typedef {NormalModuleCreateData & { cssLayer: CssLayer|null, supports: Supports|null, media: Media|null, inheritance: Inheritance|null }} CSSModuleCreateData */
class CssModule extends NormalModule {

@@ -31,2 +37,3 @@ /**

this.media = options.media;
this.inheritance = options.inheritance;
}

@@ -52,2 +59,13 @@

if (this.inheritance) {
const inheritance = this.inheritance.map(
(item, index) =>
`inheritance_${index}|${item[0] || ""}|${item[1] || ""}|${
item[2] || ""
}`
);
identifier += `|${inheritance.join("|")}`;
}
return identifier;

@@ -63,7 +81,17 @@ }

return `css ${readableIdentifier}${
this.cssLayer ? ` (layer ${this.cssLayer || ""})` : ""
}${this.supports ? ` (supports ${this.supports || ""})` : ""}${
this.media ? ` (media ${this.media || ""})` : ""
}`;
let identifier = `css ${readableIdentifier}`;
if (this.cssLayer) {
identifier += ` (layer: ${this.cssLayer})`;
}
if (this.supports) {
identifier += ` (supports: ${this.supports})`;
}
if (this.media) {
identifier += ` (media: ${this.media})`;
}
return identifier;
}

@@ -84,2 +112,3 @@

this.media = m.media;
this.inheritance = m.inheritance;
}

@@ -95,2 +124,3 @@

write(this.media);
write(this.inheritance);
super.serialize(context);

@@ -123,3 +153,4 @@ }

supports: null,
media: null
media: null,
inheritance: null
});

@@ -138,2 +169,3 @@ obj.deserialize(context);

this.media = read();
this.inheritance = read();
super.deserialize(context);

@@ -140,0 +172,0 @@ }

@@ -103,2 +103,4 @@ /*

const endTime = hrtime[0] * 1000000 + Math.round(hrtime[1] / 1000);
// Avoid coverage problems due indirect changes
/* istanbul ignore next */
if (profile.startTime < this._startTime || profile.endTime > endTime) {

@@ -105,0 +107,0 @@ // In some cases timestamps mismatch and we need to adjust them

@@ -162,2 +162,3 @@ /*

if (
typeof rootInfo === "string" ||
!rootInfo ||

@@ -164,0 +165,0 @@ !rootInfo.tagInfo ||

@@ -63,6 +63,7 @@ /*

this.postfix = undefined;
/** @type {BasicEvaluatedExpression[]} */
this.wrappedInnerExpressions = undefined;
/** @type {string | VariableInfoInterface | undefined} */
this.identifier = undefined;
/** @type {VariableInfoInterface} */
/** @type {string | VariableInfoInterface} */
this.rootInfo = undefined;

@@ -226,2 +227,6 @@ /** @type {() => string[]} */

/**
* Creates a boolean representation of this evaluated expression.
* @returns {boolean | undefined} true: truthy, false: falsy, undefined: unknown
*/
asBool() {

@@ -252,2 +257,6 @@ if (this.truthy) return true;

/**
* Creates a nullish coalescing representation of this evaluated expression.
* @returns {boolean | undefined} true: nullish, false: not nullish, undefined: unknown
*/
asNullish() {

@@ -273,2 +282,6 @@ const nullish = this.isNullish();

/**
* Creates a string representation of this evaluated expression.
* @returns {string | undefined} the string representation or undefined if not possible
*/
asString() {

@@ -323,2 +336,7 @@ if (this.isBoolean()) return `${this.bool}`;

/**
* Set's the value of this expression to a number
* @param {number} number number to set
* @returns {this} this
*/
setNumber(number) {

@@ -331,2 +349,7 @@ this.type = TypeNumber;

/**
* Set's the value of this expression to a BigInt
* @param {bigint} bigint bigint to set
* @returns {this} this
*/
setBigInt(bigint) {

@@ -339,2 +362,7 @@ this.type = TypeBigInt;

/**
* Set's the value of this expression to a boolean
* @param {boolean} bool boolean to set
* @returns {this} this
*/
setBoolean(bool) {

@@ -347,2 +375,7 @@ this.type = TypeBoolean;

/**
* Set's the value of this expression to a regular expression
* @param {RegExp} regExp regular expression to set
* @returns {this} this
*/
setRegExp(regExp) {

@@ -355,2 +388,11 @@ this.type = TypeRegExp;

/**
* Set's the value of this expression to a particular identifier and its members.
*
* @param {string | VariableInfoInterface} identifier identifier to set
* @param {string | VariableInfoInterface} rootInfo root info
* @param {() => string[]} getMembers members
* @param {() => boolean[]=} getMembersOptionals optional members
* @returns {this} this
*/
setIdentifier(identifier, rootInfo, getMembers, getMembersOptionals) {

@@ -366,2 +408,10 @@ this.type = TypeIdentifier;

/**
* Wraps an array of expressions with a prefix and postfix expression.
*
* @param {BasicEvaluatedExpression | null} prefix Expression to be added before the innerExpressions
* @param {BasicEvaluatedExpression} postfix Expression to be added after the innerExpressions
* @param {BasicEvaluatedExpression[]} innerExpressions Expressions to be wrapped
* @returns {this} this
*/
setWrapped(prefix, postfix, innerExpressions) {

@@ -376,2 +426,8 @@ this.type = TypeWrapped;

/**
* Stores the options of a conditional expression.
*
* @param {BasicEvaluatedExpression[]} options optional (consequent/alternate) expressions to be set
* @returns {this} this
*/
setOptions(options) {

@@ -384,2 +440,8 @@ this.type = TypeConditional;

/**
* Adds options to a conditional expression.
*
* @param {BasicEvaluatedExpression[]} options optional (consequent/alternate) expressions to be added
* @returns {this} this
*/
addOptions(options) {

@@ -397,2 +459,8 @@ if (!this.options) {

/**
* Set's the value of this expression to an array of expressions.
*
* @param {BasicEvaluatedExpression[]} items expressions to set
* @returns {this} this
*/
setItems(items) {

@@ -405,2 +473,8 @@ this.type = TypeArray;

/**
* Set's the value of this expression to an array of strings.
*
* @param {string[]} array array to set
* @returns {this} this
*/
setArray(array) {

@@ -413,2 +487,11 @@ this.type = TypeConstArray;

/**
* Set's the value of this expression to a processed/unprocessed template string. Used
* for evaluating TemplateLiteral expressions in the JavaScript Parser.
*
* @param {BasicEvaluatedExpression[]} quasis template string quasis
* @param {BasicEvaluatedExpression[]} parts template string parts
* @param {"cooked" | "raw"} kind template string kind
* @returns {this} this
*/
setTemplateString(quasis, parts, kind) {

@@ -436,2 +519,8 @@ this.type = TypeTemplateString;

/**
* Set's the value of the expression to nullish.
*
* @param {boolean} value true, if the expression is nullish
* @returns {this} this
*/
setNullish(value) {

@@ -445,2 +534,8 @@ this.nullish = value;

/**
* Set's the range for the expression.
*
* @param {[number, number]} range range to set
* @returns {this} this
*/
setRange(range) {

@@ -451,2 +546,8 @@ this.range = range;

/**
* Set whether or not the expression has side effects.
*
* @param {boolean} sideEffects true, if the expression has side effects
* @returns {this} this
*/
setSideEffects(sideEffects = true) {

@@ -457,2 +558,8 @@ this.sideEffects = sideEffects;

/**
* Set the expression node for the expression.
*
* @param {EsTreeNode} expression expression
* @returns {this} this
*/
setExpression(expression) {

@@ -459,0 +566,0 @@ this.expression = expression;

@@ -10,5 +10,15 @@ /*

/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/** @typedef {import("../util/Hash")} Hash */
/** @typedef {import("./JsonModulesPlugin").RawJsonData} RawJsonData */
class JsonData {
/**
* @param {Buffer | RawJsonData} data JSON data
*/
constructor(data) {
/** @type {Buffer | undefined} */
this._buffer = undefined;
/** @type {RawJsonData | undefined} */
this._data = undefined;

@@ -22,2 +32,5 @@ if (Buffer.isBuffer(data)) {

/**
* @returns {RawJsonData|undefined} Raw JSON data
*/
get() {

@@ -30,2 +43,6 @@ if (this._data === undefined && this._buffer !== undefined) {

/**
* @param {Hash} hash hash to be updated
* @returns {Hash} the updated hash
*/
updateHash(hash) {

@@ -41,2 +58,6 @@ if (this._buffer === undefined && this._data !== undefined) {

register(JsonData, "webpack/lib/json/JsonData", null, {
/**
* @param {JsonData} obj JSONData object
* @param {ObjectSerializerContext} context context
*/
serialize(obj, { write }) {

@@ -48,2 +69,6 @@ if (obj._buffer === undefined && obj._data !== undefined) {

},
/**
* @param {ObjectDeserializerContext} context context
* @returns {JsonData} deserialized JSON data
*/
deserialize({ read }) {

@@ -50,0 +75,0 @@ return new JsonData(read());

@@ -20,3 +20,9 @@ /*

/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
/** @typedef {import("./JsonData")} JsonData */
/** @typedef {import("./JsonModulesPlugin").RawJsonData} RawJsonData */
/**
* @param {RawJsonData} data Raw JSON data
* @returns {undefined|string} stringified data
*/
const stringifySafe = data => {

@@ -34,6 +40,6 @@ const stringified = JSON.stringify(data);

/**
* @param {Object} data data (always an object or array)
* @param {RawJsonData} data Raw JSON data (always an object or array)
* @param {ExportsInfo} exportsInfo exports info
* @param {RuntimeSpec} runtime the runtime
* @returns {Object} reduced data
* @returns {RawJsonData} reduced data
*/

@@ -50,2 +56,3 @@ const createObjectForExportsInfo = (data, exportsInfo, runtime) => {

/** @type {any} */
let value;

@@ -92,2 +99,3 @@ if (used === UsageState.OnlyPropertiesUsed && exportInfo.exportsInfo) {

);
/** @type {number} */
const generatedLength =

@@ -123,3 +131,4 @@ arrayLengthWhenUsed !== undefined

getSize(module, type) {
let data =
/** @type {RawJsonData | undefined} */
const data =
module.buildInfo &&

@@ -156,2 +165,3 @@ module.buildInfo.jsonData &&

) {
/** @type {RawJsonData | undefined} */
const data =

@@ -169,2 +179,3 @@ module.buildInfo &&

const exportsInfo = moduleGraph.getExportsInfo(module);
/** @type {RawJsonData} */
let finalJson =

@@ -182,2 +193,3 @@ typeof data === "object" &&

: jsonStr;
/** @type {string} */
let content;

@@ -184,0 +196,0 @@ if (concatenationScope) {

@@ -14,2 +14,3 @@ /*

/** @typedef {import("../Compiler")} Compiler */
/** @typedef {Record<string, any>} RawJsonData */

@@ -16,0 +17,0 @@ const validate = createSchemaValidation(

@@ -16,2 +16,3 @@ /*

/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */
/** @typedef {import("./JsonModulesPlugin").RawJsonData} RawJsonData */

@@ -40,3 +41,3 @@ class JsonParser extends Parser {

typeof this.options.parse === "function" ? this.options.parse : parseJson;
/** @type {Buffer | RawJsonData} */
const data =

@@ -43,0 +44,0 @@ typeof source === "object"

@@ -92,3 +92,4 @@ /*

`var ${varName} = __webpack_exports__${propertyAccess([
exportInfo.getUsedName(exportInfo.name, chunk.runtime)
/** @type {string} */
(exportInfo.getUsedName(exportInfo.name, chunk.runtime))
])};\n`

@@ -95,0 +96,0 @@ );

@@ -135,2 +135,6 @@ /*

};
/**
* @param {string} value string
* @returns {function(number): string} string to put in quotes with length
*/
const unquotedStringifyWithLength = value => length =>

@@ -137,0 +141,0 @@ unquotedStringify(`${value}`.slice(0, length));

@@ -28,2 +28,5 @@ /*

const fn = RuntimeGlobals.getTrustedTypesPolicy;
const wrapPolicyCreationInTryCatch = trustedTypes
? trustedTypes.onPolicyCreationFailure === "continue"
: false;

@@ -62,5 +65,21 @@ return Template.asString([

Template.indent([
`policy = trustedTypes.createPolicy(${JSON.stringify(
trustedTypes.policyName
)}, policy);`
...(wrapPolicyCreationInTryCatch ? ["try {"] : []),
...[
`policy = trustedTypes.createPolicy(${JSON.stringify(
trustedTypes.policyName
)}, policy);`
].map(line =>
wrapPolicyCreationInTryCatch ? Template.indent(line) : line
),
...(wrapPolicyCreationInTryCatch
? [
"} catch (e) {",
Template.indent([
`console.warn('Could not create trusted-types policy ${JSON.stringify(
trustedTypes.policyName
)}');`
]),
"}"
]
: [])
]),

@@ -67,0 +86,0 @@ "}"

@@ -16,2 +16,6 @@ /*

/**
* @param {string} uri data URI
* @returns {Buffer|null} decoded data
*/
const decodeDataURI = uri => {

@@ -18,0 +22,0 @@ const match = URIRegEx.exec(uri);

@@ -74,2 +74,6 @@ /*

/**
* @param {string} str path
* @returns {string} safe path
*/
const toSafePath = str =>

@@ -80,2 +84,6 @@ str

/**
* @param {Buffer} content content
* @returns {string} integrity
*/
const computeIntegrity = content => {

@@ -88,2 +96,7 @@ const hash = createHash("sha512");

/**
* @param {Buffer} content content
* @param {string} integrity integrity
* @returns {boolean} true, if integrity matches
*/
const verifyIntegrity = (content, integrity) => {

@@ -116,2 +129,7 @@ if (integrity === "ignore") return true;

/**
* @param {string | undefined} cacheControl Cache-Control header
* @param {number} requestTime timestamp of request
* @returns {{storeCache: boolean, storeLock: boolean, validUntil: number}} Logic for storing in cache and lockfile cache
*/
const parseCacheControl = (cacheControl, requestTime) => {

@@ -154,2 +172,6 @@ // When false resource is not stored in cache

/**
* @param {LockfileEntry} entry lockfile entry
* @returns {`resolved: ${string}, integrity: ${string}, contentType: ${*}`} stringified entry
*/
const entryToString = entry => {

@@ -166,2 +188,6 @@ return `resolved: ${entry.resolved}, integrity: ${entry.integrity}, contentType: ${entry.contentType}`;

/**
* @param {string} content content of the lockfile
* @returns {Lockfile} lockfile
*/
static parse(content) {

@@ -189,2 +215,5 @@ // TODO handle merge conflicts

/**
* @returns {string} stringified lockfile
*/
toString() {

@@ -352,2 +381,3 @@ let str = "{\n";

const logger = compilation.getLogger("webpack.HttpUriPlugin");
/** @type {string} */
const lockfileLocation =

@@ -362,2 +392,3 @@ this._lockfileLocation ||

);
/** @type {string | false} */
const cacheLocation =

@@ -376,2 +407,3 @@ this._cacheLocation !== undefined

/** @type {Map<string, string>} */
const cacheKeyCache = new Map();

@@ -460,2 +492,8 @@ /**

let lockfileUpdates = undefined;
/**
* @param {Lockfile} lockfile lockfile instance
* @param {string} url url to store
* @param {LockfileEntry | "ignore" | "no-cache"} entry lockfile entry
*/
const storeLockEntry = (lockfile, url, entry) => {

@@ -462,0 +500,0 @@ const oldEntry = lockfile.entries.get(url);

@@ -12,11 +12,297 @@ /*

// Extreme shorthand only for github. eg: foo/bar
const RE_URL_GITHUB_EXTREME_SHORT = /^[^/@:.\s][^/@:\s]*\/[^@:\s]*[^/@:\s]#\S+/;
// Short url with specific protocol. eg: github:foo/bar
const RE_GIT_URL_SHORT = /^(github|gitlab|bitbucket|gist):\/?[^/.]+\/?/i;
// Currently supported protocols
const RE_PROTOCOL =
/^((git\+)?(ssh|https?|file)|git|github|gitlab|bitbucket|gist):$/i;
// Has custom protocol
const RE_CUSTOM_PROTOCOL = /^((git\+)?(ssh|https?|file)|git):\/\//i;
// Valid hash format for npm / yarn ...
const RE_URL_HASH_VERSION = /#(?:semver:)?(.+)/;
// Simple hostname validate
const RE_HOSTNAME = /^(?:[^/.]+(\.[^/]+)+|localhost)$/;
// For hostname with colon. eg: ssh://user@github.com:foo/bar
const RE_HOSTNAME_WITH_COLON =
/([^/@#:.]+(?:\.[^/@#:.]+)+|localhost):([^#/0-9]+)/;
// Reg for url without protocol
const RE_NO_PROTOCOL = /^([^/@#:.]+(?:\.[^/@#:.]+)+)/;
// RegExp for version string
const VERSION_PATTERN_REGEXP = /^([\d^=v<>~]|[*xX]$)/;
// Specific protocol for short url without normal hostname
const PROTOCOLS_FOR_SHORT = [
"github:",
"gitlab:",
"bitbucket:",
"gist:",
"file:"
];
// Default protocol for git url
const DEF_GIT_PROTOCOL = "git+ssh://";
// thanks to https://github.com/npm/hosted-git-info/blob/latest/git-host-info.js
const extractCommithashByDomain = {
"github.com": (pathname, hash) => {
let [, user, project, type, commithash] = pathname.split("/", 5);
if (type && type !== "tree") {
return;
}
if (!type) {
commithash = hash;
} else {
commithash = "#" + commithash;
}
if (project && project.endsWith(".git")) {
project = project.slice(0, -4);
}
if (!user || !project) {
return;
}
return commithash;
},
"gitlab.com": (pathname, hash) => {
const path = pathname.slice(1);
if (path.includes("/-/") || path.includes("/archive.tar.gz")) {
return;
}
const segments = path.split("/");
let project = segments.pop();
if (project.endsWith(".git")) {
project = project.slice(0, -4);
}
const user = segments.join("/");
if (!user || !project) {
return;
}
return hash;
},
"bitbucket.org": (pathname, hash) => {
let [, user, project, aux] = pathname.split("/", 4);
if (["get"].includes(aux)) {
return;
}
if (project && project.endsWith(".git")) {
project = project.slice(0, -4);
}
if (!user || !project) {
return;
}
return hash;
},
"gist.github.com": (pathname, hash) => {
let [, user, project, aux] = pathname.split("/", 4);
if (aux === "raw") {
return;
}
if (!project) {
if (!user) {
return;
}
project = user;
user = null;
}
if (project.endsWith(".git")) {
project = project.slice(0, -4);
}
return hash;
}
};
/**
* extract commit hash from parsed url
*
* @inner
* @param {Object} urlParsed parsed url
* @returns {string} commithash
*/
function getCommithash(urlParsed) {
let { hostname, pathname, hash } = urlParsed;
hostname = hostname.replace(/^www\./, "");
try {
hash = decodeURIComponent(hash);
// eslint-disable-next-line no-empty
} catch (e) {}
if (extractCommithashByDomain[hostname]) {
return extractCommithashByDomain[hostname](pathname, hash) || "";
}
return hash;
}
/**
* make url right for URL parse
*
* @inner
* @param {string} gitUrl git url
* @returns {string} fixed url
*/
function correctUrl(gitUrl) {
// like:
// proto://hostname.com:user/repo -> proto://hostname.com/user/repo
return gitUrl.replace(RE_HOSTNAME_WITH_COLON, "$1/$2");
}
/**
* make url protocol right for URL parse
*
* @inner
* @param {string} gitUrl git url
* @returns {string} fixed url
*/
function correctProtocol(gitUrl) {
// eg: github:foo/bar#v1.0. Should not add double slash, in case of error parsed `pathname`
if (RE_GIT_URL_SHORT.test(gitUrl)) {
return gitUrl;
}
// eg: user@github.com:foo/bar
if (!RE_CUSTOM_PROTOCOL.test(gitUrl)) {
return `${DEF_GIT_PROTOCOL}${gitUrl}`;
}
return gitUrl;
}
/**
* extract git dep version from hash
*
* @inner
* @param {string} hash hash
* @returns {string} git dep version
*/
function getVersionFromHash(hash) {
const matched = hash.match(RE_URL_HASH_VERSION);
return (matched && matched[1]) || "";
}
/**
* if string can be decoded
*
* @inner
* @param {string} str str to be checked
* @returns {boolean} if can be decoded
*/
function canBeDecoded(str) {
try {
decodeURIComponent(str);
} catch (e) {
return false;
}
return true;
}
/**
* get right dep version from git url
*
* @inner
* @param {string} gitUrl git url
* @returns {string} dep version
*/
function getGitUrlVersion(gitUrl) {
let oriGitUrl = gitUrl;
// github extreme shorthand
if (RE_URL_GITHUB_EXTREME_SHORT.test(gitUrl)) {
gitUrl = "github:" + gitUrl;
} else {
gitUrl = correctProtocol(gitUrl);
}
gitUrl = correctUrl(gitUrl);
let parsed;
try {
parsed = new URL(gitUrl);
// eslint-disable-next-line no-empty
} catch (e) {}
if (!parsed) {
return "";
}
const { protocol, hostname, pathname, username, password } = parsed;
if (!RE_PROTOCOL.test(protocol)) {
return "";
}
// pathname shouldn't be empty or URL malformed
if (!pathname || !canBeDecoded(pathname)) {
return "";
}
// without protocol, there should have auth info
if (RE_NO_PROTOCOL.test(oriGitUrl) && !username && !password) {
return "";
}
if (!PROTOCOLS_FOR_SHORT.includes(protocol.toLowerCase())) {
if (!RE_HOSTNAME.test(hostname)) {
return "";
}
const commithash = getCommithash(parsed);
return getVersionFromHash(commithash) || commithash;
}
// for protocol short
return getVersionFromHash(gitUrl);
}
/**
* @param {string} str maybe required version
* @returns {boolean} true, if it looks like a version
*/
exports.isRequiredVersion = str => {
return /^([\d^=v<>~]|[*xX]$)/.test(str);
};
function isRequiredVersion(str) {
return VERSION_PATTERN_REGEXP.test(str);
}
exports.isRequiredVersion = isRequiredVersion;
/**
* @see https://docs.npmjs.com/cli/v7/configuring-npm/package-json#urls-as-dependencies
* @param {string} versionDesc version to be normalized
* @returns {string} normalized version
*/
function normalizeVersion(versionDesc) {
versionDesc = (versionDesc && versionDesc.trim()) || "";
if (isRequiredVersion(versionDesc)) {
return versionDesc;
}
// add handle for URL Dependencies
return getGitUrlVersion(versionDesc.toLowerCase());
}
exports.normalizeVersion = normalizeVersion;
/**
*

@@ -68,3 +354,3 @@ * @param {InputFileSystem} fs file system

) {
return data.optionalDependencies[packageName];
return normalizeVersion(data.optionalDependencies[packageName]);
}

@@ -76,3 +362,3 @@ if (

) {
return data.dependencies[packageName];
return normalizeVersion(data.dependencies[packageName]);
}

@@ -84,3 +370,3 @@ if (

) {
return data.peerDependencies[packageName];
return normalizeVersion(data.peerDependencies[packageName]);
}

@@ -92,4 +378,4 @@ if (

) {
return data.devDependencies[packageName];
return normalizeVersion(data.devDependencies[packageName]);
}
};

@@ -15,2 +15,8 @@ /*

/**
* @param {number} n a number
* @param {string} singular singular
* @param {string} plural plural
* @returns {string} if n is 1, singular, else plural
*/
const plural = (n, singular, plural) => (n === 1 ? singular : plural);

@@ -33,2 +39,6 @@

/**
* @param {string} resource resource
* @returns {string} resource name for display
*/
const getResourceName = resource => {

@@ -46,2 +56,6 @@ const dataUrl = /^data:[^,]+,/.exec(resource);

/**
* @param {string} name module name
* @returns {[string,string]} prefix and module name
*/
const getModuleName = name => {

@@ -65,2 +79,7 @@ const [, prefix, resource] = /^(.*!)?([^!]*)$/.exec(name);

/**
* @param {string} str string
* @param {function(string): string} fn function to apply to each line
* @returns {string} joined string
*/
const mapLines = (str, fn) => str.split("\n").map(fn).join("\n");

@@ -78,2 +97,8 @@

/**
* @template T
* @param {Array<T>} list of items
* @param {number} count number of items to show
* @returns {string} string representation of list
*/
const moreCount = (list, count) => {

@@ -80,0 +105,0 @@ return list && list.length > 0 ? `+ ${count}` : `${count}`;

@@ -8,2 +8,6 @@ /*

/**
* @param {string} str string
* @returns {string} quoted meta
*/
const quoteMeta = str => {

@@ -13,2 +17,6 @@ return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&");

/**
* @param {string} str string
* @returns {string} string
*/
const toSimpleString = str => {

@@ -54,3 +62,10 @@ if (`${+str}` === str) {

/**
* @param {Set<string>} itemsSet items set
* @param {(str: string) => string | false} getKey get key function
* @param {(str: Array<string>) => boolean} condition condition
* @returns {Array<Array<string>>} list of common items
*/
const popCommonItems = (itemsSet, getKey, condition) => {
/** @type {Map<string, Array<string>>} */
const map = new Map();

@@ -62,2 +77,3 @@ for (const item of itemsSet) {

if (list === undefined) {
/** @type {Array<string>} */
list = [];

@@ -69,2 +85,3 @@ map.set(key, list);

}
/** @type {Array<Array<string>>} */
const result = [];

@@ -82,2 +99,6 @@ for (const list of map.values()) {

/**
* @param {Array<string>} items items
* @returns {string} common prefix
*/
const getCommonPrefix = items => {

@@ -97,2 +118,6 @@ let prefix = items[0];

/**
* @param {Array<string>} items items
* @returns {string} common suffix
*/
const getCommonSuffix = items => {

@@ -112,2 +137,6 @@ let suffix = items[0];

/**
* @param {Array<string>} itemsArr array of items
* @returns {string} regexp
*/
const itemsToRegexp = itemsArr => {

@@ -117,2 +146,3 @@ if (itemsArr.length === 1) {

}
/** @type {Array<string>} */
const finishedItems = [];

@@ -158,2 +188,3 @@

if (finishedItems.length === 0 && items.size === 2) {
/** @type {Iterator<string>} */
const it = items[Symbol.iterator]();

@@ -160,0 +191,0 @@ const a = it.next().value;

@@ -181,2 +181,10 @@ /*

/**
* @template T
* @param {Object} obj object
* @param {string} name property name
* @param {string} code deprecation code
* @param {string} note additional note
* @returns {Object} frozen object with deprecation when modifying
*/
exports.soonFrozenObjectDeprecation = (obj, name, code, note = "") => {

@@ -183,0 +191,0 @@ const message = `${name} will be frozen in future, all modifications are deprecated.${

@@ -18,2 +18,6 @@ /*

/**
* @param {string} relativePath relative path
* @returns {string} request
*/
const relativePathToRequest = relativePath => {

@@ -20,0 +24,0 @@ if (relativePath === "") return "./.";

@@ -8,39 +8,93 @@ /*

/**
* The maximum safe integer value for 32-bit integers.
* @type {number}
*/
const SAFE_LIMIT = 0x80000000;
/**
* The maximum safe integer value for 32-bit integers minus one. This is used
* in the algorithm to ensure that intermediate hash values do not exceed the
* 32-bit integer limit.
* @type {number}
*/
const SAFE_PART = SAFE_LIMIT - 1;
/**
* The number of 32-bit integers used to store intermediate hash values.
* @type {number}
*/
const COUNT = 4;
/**
* An array used to store intermediate hash values during the calculation.
* @type {number[]}
*/
const arr = [0, 0, 0, 0, 0];
/**
* An array of prime numbers used in the hash calculation.
* @type {number[]}
*/
const primes = [3, 7, 17, 19];
/**
* Computes a hash value for the given string and range. This hashing algorithm is a modified
* version of the [FNV-1a algorithm](https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function).
* It is optimized for speed and does **not** generate a cryptographic hash value.
*
* We use `numberHash` in `lib/ids/IdHelpers.js` to generate hash values for the module identifier. The generated
* hash is used as a prefix for the module id's to avoid collisions with other modules.
*
* @param {string} str The input string to hash.
* @param {number} range The range of the hash value (0 to range-1).
* @returns {number} - The computed hash value.
*
* @example
*
* ```js
* const numberHash = require("webpack/lib/util/numberHash");
* numberHash("hello", 1000); // 57
* numberHash("hello world"); // 990
* ```
*
*/
module.exports = (str, range) => {
/**
* Initialize the array with zeros before it is used
* to store intermediate hash values.
*/
arr.fill(0);
// For each character in the string
for (let i = 0; i < str.length; i++) {
// Get the character code.
const c = str.charCodeAt(i);
for (let j = 0; j < COUNT; j++) {
const p = (j + COUNT - 1) % COUNT;
arr[j] = (arr[j] + c * primes[j] + arr[p]) & SAFE_PART;
}
for (let j = 0; j < COUNT; j++) {
const q = arr[j] % COUNT;
arr[j] = arr[j] ^ (arr[q] >> 1);
}
// For each 32-bit integer used to store the hash value
// add the character code to the current hash value and multiply by the prime number and
// add the previous 32-bit integer.
arr[0] = (arr[0] + c * primes[0] + arr[3]) & SAFE_PART;
arr[1] = (arr[1] + c * primes[1] + arr[0]) & SAFE_PART;
arr[2] = (arr[2] + c * primes[2] + arr[1]) & SAFE_PART;
arr[3] = (arr[3] + c * primes[3] + arr[2]) & SAFE_PART;
// For each 32-bit integer used to store the hash value
// XOR the current hash value with the value of the next 32-bit integer.
arr[0] = arr[0] ^ (arr[arr[0] % COUNT] >> 1);
arr[1] = arr[1] ^ (arr[arr[1] % COUNT] >> 1);
arr[2] = arr[2] ^ (arr[arr[2] % COUNT] >> 1);
arr[3] = arr[3] ^ (arr[arr[3] % COUNT] >> 1);
}
if (range <= SAFE_PART) {
let sum = 0;
for (let j = 0; j < COUNT; j++) {
sum = (sum + arr[j]) % range;
}
return sum;
return (arr[0] + arr[1] + arr[2] + arr[3]) % range;
} else {
let sum1 = 0;
let sum2 = 0;
// Calculate the range extension.
const rangeExt = Math.floor(range / SAFE_LIMIT);
for (let j = 0; j < COUNT; j += 2) {
sum1 = (sum1 + arr[j]) & SAFE_PART;
}
for (let j = 1; j < COUNT; j += 2) {
sum2 = (sum2 + arr[j]) % rangeExt;
}
const sum1 = (arr[0] + arr[2]) & SAFE_PART;
const sum2 = (arr[0] + arr[2]) % rangeExt;
return (sum2 * SAFE_LIMIT + sum1) % range;
}
};

@@ -63,2 +63,7 @@ /*

/**
* @param {ArrayLike<string>} properties properties
* @param {number} start start index
* @returns {string} chain of property accesses
*/
const propertyAccess = (properties, start = 0) => {

@@ -65,0 +70,0 @@ let str = "";

@@ -86,2 +86,5 @@ /*

/**
* @returns {number} size of the map
*/
get size() {

@@ -95,2 +98,5 @@ let size = this.map.size;

/**
* @returns {Iterator<[K, V]>} iterator
*/
[Symbol.iterator]() {

@@ -97,0 +103,0 @@ const iterators = this.stack.map(map => map[Symbol.iterator]());

@@ -8,4 +8,36 @@ /*

/** @typedef {import("../util/Hash")} Hash */
/**
* StringXor class provides methods for performing
* [XOR operations](https://en.wikipedia.org/wiki/Exclusive_or) on strings. In this context
* we operating on the character codes of two strings, which are represented as
* [Buffer](https://nodejs.org/api/buffer.html) objects.
*
* We use [StringXor in webpack](https://github.com/webpack/webpack/commit/41a8e2ea483a544c4ccd3e6217bdfb80daffca39)
* to create a hash of the current state of the compilation. By XOR'ing the Module hashes, it
* doesn't matter if the Module hashes are sorted or not. This is useful because it allows us to avoid sorting the
* Module hashes.
*
* @example
* ```js
* const xor = new StringXor();
* xor.add('hello');
* xor.add('world');
* console.log(xor.toString());
* ```
*
* @example
* ```js
* const xor = new StringXor();
* xor.add('foo');
* xor.add('bar');
* const hash = createHash('sha256');
* hash.update(xor.toString());
* console.log(hash.digest('hex'));
* ```
*/
class StringXor {
constructor() {
/** @type {Buffer|undefined} */
this._value = undefined;

@@ -15,2 +47,4 @@ }

/**
* Adds a string to the current StringXor object.
*
* @param {string} str string

@@ -23,2 +57,6 @@ * @returns {void}

if (value === undefined) {
/**
* We are choosing to use Buffer.allocUnsafe() because it is often faster than Buffer.alloc() because
* it allocates a new buffer of the specified size without initializing the memory.
*/
const newValue = (this._value = Buffer.allocUnsafe(len));

@@ -47,2 +85,10 @@ for (let i = 0; i < len; i++) {

/**
* Returns a string that represents the current state of the StringXor object. We chose to use "latin1" encoding
* here because "latin1" encoding is a single-byte encoding that can represent all characters in the
* [ISO-8859-1 character set](https://en.wikipedia.org/wiki/ISO/IEC_8859-1). This is useful when working
* with binary data that needs to be represented as a string.
*
* @returns {string} Returns a string that represents the current state of the StringXor object.
*/
toString() {

@@ -53,2 +99,7 @@ const value = this._value;

/**
* Updates the hash with the current state of the StringXor object.
*
* @param {Hash} hash Hash instance
*/
updateHash(hash) {

@@ -55,0 +106,0 @@ const value = this._value;

@@ -88,2 +88,3 @@ /*

/** @type {Array<string>} */
const promises = [];

@@ -90,0 +91,0 @@

@@ -50,3 +50,3 @@ /*

const module = program.body[0];
/** @type {Array<string>} */
const exports = [];

@@ -53,0 +53,0 @@ t.traverse(module, {

@@ -15,2 +15,6 @@ /*

/**
* @param {Compiler} compiler compiler instance
* @returns {Set<WasmLoadingType>} enabled types
*/
const getEnabledTypes = compiler => {

@@ -17,0 +21,0 @@ let set = enabledTypes.get(compiler);

@@ -122,43 +122,36 @@ /*

const ExternalsPlugin = require("./ExternalsPlugin");
new ExternalsPlugin(
"import",
options.experiments.css
? ({ request, dependencyType }, callback) => {
if (dependencyType === "url") {
if (/^(\/\/|https?:\/\/)/.test(request))
return callback(null, `asset ${request}`);
} else if (dependencyType === "css-import") {
if (/^(\/\/|https?:\/\/)/.test(request))
return callback(null, `css-import ${request}`);
} else if (/^(\/\/|https?:\/\/|std:)/.test(request)) {
if (/^\.css(\?|$)/.test(request))
return callback(null, `css-import ${request}`);
return callback(null, `import ${request}`);
}
callback();
}
: /^(\/\/|https?:\/\/|std:)/
).apply(compiler);
new ExternalsPlugin("import", ({ request, dependencyType }, callback) => {
if (dependencyType === "url") {
if (/^(\/\/|https?:\/\/|#)/.test(request))
return callback(null, `asset ${request}`);
} else if (options.experiments.css && dependencyType === "css-import") {
if (/^(\/\/|https?:\/\/|#)/.test(request))
return callback(null, `css-import ${request}`);
} else if (
options.experiments.css &&
/^(\/\/|https?:\/\/|std:)/.test(request)
) {
if (/^\.css(\?|$)/.test(request))
return callback(null, `css-import ${request}`);
return callback(null, `import ${request}`);
}
callback();
}).apply(compiler);
} else if (options.externalsPresets.web) {
//@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
const ExternalsPlugin = require("./ExternalsPlugin");
new ExternalsPlugin(
"module",
options.experiments.css
? ({ request, dependencyType }, callback) => {
if (dependencyType === "url") {
if (/^(\/\/|https?:\/\/)/.test(request))
return callback(null, `asset ${request}`);
} else if (dependencyType === "css-import") {
if (/^(\/\/|https?:\/\/)/.test(request))
return callback(null, `css-import ${request}`);
} else if (/^(\/\/|https?:\/\/|std:)/.test(request)) {
if (/^\.css(\?|$)/.test(request))
return callback(null, `css-import ${request}`);
return callback(null, `module ${request}`);
}
callback();
}
: /^(\/\/|https?:\/\/|std:)/
).apply(compiler);
new ExternalsPlugin("module", ({ request, dependencyType }, callback) => {
if (dependencyType === "url") {
if (/^(\/\/|https?:\/\/|#)/.test(request))
return callback(null, `asset ${request}`);
} else if (options.experiments.css && dependencyType === "css-import") {
if (/^(\/\/|https?:\/\/|#)/.test(request))
return callback(null, `css-import ${request}`);
} else if (/^(\/\/|https?:\/\/|std:)/.test(request)) {
if (options.experiments.css && /^\.css((\?)|$)/.test(request))
return callback(null, `css-import ${request}`);
return callback(null, `module ${request}`);
}
callback();
}).apply(compiler);
} else if (options.externalsPresets.node) {

@@ -172,6 +165,6 @@ if (options.experiments.css) {

if (dependencyType === "url") {
if (/^(\/\/|https?:\/\/)/.test(request))
if (/^(\/\/|https?:\/\/|#)/.test(request))
return callback(null, `asset ${request}`);
} else if (dependencyType === "css-import") {
if (/^(\/\/|https?:\/\/)/.test(request))
if (/^(\/\/|https?:\/\/|#)/.test(request))
return callback(null, `css-import ${request}`);

@@ -178,0 +171,0 @@ } else if (/^(\/\/|https?:\/\/|std:)/.test(request)) {

{
"name": "webpack",
"version": "5.81.0",
"version": "5.82.0",
"author": "Tobias Koppers @sokra",

@@ -5,0 +5,0 @@ "description": "Packs CommonJs/AMD modules for the browser. Allows to split your codebase into multiple bundles, which can be loaded on demand. Support loaders to preprocess files, i.e. json, jsx, es7, css, less, ... and your custom stuff.",

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc