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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(type): small improve #17107

Merged
merged 3 commits into from
May 3, 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@
"prewalking",
"prioritise",
"promisify",
"proxied",
"quasis",
"queryloader",
"querystrings",
Expand Down
3 changes: 2 additions & 1 deletion lib/library/ModuleLibraryPlugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,8 @@ class ModuleLibraryPlugin extends AbstractLibraryPlugin {
)}`;
result.add(
`var ${varName} = __webpack_exports__${propertyAccess([
exportInfo.getUsedName(exportInfo.name, chunk.runtime)
/** @type {string} */
(exportInfo.getUsedName(exportInfo.name, chunk.runtime))
])};\n`
);
exports.push(`${varName} as ${exportInfo.name}`);
Expand Down
4 changes: 4 additions & 0 deletions lib/runtime/GetChunkFilenameRuntimeModule.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,10 @@ class GetChunkFilenameRuntimeModule extends RuntimeModule {
const s = JSON.stringify(str);
return s.slice(1, s.length - 1);
};
/**
* @param {string} value string
* @returns {function(number): string} string to put in quotes with length
*/
const unquotedStringifyWithLength = value => length =>
unquotedStringify(`${value}`.slice(0, length));
const chunkFilenameValue =
Expand Down
4 changes: 4 additions & 0 deletions lib/schemes/DataUriPlugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ const NormalModule = require("../NormalModule");
// http://www.ietf.org/rfc/rfc2397.txt
const URIRegEx = /^data:([^;,]+)?((?:;[^;,]+)*?)(?:;(base64))?,(.*)$/i;

/**
* @param {string} uri data URI
* @returns {Buffer|null} decoded data
*/
const decodeDataURI = uri => {
const match = URIRegEx.exec(uri);
if (!match) return null;
Expand Down
38 changes: 38 additions & 0 deletions lib/schemes/HttpUriPlugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,18 +71,31 @@ const validate = createSchemaValidation(
}
);

/**
* @param {string} str path
* @returns {string} safe path
*/
const toSafePath = str =>
str
.replace(/^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$/g, "")
.replace(/[^a-zA-Z0-9._-]+/g, "_");

/**
* @param {Buffer} content content
* @returns {string} integrity
*/
const computeIntegrity = content => {
const hash = createHash("sha512");
hash.update(content);
const integrity = "sha512-" + hash.digest("base64");
return integrity;
};

/**
* @param {Buffer} content content
* @param {string} integrity integrity
* @returns {boolean} true, if integrity matches
*/
const verifyIntegrity = (content, integrity) => {
if (integrity === "ignore") return true;
return computeIntegrity(content) === integrity;
Expand Down Expand Up @@ -110,6 +123,11 @@ const parseKeyValuePairs = str => {
return result;
};

/**
* @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) => {
// When false resource is not stored in cache
let storeCache = true;
Expand Down Expand Up @@ -147,6 +165,10 @@ const areLockfileEntriesEqual = (a, b) => {
);
};

/**
* @param {LockfileEntry} entry lockfile entry
* @returns {`resolved: ${string}, integrity: ${string}, contentType: ${*}`} stringified entry
*/
const entryToString = entry => {
return `resolved: ${entry.resolved}, integrity: ${entry.integrity}, contentType: ${entry.contentType}`;
};
Expand All @@ -158,6 +180,10 @@ class Lockfile {
this.entries = new Map();
}

/**
* @param {string} content content of the lockfile
* @returns {Lockfile} lockfile
*/
static parse(content) {
// TODO handle merge conflicts
const data = JSON.parse(content);
Expand All @@ -180,6 +206,9 @@ class Lockfile {
return lockfile;
}

/**
* @returns {string} stringified lockfile
*/
toString() {
let str = "{\n";
const entries = Array.from(this.entries).sort(([a], [b]) =>
Expand Down Expand Up @@ -342,6 +371,7 @@ class HttpUriPlugin {
const fs = compilation.inputFileSystem;
const cache = compilation.getCache("webpack.HttpUriPlugin");
const logger = compilation.getLogger("webpack.HttpUriPlugin");
/** @type {string} */
const lockfileLocation =
this._lockfileLocation ||
join(
Expand All @@ -351,6 +381,7 @@ class HttpUriPlugin {
? `${toSafePath(compiler.name)}.webpack.lock`
: "webpack.lock"
);
/** @type {string | false} */
const cacheLocation =
this._cacheLocation !== undefined
? this._cacheLocation
Expand All @@ -364,6 +395,7 @@ class HttpUriPlugin {

let warnedAboutEol = false;

/** @type {Map<string, string>} */
const cacheKeyCache = new Map();
/**
* @param {string} url the url
Expand Down Expand Up @@ -447,6 +479,12 @@ class HttpUriPlugin {

/** @type {Map<string, LockfileEntry | "ignore" | "no-cache"> | undefined} */
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) => {
const oldEntry = lockfile.entries.get(url);
if (lockfileUpdates === undefined) lockfileUpdates = new Map();
Expand Down
25 changes: 25 additions & 0 deletions lib/stats/DefaultStatsPrinterPlugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@
const DATA_URI_CONTENT_LENGTH = 16;
const MAX_MODULE_IDENTIFIER_LENGTH = 80;

/**
* @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);

/**
Expand All @@ -29,6 +35,10 @@ const printSizes = (sizes, { formatSize = n => `${n}` }) => {
}
};

/**
* @param {string} resource resource
* @returns {string} resource name for display
*/
const getResourceName = resource => {
const dataUrl = /^data:[^,]+,/.exec(resource);
if (!dataUrl) return resource;
Expand All @@ -41,6 +51,10 @@ const getResourceName = resource => {
)}..`;
};

/**
* @param {string} name module name
* @returns {[string,string]} prefix and module name
*/
const getModuleName = name => {
const [, prefix, resource] = /^(.*!)?([^!]*)$/.exec(name);

Expand All @@ -59,6 +73,11 @@ const getModuleName = name => {
return [prefix, getResourceName(resource)];
};

/**
* @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");

/**
Expand All @@ -71,6 +90,12 @@ const isValidId = id => {
return typeof id === "number" || id;
};

/**
* @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) => {
return list && list.length > 0 ? `+ ${count}` : `${count}`;
};
Expand Down
6 changes: 6 additions & 0 deletions lib/util/StackedCacheMap.js
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Document this.

Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,9 @@ class StackedCacheMap {
this.map.clear();
}

/**
* @returns {number} size of the map
*/
get size() {
let size = this.map.size;
for (const map of this.stack) {
Expand All @@ -91,6 +94,9 @@ class StackedCacheMap {
return size;
}

/**
* @returns {Iterator<[K, V]>} iterator
*/
[Symbol.iterator]() {
const iterators = this.stack.map(map => map[Symbol.iterator]());
let current = this.map[Symbol.iterator]();
Expand Down
31 changes: 31 additions & 0 deletions lib/util/compileBooleanMatcher.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,18 @@

"use strict";

/**
* @param {string} str string
* @returns {string} quoted meta
*/
const quoteMeta = str => {
return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&");
};

/**
* @param {string} str string
* @returns {string} string
*/
const toSimpleString = str => {
if (`${+str}` === str) {
return str;
Expand Down Expand Up @@ -49,19 +57,28 @@ const compileBooleanMatcherFromLists = (positiveItems, negativeItems) => {
}
};

/**
* @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();
for (const item of itemsSet) {
const key = getKey(item);
if (key) {
let list = map.get(key);
if (list === undefined) {
/** @type {Array<string>} */
list = [];
map.set(key, list);
}
list.push(item);
}
}
/** @type {Array<Array<string>>} */
const result = [];
for (const list of map.values()) {
if (condition(list)) {
Expand All @@ -74,6 +91,10 @@ const popCommonItems = (itemsSet, getKey, condition) => {
return result;
};

/**
* @param {Array<string>} items items
* @returns {string} common prefix
*/
const getCommonPrefix = items => {
let prefix = items[0];
for (let i = 1; i < items.length; i++) {
Expand All @@ -88,6 +109,10 @@ const getCommonPrefix = items => {
return prefix;
};

/**
* @param {Array<string>} items items
* @returns {string} common suffix
*/
const getCommonSuffix = items => {
let suffix = items[0];
for (let i = 1; i < items.length; i++) {
Expand All @@ -102,10 +127,15 @@ const getCommonSuffix = items => {
return suffix;
};

/**
* @param {Array<string>} itemsArr array of items
* @returns {string} regexp
*/
const itemsToRegexp = itemsArr => {
if (itemsArr.length === 1) {
return quoteMeta(itemsArr[0]);
}
/** @type {Array<string>} */
const finishedItems = [];

// merge single char items: (a|b|c|d|ef) => ([abcd]|ef)
Expand Down Expand Up @@ -146,6 +176,7 @@ const itemsToRegexp = itemsArr => {

// special case for 2 items with common suffix
if (finishedItems.length === 0 && items.size === 2) {
/** @type {Iterator<string>} */
const it = items[Symbol.iterator]();
const a = it.next().value;
const b = it.next().value;
Expand Down
8 changes: 8 additions & 0 deletions lib/util/deprecation.js
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,14 @@ exports.createArrayToSetDeprecationSet = name => {
return SetDeprecatedArray;
};

/**
* @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 = "") => {
const message = `${name} will be frozen in future, all modifications are deprecated.${
note && `\n${note}`
Expand Down
4 changes: 4 additions & 0 deletions lib/util/identifier.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ const WINDOWS_PATH_SEPARATOR_REGEXP = /\\/g;
* @property {Map<string, Map<string, string>>=} relativePaths
*/

/**
* @param {string} relativePath relative path
* @returns {string} request
*/
const relativePathToRequest = relativePath => {
if (relativePath === "") return "./.";
if (relativePath === "..") return "../.";
Expand Down
5 changes: 5 additions & 0 deletions lib/util/propertyAccess.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,11 @@ const RESERVED_IDENTIFIER = new Set([
"false"
]);

/**
* @param {ArrayLike<string>} properties properties
* @param {number} start start index
* @returns {string} chain of property accesses
*/
const propertyAccess = (properties, start = 0) => {
let str = "";
for (let i = start; i < properties.length; i++) {
Expand Down
1 change: 1 addition & 0 deletions lib/wasm-async/AsyncWebAssemblyJavascriptGenerator.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ class AsyncWebAssemblyJavascriptGenerator extends Generator {
}
}

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

const importStatements = Array.from(
Expand Down
2 changes: 1 addition & 1 deletion lib/wasm-async/AsyncWebAssemblyParser.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ class WebAssemblyParser extends Parser {
// parse it
const program = decode(source, decoderOpts);
const module = program.body[0];

/** @type {Array<string>} */
const exports = [];
t.traverse(module, {
ModuleExport({ node }) {
Expand Down
4 changes: 4 additions & 0 deletions lib/wasm/EnableWasmLoadingPlugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@
/** @type {WeakMap<Compiler, Set<WasmLoadingType>>} */
const enabledTypes = new WeakMap();

/**
* @param {Compiler} compiler compiler instance
* @returns {Set<WasmLoadingType>} enabled types
*/
const getEnabledTypes = compiler => {
let set = enabledTypes.get(compiler);
if (set === undefined) {
Expand Down