diff --git a/tools/ui/node_modules/es-toolkit/dist/compat/util/toSafeInteger.d.ts b/tools/ui/node_modules/es-toolkit/dist/compat/util/toSafeInteger.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bf17df99ff3949d1c20c400b74f9b3007cb59dee --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/compat/util/toSafeInteger.d.ts @@ -0,0 +1,21 @@ +//#region src/compat/util/toSafeInteger.d.ts +/** + * Converts `value` to a safe integer. + * + * A safe integer can be compared and represented correctly. + * + * @param {any} value - The value to convert. + * @returns {number} Returns the value converted to a safe integer. + * + * @example + * toSafeInteger(3.2); // => 3 + * toSafeInteger(Number.MAX_VALUE); // => 9007199254740991 + * toSafeInteger(Infinity); // => 9007199254740991 + * toSafeInteger('3.2'); // => 3 + * toSafeInteger(NaN); // => 0 + * toSafeInteger(null); // => 0 + * toSafeInteger(-Infinity); // => -9007199254740991 + */ +declare function toSafeInteger(value: any): number; +//#endregion +export { toSafeInteger }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/compat/util/toSafeInteger.js b/tools/ui/node_modules/es-toolkit/dist/compat/util/toSafeInteger.js new file mode 100644 index 0000000000000000000000000000000000000000..354205ff2b861e89aeee303f215d7edbd000388f --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/compat/util/toSafeInteger.js @@ -0,0 +1,27 @@ +const require_toInteger = require("./toInteger.js"); +const require_clamp = require("../math/clamp.js"); +const require_MAX_SAFE_INTEGER = require("../_internal/MAX_SAFE_INTEGER.js"); +//#region src/compat/util/toSafeInteger.ts +/** +* Converts `value` to a safe integer. +* +* A safe integer can be compared and represented correctly. +* +* @param {any} value - The value to convert. +* @returns {number} Returns the value converted to a safe integer. +* +* @example +* toSafeInteger(3.2); // => 3 +* toSafeInteger(Number.MAX_VALUE); // => 9007199254740991 +* toSafeInteger(Infinity); // => 9007199254740991 +* toSafeInteger('3.2'); // => 3 +* toSafeInteger(NaN); // => 0 +* toSafeInteger(null); // => 0 +* toSafeInteger(-Infinity); // => -9007199254740991 +*/ +function toSafeInteger(value) { + if (value == null) return 0; + return require_clamp.clamp(require_toInteger.toInteger(value), -require_MAX_SAFE_INTEGER.MAX_SAFE_INTEGER, require_MAX_SAFE_INTEGER.MAX_SAFE_INTEGER); +} +//#endregion +exports.toSafeInteger = toSafeInteger; diff --git a/tools/ui/node_modules/es-toolkit/dist/compat/util/toSafeInteger.mjs b/tools/ui/node_modules/es-toolkit/dist/compat/util/toSafeInteger.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4db688d65e28e4a97dd79882834360d50be552b6 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/compat/util/toSafeInteger.mjs @@ -0,0 +1,27 @@ +import { toInteger } from "./toInteger.mjs"; +import { clamp } from "../math/clamp.mjs"; +import { MAX_SAFE_INTEGER } from "../_internal/MAX_SAFE_INTEGER.mjs"; +//#region src/compat/util/toSafeInteger.ts +/** +* Converts `value` to a safe integer. +* +* A safe integer can be compared and represented correctly. +* +* @param {any} value - The value to convert. +* @returns {number} Returns the value converted to a safe integer. +* +* @example +* toSafeInteger(3.2); // => 3 +* toSafeInteger(Number.MAX_VALUE); // => 9007199254740991 +* toSafeInteger(Infinity); // => 9007199254740991 +* toSafeInteger('3.2'); // => 3 +* toSafeInteger(NaN); // => 0 +* toSafeInteger(null); // => 0 +* toSafeInteger(-Infinity); // => -9007199254740991 +*/ +function toSafeInteger(value) { + if (value == null) return 0; + return clamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); +} +//#endregion +export { toSafeInteger }; diff --git a/tools/ui/node_modules/es-toolkit/dist/compat/util/toString.d.mts b/tools/ui/node_modules/es-toolkit/dist/compat/util/toString.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..b3c1e92ea6bb787c9c12b41606498ae54f3c6e97 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/compat/util/toString.d.mts @@ -0,0 +1,20 @@ +//#region src/compat/util/toString.d.ts +/** + * Converts `value` to a string. + * + * An empty string is returned for `null` and `undefined` values. + * The sign of `-0` is preserved. + * + * @param {any} value - The value to convert. + * @returns {string} Returns the converted string. + * + * @example + * toString(null) // returns '' + * toString(undefined) // returns '' + * toString(-0) // returns '-0' + * toString([1, 2, -0]) // returns '1,2,-0' + * toString([Symbol('a'), Symbol('b')]) // returns 'Symbol(a),Symbol(b)' + */ +declare function toString(value: any): string; +//#endregion +export { toString }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/compat/util/toString.d.ts b/tools/ui/node_modules/es-toolkit/dist/compat/util/toString.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b3c1e92ea6bb787c9c12b41606498ae54f3c6e97 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/compat/util/toString.d.ts @@ -0,0 +1,20 @@ +//#region src/compat/util/toString.d.ts +/** + * Converts `value` to a string. + * + * An empty string is returned for `null` and `undefined` values. + * The sign of `-0` is preserved. + * + * @param {any} value - The value to convert. + * @returns {string} Returns the converted string. + * + * @example + * toString(null) // returns '' + * toString(undefined) // returns '' + * toString(-0) // returns '-0' + * toString([1, 2, -0]) // returns '1,2,-0' + * toString([Symbol('a'), Symbol('b')]) // returns 'Symbol(a),Symbol(b)' + */ +declare function toString(value: any): string; +//#endregion +export { toString }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/compat/util/toString.js b/tools/ui/node_modules/es-toolkit/dist/compat/util/toString.js new file mode 100644 index 0000000000000000000000000000000000000000..c62a2d03aab865ff7461d9214aa42766ac71db77 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/compat/util/toString.js @@ -0,0 +1,27 @@ +//#region src/compat/util/toString.ts +/** +* Converts `value` to a string. +* +* An empty string is returned for `null` and `undefined` values. +* The sign of `-0` is preserved. +* +* @param {any} value - The value to convert. +* @returns {string} Returns the converted string. +* +* @example +* toString(null) // returns '' +* toString(undefined) // returns '' +* toString(-0) // returns '-0' +* toString([1, 2, -0]) // returns '1,2,-0' +* toString([Symbol('a'), Symbol('b')]) // returns 'Symbol(a),Symbol(b)' +*/ +function toString(value) { + if (value == null) return ""; + if (typeof value === "string") return value; + if (Array.isArray(value)) return value.map(toString).join(","); + const result = String(value); + if (result === "0" && Object.is(Number(value), -0)) return "-0"; + return result; +} +//#endregion +exports.toString = toString; diff --git a/tools/ui/node_modules/es-toolkit/dist/compat/util/toString.mjs b/tools/ui/node_modules/es-toolkit/dist/compat/util/toString.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7b2c07adf84c5ea848ae3af3ae50ef0949a76075 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/compat/util/toString.mjs @@ -0,0 +1,27 @@ +//#region src/compat/util/toString.ts +/** +* Converts `value` to a string. +* +* An empty string is returned for `null` and `undefined` values. +* The sign of `-0` is preserved. +* +* @param {any} value - The value to convert. +* @returns {string} Returns the converted string. +* +* @example +* toString(null) // returns '' +* toString(undefined) // returns '' +* toString(-0) // returns '-0' +* toString([1, 2, -0]) // returns '1,2,-0' +* toString([Symbol('a'), Symbol('b')]) // returns 'Symbol(a),Symbol(b)' +*/ +function toString(value) { + if (value == null) return ""; + if (typeof value === "string") return value; + if (Array.isArray(value)) return value.map(toString).join(","); + const result = String(value); + if (result === "0" && Object.is(Number(value), -0)) return "-0"; + return result; +} +//#endregion +export { toString }; diff --git a/tools/ui/node_modules/es-toolkit/dist/compat/util/uniqueId.d.mts b/tools/ui/node_modules/es-toolkit/dist/compat/util/uniqueId.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..0ae7e3c7f707dcc98d481202b74757324f0defb9 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/compat/util/uniqueId.d.mts @@ -0,0 +1,26 @@ +//#region src/compat/util/uniqueId.d.ts +/** + * Generates a unique identifier, optionally prefixed with a given string. + * + * @param {string} [prefix] - An optional string to prefix the unique identifier. + * If not provided or not a string, only the unique + * numeric identifier is returned. + * @returns {string} A string containing the unique identifier, with the optional + * prefix if provided. + * + * @example + * // Generate a unique ID with a prefix + * uniqueId('user_'); // => 'user_1' + * + * @example + * // Generate a unique ID without a prefix + * uniqueId(); // => '2' + * + * @example + * // Subsequent calls increment the internal counter + * uniqueId('item_'); // => 'item_3' + * uniqueId(); // => '4' + */ +declare function uniqueId(prefix?: string): string; +//#endregion +export { uniqueId }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/compat/util/uniqueId.d.ts b/tools/ui/node_modules/es-toolkit/dist/compat/util/uniqueId.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0ae7e3c7f707dcc98d481202b74757324f0defb9 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/compat/util/uniqueId.d.ts @@ -0,0 +1,26 @@ +//#region src/compat/util/uniqueId.d.ts +/** + * Generates a unique identifier, optionally prefixed with a given string. + * + * @param {string} [prefix] - An optional string to prefix the unique identifier. + * If not provided or not a string, only the unique + * numeric identifier is returned. + * @returns {string} A string containing the unique identifier, with the optional + * prefix if provided. + * + * @example + * // Generate a unique ID with a prefix + * uniqueId('user_'); // => 'user_1' + * + * @example + * // Generate a unique ID without a prefix + * uniqueId(); // => '2' + * + * @example + * // Subsequent calls increment the internal counter + * uniqueId('item_'); // => 'item_3' + * uniqueId(); // => '4' + */ +declare function uniqueId(prefix?: string): string; +//#endregion +export { uniqueId }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/compat/util/uniqueId.js b/tools/ui/node_modules/es-toolkit/dist/compat/util/uniqueId.js new file mode 100644 index 0000000000000000000000000000000000000000..d21e298ac0833b8c576c353a27eec64e63d77c88 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/compat/util/uniqueId.js @@ -0,0 +1,30 @@ +//#region src/compat/util/uniqueId.ts +/** Counter used to generate unique numeric identifiers. */ +let idCounter = 0; +/** +* Generates a unique identifier, optionally prefixed with a given string. +* +* @param {string} [prefix] - An optional string to prefix the unique identifier. +* If not provided or not a string, only the unique +* numeric identifier is returned. +* @returns {string} A string containing the unique identifier, with the optional +* prefix if provided. +* +* @example +* // Generate a unique ID with a prefix +* uniqueId('user_'); // => 'user_1' +* +* @example +* // Generate a unique ID without a prefix +* uniqueId(); // => '2' +* +* @example +* // Subsequent calls increment the internal counter +* uniqueId('item_'); // => 'item_3' +* uniqueId(); // => '4' +*/ +function uniqueId(prefix = "") { + return `${prefix}${++idCounter}`; +} +//#endregion +exports.uniqueId = uniqueId; diff --git a/tools/ui/node_modules/es-toolkit/dist/compat/util/uniqueId.mjs b/tools/ui/node_modules/es-toolkit/dist/compat/util/uniqueId.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c4457697a8fc11f0ab72d1a235e3b239b78df1a3 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/compat/util/uniqueId.mjs @@ -0,0 +1,30 @@ +//#region src/compat/util/uniqueId.ts +/** Counter used to generate unique numeric identifiers. */ +let idCounter = 0; +/** +* Generates a unique identifier, optionally prefixed with a given string. +* +* @param {string} [prefix] - An optional string to prefix the unique identifier. +* If not provided or not a string, only the unique +* numeric identifier is returned. +* @returns {string} A string containing the unique identifier, with the optional +* prefix if provided. +* +* @example +* // Generate a unique ID with a prefix +* uniqueId('user_'); // => 'user_1' +* +* @example +* // Generate a unique ID without a prefix +* uniqueId(); // => '2' +* +* @example +* // Subsequent calls increment the internal counter +* uniqueId('item_'); // => 'item_3' +* uniqueId(); // => '4' +*/ +function uniqueId(prefix = "") { + return `${prefix}${++idCounter}`; +} +//#endregion +export { uniqueId }; diff --git a/tools/ui/node_modules/es-toolkit/dist/error/AbortError.d.mts b/tools/ui/node_modules/es-toolkit/dist/error/AbortError.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..bac4e99ff420adebece7bd889bd8f804d28f659d --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/error/AbortError.d.mts @@ -0,0 +1,12 @@ +import { DOMException } from "../_internal/DOMException.mjs"; + +//#region src/error/AbortError.d.ts +/** + * An error class representing an aborted operation. + * @augments DOMException + */ +declare class AbortError extends DOMException { + constructor(message?: string); +} +//#endregion +export { AbortError }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/error/AbortError.d.ts b/tools/ui/node_modules/es-toolkit/dist/error/AbortError.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..be46c2509ec9442df75daed96612f81c83b6cef3 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/error/AbortError.d.ts @@ -0,0 +1,12 @@ +import { DOMException } from "../_internal/DOMException.js"; + +//#region src/error/AbortError.d.ts +/** + * An error class representing an aborted operation. + * @augments DOMException + */ +declare class AbortError extends DOMException { + constructor(message?: string); +} +//#endregion +export { AbortError }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/error/AbortError.js b/tools/ui/node_modules/es-toolkit/dist/error/AbortError.js new file mode 100644 index 0000000000000000000000000000000000000000..8427b37492a4492a771996e195c6b2db94819cf2 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/error/AbortError.js @@ -0,0 +1,13 @@ +const require_DOMException = require("../_internal/DOMException.js"); +//#region src/error/AbortError.ts +/** +* An error class representing an aborted operation. +* @augments DOMException +*/ +var AbortError = class extends require_DOMException.DOMException { + constructor(message = "The operation was aborted") { + super(message); + } +}; +//#endregion +exports.AbortError = AbortError; diff --git a/tools/ui/node_modules/es-toolkit/dist/error/AbortError.mjs b/tools/ui/node_modules/es-toolkit/dist/error/AbortError.mjs new file mode 100644 index 0000000000000000000000000000000000000000..69999eab31e401f36d5e28348152aa78cc0044d4 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/error/AbortError.mjs @@ -0,0 +1,13 @@ +import { DOMException } from "../_internal/DOMException.mjs"; +//#region src/error/AbortError.ts +/** +* An error class representing an aborted operation. +* @augments DOMException +*/ +var AbortError = class extends DOMException { + constructor(message = "The operation was aborted") { + super(message); + } +}; +//#endregion +export { AbortError }; diff --git a/tools/ui/node_modules/es-toolkit/dist/error/TimeoutError.d.mts b/tools/ui/node_modules/es-toolkit/dist/error/TimeoutError.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..ec15da04004465b513e31432364963c1f95cc614 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/error/TimeoutError.d.mts @@ -0,0 +1,12 @@ +import { DOMException } from "../_internal/DOMException.mjs"; + +//#region src/error/TimeoutError.d.ts +/** + * An error class representing a timeout operation. + * @augments DOMException + */ +declare class TimeoutError extends DOMException { + constructor(message?: string); +} +//#endregion +export { TimeoutError }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/error/TimeoutError.d.ts b/tools/ui/node_modules/es-toolkit/dist/error/TimeoutError.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5c52fe5eae7252c1810ea9610846f9384f465b86 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/error/TimeoutError.d.ts @@ -0,0 +1,12 @@ +import { DOMException } from "../_internal/DOMException.js"; + +//#region src/error/TimeoutError.d.ts +/** + * An error class representing a timeout operation. + * @augments DOMException + */ +declare class TimeoutError extends DOMException { + constructor(message?: string); +} +//#endregion +export { TimeoutError }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/error/TimeoutError.js b/tools/ui/node_modules/es-toolkit/dist/error/TimeoutError.js new file mode 100644 index 0000000000000000000000000000000000000000..cb4f170ad6fd73e78feaceea6362b32a7b648396 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/error/TimeoutError.js @@ -0,0 +1,13 @@ +const require_DOMException = require("../_internal/DOMException.js"); +//#region src/error/TimeoutError.ts +/** +* An error class representing a timeout operation. +* @augments DOMException +*/ +var TimeoutError = class extends require_DOMException.DOMException { + constructor(message = "The operation was timed out") { + super(message); + } +}; +//#endregion +exports.TimeoutError = TimeoutError; diff --git a/tools/ui/node_modules/es-toolkit/dist/error/TimeoutError.mjs b/tools/ui/node_modules/es-toolkit/dist/error/TimeoutError.mjs new file mode 100644 index 0000000000000000000000000000000000000000..24c00c7bdf9d2cbbcc78e118d7c484906603d1d6 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/error/TimeoutError.mjs @@ -0,0 +1,13 @@ +import { DOMException } from "../_internal/DOMException.mjs"; +//#region src/error/TimeoutError.ts +/** +* An error class representing a timeout operation. +* @augments DOMException +*/ +var TimeoutError = class extends DOMException { + constructor(message = "The operation was timed out") { + super(message); + } +}; +//#endregion +export { TimeoutError }; diff --git a/tools/ui/node_modules/es-toolkit/dist/error/index.d.mts b/tools/ui/node_modules/es-toolkit/dist/error/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..9faec5976fd7671f46ca4231deb86d5b55ceb902 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/error/index.d.mts @@ -0,0 +1,3 @@ +import { AbortError } from "./AbortError.mjs"; +import { TimeoutError } from "./TimeoutError.mjs"; +export { AbortError, TimeoutError }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/error/index.d.ts b/tools/ui/node_modules/es-toolkit/dist/error/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dd25ebf43f67eb40be4b796000392f58593413d1 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/error/index.d.ts @@ -0,0 +1,3 @@ +import { AbortError } from "./AbortError.js"; +import { TimeoutError } from "./TimeoutError.js"; +export { AbortError, TimeoutError }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/error/index.js b/tools/ui/node_modules/es-toolkit/dist/error/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a8c7140ac291c4cb1533a97f38defad1c653d197 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/error/index.js @@ -0,0 +1,5 @@ +Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); +const require_AbortError = require("./AbortError.js"); +const require_TimeoutError = require("./TimeoutError.js"); +exports.AbortError = require_AbortError.AbortError; +exports.TimeoutError = require_TimeoutError.TimeoutError; diff --git a/tools/ui/node_modules/es-toolkit/dist/error/index.mjs b/tools/ui/node_modules/es-toolkit/dist/error/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..55c7f7a844c096da790e577d502105e4d3fc0dd1 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/error/index.mjs @@ -0,0 +1,3 @@ +import { AbortError } from "./AbortError.mjs"; +import { TimeoutError } from "./TimeoutError.mjs"; +export { AbortError, TimeoutError }; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/after.d.mts b/tools/ui/node_modules/es-toolkit/dist/function/after.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..22ff2c62216e5c7c5429631ed3eb49ac65164c17 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/after.d.mts @@ -0,0 +1,32 @@ +//#region src/function/after.d.ts +/** + * Creates a function that only executes starting from the `n`-th call. + * The provided function will be invoked starting from the `n`-th call. + * + * This is particularly useful for scenarios involving events or asynchronous operations + * where an action should occur only after a certain number of invocations. + * + * @template F - The type of the function to be invoked. + * @param {number} n - The number of calls required for `func` to execute. + * @param {F} func - The function to be invoked. + * @returns {(...args: Parameters) => ReturnType | undefined} - A new function that: + * - Tracks the number of calls. + * - Invokes `func` starting from the `n`-th call. + * - Returns `undefined` if fewer than `n` calls have been made. + * @throws {Error} - Throws an error if `n` is negative. + * @example + * + * const afterFn = after(3, () => { + * console.log("called") + * }); + * + * // Will not log anything. + * afterFn() + * // Will not log anything. + * afterFn() + * // Will log 'called'. + * afterFn() + */ +declare function after any>(n: number, func: F): (...args: Parameters) => ReturnType | undefined; +//#endregion +export { after }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/after.d.ts b/tools/ui/node_modules/es-toolkit/dist/function/after.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..22ff2c62216e5c7c5429631ed3eb49ac65164c17 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/after.d.ts @@ -0,0 +1,32 @@ +//#region src/function/after.d.ts +/** + * Creates a function that only executes starting from the `n`-th call. + * The provided function will be invoked starting from the `n`-th call. + * + * This is particularly useful for scenarios involving events or asynchronous operations + * where an action should occur only after a certain number of invocations. + * + * @template F - The type of the function to be invoked. + * @param {number} n - The number of calls required for `func` to execute. + * @param {F} func - The function to be invoked. + * @returns {(...args: Parameters) => ReturnType | undefined} - A new function that: + * - Tracks the number of calls. + * - Invokes `func` starting from the `n`-th call. + * - Returns `undefined` if fewer than `n` calls have been made. + * @throws {Error} - Throws an error if `n` is negative. + * @example + * + * const afterFn = after(3, () => { + * console.log("called") + * }); + * + * // Will not log anything. + * afterFn() + * // Will not log anything. + * afterFn() + * // Will log 'called'. + * afterFn() + */ +declare function after any>(n: number, func: F): (...args: Parameters) => ReturnType | undefined; +//#endregion +export { after }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/after.js b/tools/ui/node_modules/es-toolkit/dist/function/after.js new file mode 100644 index 0000000000000000000000000000000000000000..3ddac45dac24ce5236fd32ce59e1db366fe42fb2 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/after.js @@ -0,0 +1,38 @@ +//#region src/function/after.ts +/** +* Creates a function that only executes starting from the `n`-th call. +* The provided function will be invoked starting from the `n`-th call. +* +* This is particularly useful for scenarios involving events or asynchronous operations +* where an action should occur only after a certain number of invocations. +* +* @template F - The type of the function to be invoked. +* @param {number} n - The number of calls required for `func` to execute. +* @param {F} func - The function to be invoked. +* @returns {(...args: Parameters) => ReturnType | undefined} - A new function that: +* - Tracks the number of calls. +* - Invokes `func` starting from the `n`-th call. +* - Returns `undefined` if fewer than `n` calls have been made. +* @throws {Error} - Throws an error if `n` is negative. +* @example +* +* const afterFn = after(3, () => { +* console.log("called") +* }); +* +* // Will not log anything. +* afterFn() +* // Will not log anything. +* afterFn() +* // Will log 'called'. +* afterFn() +*/ +function after(n, func) { + if (!Number.isInteger(n) || n < 0) throw new Error(`n must be a non-negative integer.`); + let counter = 0; + return (...args) => { + if (++counter >= n) return func(...args); + }; +} +//#endregion +exports.after = after; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/after.mjs b/tools/ui/node_modules/es-toolkit/dist/function/after.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5ffaa294cacda77991e1cbca2523ebcc1577e500 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/after.mjs @@ -0,0 +1,38 @@ +//#region src/function/after.ts +/** +* Creates a function that only executes starting from the `n`-th call. +* The provided function will be invoked starting from the `n`-th call. +* +* This is particularly useful for scenarios involving events or asynchronous operations +* where an action should occur only after a certain number of invocations. +* +* @template F - The type of the function to be invoked. +* @param {number} n - The number of calls required for `func` to execute. +* @param {F} func - The function to be invoked. +* @returns {(...args: Parameters) => ReturnType | undefined} - A new function that: +* - Tracks the number of calls. +* - Invokes `func` starting from the `n`-th call. +* - Returns `undefined` if fewer than `n` calls have been made. +* @throws {Error} - Throws an error if `n` is negative. +* @example +* +* const afterFn = after(3, () => { +* console.log("called") +* }); +* +* // Will not log anything. +* afterFn() +* // Will not log anything. +* afterFn() +* // Will log 'called'. +* afterFn() +*/ +function after(n, func) { + if (!Number.isInteger(n) || n < 0) throw new Error(`n must be a non-negative integer.`); + let counter = 0; + return (...args) => { + if (++counter >= n) return func(...args); + }; +} +//#endregion +export { after }; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/ary.d.mts b/tools/ui/node_modules/es-toolkit/dist/function/ary.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..b1bab8a00f190b19d8d97e39edcb40a1e2882f5a --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/ary.d.mts @@ -0,0 +1,22 @@ +//#region src/function/ary.d.ts +/** + * Creates a function that invokes func, with up to n arguments, ignoring any additional arguments. + * + * @template F - The type of the function. + * @param {F} func - The function to cap arguments for. + * @param {number} n - The arity cap. + * @returns {(...args: any[]) => ReturnType} Returns the new capped function. + * + * @example + * function fn(a: number, b: number, c: number) { + * return Array.from(arguments); + * } + * + * ary(fn, 0)(1, 2, 3) // [] + * ary(fn, 1)(1, 2, 3) // [1] + * ary(fn, 2)(1, 2, 3) // [1, 2] + * ary(fn, 3)(1, 2, 3) // [1, 2, 3] + */ +declare function ary any>(func: F, n: number): (...args: any[]) => ReturnType; +//#endregion +export { ary }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/ary.d.ts b/tools/ui/node_modules/es-toolkit/dist/function/ary.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b1bab8a00f190b19d8d97e39edcb40a1e2882f5a --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/ary.d.ts @@ -0,0 +1,22 @@ +//#region src/function/ary.d.ts +/** + * Creates a function that invokes func, with up to n arguments, ignoring any additional arguments. + * + * @template F - The type of the function. + * @param {F} func - The function to cap arguments for. + * @param {number} n - The arity cap. + * @returns {(...args: any[]) => ReturnType} Returns the new capped function. + * + * @example + * function fn(a: number, b: number, c: number) { + * return Array.from(arguments); + * } + * + * ary(fn, 0)(1, 2, 3) // [] + * ary(fn, 1)(1, 2, 3) // [1] + * ary(fn, 2)(1, 2, 3) // [1, 2] + * ary(fn, 3)(1, 2, 3) // [1, 2, 3] + */ +declare function ary any>(func: F, n: number): (...args: any[]) => ReturnType; +//#endregion +export { ary }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/ary.js b/tools/ui/node_modules/es-toolkit/dist/function/ary.js new file mode 100644 index 0000000000000000000000000000000000000000..a8d28ff2301f6df938121ec7218a4d308e4d66ad --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/ary.js @@ -0,0 +1,26 @@ +//#region src/function/ary.ts +/** +* Creates a function that invokes func, with up to n arguments, ignoring any additional arguments. +* +* @template F - The type of the function. +* @param {F} func - The function to cap arguments for. +* @param {number} n - The arity cap. +* @returns {(...args: any[]) => ReturnType} Returns the new capped function. +* +* @example +* function fn(a: number, b: number, c: number) { +* return Array.from(arguments); +* } +* +* ary(fn, 0)(1, 2, 3) // [] +* ary(fn, 1)(1, 2, 3) // [1] +* ary(fn, 2)(1, 2, 3) // [1, 2] +* ary(fn, 3)(1, 2, 3) // [1, 2, 3] +*/ +function ary(func, n) { + return function(...args) { + return func.apply(this, args.slice(0, n)); + }; +} +//#endregion +exports.ary = ary; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/ary.mjs b/tools/ui/node_modules/es-toolkit/dist/function/ary.mjs new file mode 100644 index 0000000000000000000000000000000000000000..86929e77b5cf8b4bdd9ef938a267eba4f8cca308 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/ary.mjs @@ -0,0 +1,26 @@ +//#region src/function/ary.ts +/** +* Creates a function that invokes func, with up to n arguments, ignoring any additional arguments. +* +* @template F - The type of the function. +* @param {F} func - The function to cap arguments for. +* @param {number} n - The arity cap. +* @returns {(...args: any[]) => ReturnType} Returns the new capped function. +* +* @example +* function fn(a: number, b: number, c: number) { +* return Array.from(arguments); +* } +* +* ary(fn, 0)(1, 2, 3) // [] +* ary(fn, 1)(1, 2, 3) // [1] +* ary(fn, 2)(1, 2, 3) // [1, 2] +* ary(fn, 3)(1, 2, 3) // [1, 2, 3] +*/ +function ary(func, n) { + return function(...args) { + return func.apply(this, args.slice(0, n)); + }; +} +//#endregion +export { ary }; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/asyncNoop.d.mts b/tools/ui/node_modules/es-toolkit/dist/function/asyncNoop.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..f377dadb4f04b3b20ac2589769328b45ae2626b4 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/asyncNoop.d.mts @@ -0,0 +1,13 @@ +//#region src/function/asyncNoop.d.ts +/** + * An asynchronous no-operation function that does nothing. + * This can be used as a placeholder or default function. + * + * @example + * asyncNoop(); // Does nothing + * + * @returns {Promise} This function returns a Promise that resolves to undefined. + */ +declare function asyncNoop(): Promise; +//#endregion +export { asyncNoop }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/asyncNoop.d.ts b/tools/ui/node_modules/es-toolkit/dist/function/asyncNoop.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f377dadb4f04b3b20ac2589769328b45ae2626b4 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/asyncNoop.d.ts @@ -0,0 +1,13 @@ +//#region src/function/asyncNoop.d.ts +/** + * An asynchronous no-operation function that does nothing. + * This can be used as a placeholder or default function. + * + * @example + * asyncNoop(); // Does nothing + * + * @returns {Promise} This function returns a Promise that resolves to undefined. + */ +declare function asyncNoop(): Promise; +//#endregion +export { asyncNoop }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/asyncNoop.js b/tools/ui/node_modules/es-toolkit/dist/function/asyncNoop.js new file mode 100644 index 0000000000000000000000000000000000000000..ab049b62308be63829bbad290b4951cf42025eaa --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/asyncNoop.js @@ -0,0 +1,13 @@ +//#region src/function/asyncNoop.ts +/** +* An asynchronous no-operation function that does nothing. +* This can be used as a placeholder or default function. +* +* @example +* asyncNoop(); // Does nothing +* +* @returns {Promise} This function returns a Promise that resolves to undefined. +*/ +async function asyncNoop() {} +//#endregion +exports.asyncNoop = asyncNoop; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/asyncNoop.mjs b/tools/ui/node_modules/es-toolkit/dist/function/asyncNoop.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7bbc268629ecace1ad7a3d2a2e5dee93fa186e99 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/asyncNoop.mjs @@ -0,0 +1,13 @@ +//#region src/function/asyncNoop.ts +/** +* An asynchronous no-operation function that does nothing. +* This can be used as a placeholder or default function. +* +* @example +* asyncNoop(); // Does nothing +* +* @returns {Promise} This function returns a Promise that resolves to undefined. +*/ +async function asyncNoop() {} +//#endregion +export { asyncNoop }; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/before.d.mts b/tools/ui/node_modules/es-toolkit/dist/function/before.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..f4a935e9839acdafdafbbbebfa9bdeae581bef68 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/before.d.mts @@ -0,0 +1,32 @@ +//#region src/function/before.d.ts +/** + * Creates a function that limits the number of times the given function (`func`) can be called. + * + * @template F - The type of the function to be invoked. + * @param {number} n - The number of times the returned function is allowed to call `func` before stopping. + * - If `n` is 0, `func` will never be called. + * - If `n` is a positive integer, `func` will be called up to `n-1` times. + * @param {F} func - The function to be called with the limit applied. + * @returns {(...args: Parameters) => ReturnType | undefined} - A new function that: + * - Tracks the number of calls. + * - Invokes `func` until the `n-1`-th call. + * - Returns `undefined` if the number of calls reaches or exceeds `n`, stopping further calls. + * @throws {Error} - Throw an error if `n` is negative. + * @example + * + * const beforeFn = before(3, () => { + * console.log("called"); + * }) + * + * // Will log 'called'. + * beforeFn(); + * + * // Will log 'called'. + * beforeFn(); + * + * // Will not log anything. + * beforeFn(); + */ +declare function before any>(n: number, func: F): (...args: Parameters) => ReturnType | undefined; +//#endregion +export { before }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/before.d.ts b/tools/ui/node_modules/es-toolkit/dist/function/before.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f4a935e9839acdafdafbbbebfa9bdeae581bef68 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/before.d.ts @@ -0,0 +1,32 @@ +//#region src/function/before.d.ts +/** + * Creates a function that limits the number of times the given function (`func`) can be called. + * + * @template F - The type of the function to be invoked. + * @param {number} n - The number of times the returned function is allowed to call `func` before stopping. + * - If `n` is 0, `func` will never be called. + * - If `n` is a positive integer, `func` will be called up to `n-1` times. + * @param {F} func - The function to be called with the limit applied. + * @returns {(...args: Parameters) => ReturnType | undefined} - A new function that: + * - Tracks the number of calls. + * - Invokes `func` until the `n-1`-th call. + * - Returns `undefined` if the number of calls reaches or exceeds `n`, stopping further calls. + * @throws {Error} - Throw an error if `n` is negative. + * @example + * + * const beforeFn = before(3, () => { + * console.log("called"); + * }) + * + * // Will log 'called'. + * beforeFn(); + * + * // Will log 'called'. + * beforeFn(); + * + * // Will not log anything. + * beforeFn(); + */ +declare function before any>(n: number, func: F): (...args: Parameters) => ReturnType | undefined; +//#endregion +export { before }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/before.js b/tools/ui/node_modules/es-toolkit/dist/function/before.js new file mode 100644 index 0000000000000000000000000000000000000000..5d931d0fdc2260bad535b550692364c57c852c7c --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/before.js @@ -0,0 +1,38 @@ +//#region src/function/before.ts +/** +* Creates a function that limits the number of times the given function (`func`) can be called. +* +* @template F - The type of the function to be invoked. +* @param {number} n - The number of times the returned function is allowed to call `func` before stopping. +* - If `n` is 0, `func` will never be called. +* - If `n` is a positive integer, `func` will be called up to `n-1` times. +* @param {F} func - The function to be called with the limit applied. +* @returns {(...args: Parameters) => ReturnType | undefined} - A new function that: +* - Tracks the number of calls. +* - Invokes `func` until the `n-1`-th call. +* - Returns `undefined` if the number of calls reaches or exceeds `n`, stopping further calls. +* @throws {Error} - Throw an error if `n` is negative. +* @example +* +* const beforeFn = before(3, () => { +* console.log("called"); +* }) +* +* // Will log 'called'. +* beforeFn(); +* +* // Will log 'called'. +* beforeFn(); +* +* // Will not log anything. +* beforeFn(); +*/ +function before(n, func) { + if (!Number.isInteger(n) || n < 0) throw new Error("n must be a non-negative integer."); + let counter = 0; + return (...args) => { + if (++counter < n) return func(...args); + }; +} +//#endregion +exports.before = before; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/before.mjs b/tools/ui/node_modules/es-toolkit/dist/function/before.mjs new file mode 100644 index 0000000000000000000000000000000000000000..018901311a3b8b790c03b5033e12153ae202e4f5 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/before.mjs @@ -0,0 +1,38 @@ +//#region src/function/before.ts +/** +* Creates a function that limits the number of times the given function (`func`) can be called. +* +* @template F - The type of the function to be invoked. +* @param {number} n - The number of times the returned function is allowed to call `func` before stopping. +* - If `n` is 0, `func` will never be called. +* - If `n` is a positive integer, `func` will be called up to `n-1` times. +* @param {F} func - The function to be called with the limit applied. +* @returns {(...args: Parameters) => ReturnType | undefined} - A new function that: +* - Tracks the number of calls. +* - Invokes `func` until the `n-1`-th call. +* - Returns `undefined` if the number of calls reaches or exceeds `n`, stopping further calls. +* @throws {Error} - Throw an error if `n` is negative. +* @example +* +* const beforeFn = before(3, () => { +* console.log("called"); +* }) +* +* // Will log 'called'. +* beforeFn(); +* +* // Will log 'called'. +* beforeFn(); +* +* // Will not log anything. +* beforeFn(); +*/ +function before(n, func) { + if (!Number.isInteger(n) || n < 0) throw new Error("n must be a non-negative integer."); + let counter = 0; + return (...args) => { + if (++counter < n) return func(...args); + }; +} +//#endregion +export { before }; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/curry.d.mts b/tools/ui/node_modules/es-toolkit/dist/function/curry.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..e777ea3d4c2ed5329c82c702df9923b258029d79 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/curry.d.mts @@ -0,0 +1,127 @@ +//#region src/function/curry.d.ts +/** + * Curries a function, allowing it to be called with a single argument at a time and returning a new function that takes the next argument. + * This process continues until all arguments have been provided, at which point the original function is called with all accumulated arguments. + * + * @param {() => R} func - The function to curry. + * @returns {() => R} A curried function. + * + * @example + * function noArgFunc() { + * return 42; + * } + * const curriedNoArgFunc = curry(noArgFunc); + * console.log(curriedNoArgFunc()); // 42 + */ +declare function curry(func: () => R): () => R; +/** + * Curries a function, allowing it to be called with a single argument at a time and returning a new function that takes the next argument. + * This process continues until all arguments have been provided, at which point the original function is called with all accumulated arguments. + * + * @param {(p: P) => R} func - The function to curry. + * @returns {(p: P) => R} A curried function. + * + * @example + * function oneArgFunc(a: number) { + * return a * 2; + * } + * const curriedOneArgFunc = curry(oneArgFunc); + * console.log(curriedOneArgFunc(5)); // 10 + */ +declare function curry(func: (p: P) => R): (p: P) => R; +/** + * Curries a function, allowing it to be called with a single argument at a time and returning a new function that takes the next argument. + * This process continues until all arguments have been provided, at which point the original function is called with all accumulated arguments. + * + * @param {(p1: P1, p2: P2) => R} func - The function to curry. + * @returns {(p1: P1) => (p2: P2) => R} A curried function. + * + * @example + * function twoArgFunc(a: number, b: number) { + * return a + b; + * } + * const curriedTwoArgFunc = curry(twoArgFunc); + * const add5 = curriedTwoArgFunc(5); + * console.log(add5(10)); // 15 + */ +declare function curry(func: (p1: P1, p2: P2) => R): (p1: P1) => (p2: P2) => R; +/** + * Curries a function, allowing it to be called with a single argument at a time and returning a new function that takes the next argument. + * This process continues until all arguments have been provided, at which point the original function is called with all accumulated arguments. + * + * @param {(p1: P1, p2: P2, p3: P3) => R} func - The function to curry. + * @returns {(p1: P1) => (p2: P2) => (p3: P3) => R} A curried function. + * + * @example + * function threeArgFunc(a: number, b: number, c: number) { + * return a + b + c; + * } + * const curriedThreeArgFunc = curry(threeArgFunc); + * const add1 = curriedThreeArgFunc(1); + * const add3 = add1(2); + * console.log(add3(3)); // 6 + */ +declare function curry(func: (p1: P1, p2: P2, p3: P3) => R): (p1: P1) => (p2: P2) => (p3: P3) => R; +/** + * Curries a function, allowing it to be called with a single argument at a time and returning a new function that takes the next argument. + * This process continues until all arguments have been provided, at which point the original function is called with all accumulated arguments. + * + * @param {(p1: P1, p2: P2, p3: P3, p4: P4) => R} func - The function to curry. + * @returns {(p1: P1) => (p2: P2) => (p3: P3) => (p4: P4) => R} A curried function. + * + * @example + * function fourArgFunc(a: number, b: number, c: number, d: number) { + * return a + b + c + d; + * } + * const curriedFourArgFunc = curry(fourArgFunc); + * const add1 = curriedFourArgFunc(1); + * const add3 = add1(2); + * const add6 = add3(3); + * console.log(add6(4)); // 10 + */ +declare function curry(func: (p1: P1, p2: P2, p3: P3, p4: P4) => R): (p1: P1) => (p2: P2) => (p3: P3) => (p4: P4) => R; +/** + * Curries a function, allowing it to be called with a single argument at a time and returning a new function that takes the next argument. + * This process continues until all arguments have been provided, at which point the original function is called with all accumulated arguments. + * + * @param {(p1: P1, p2: P2, p3: P3, p4: P4, p5: P5) => R} func - The function to curry. + * @returns {(p1: P1) => (p2: P2) => (p3: P3) => (p4: P4) => (p5: P5) => R} A curried function. + * + * @example + * function fiveArgFunc(a: number, b: number, c: number, d: number, e: number) { + * return a + b + c + d + e; + * } + * const curriedFiveArgFunc = curry(fiveArgFunc); + * const add1 = curriedFiveArgFunc(1); + * const add3 = add1(2); + * const add6 = add3(3); + * const add10 = add6(4); + * console.log(add10(5)); // 15 + */ +declare function curry(func: (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5) => R): (p1: P1) => (p2: P2) => (p3: P3) => (p4: P4) => (p5: P5) => R; +/** + * Curries a function, allowing it to be called with a single argument at a time and returning a new function that takes the next argument. + * This process continues until all arguments have been provided, at which point the original function is called with all accumulated arguments. + * + * @param {(...args: any[]) => any} func - The function to curry. + * @returns {(...args: any[]) => any} A curried function that can be called with a single argument at a time. + * + * @example + * function sum(a: number, b: number, c: number) { + * return a + b + c; + * } + * + * const curriedSum = curry(sum); + * + * // The parameter `a` should be given the value `10`. + * const add10 = curriedSum(10); + * + * // The parameter `b` should be given the value `15`. + * const add25 = add10(15); + * + * // The parameter `c` should be given the value `5`. The function 'sum' has received all its arguments and will now return a value. + * const result = add25(5); + */ +declare function curry(func: (...args: any[]) => any): (...args: any[]) => any; +//#endregion +export { curry }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/curry.d.ts b/tools/ui/node_modules/es-toolkit/dist/function/curry.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e777ea3d4c2ed5329c82c702df9923b258029d79 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/curry.d.ts @@ -0,0 +1,127 @@ +//#region src/function/curry.d.ts +/** + * Curries a function, allowing it to be called with a single argument at a time and returning a new function that takes the next argument. + * This process continues until all arguments have been provided, at which point the original function is called with all accumulated arguments. + * + * @param {() => R} func - The function to curry. + * @returns {() => R} A curried function. + * + * @example + * function noArgFunc() { + * return 42; + * } + * const curriedNoArgFunc = curry(noArgFunc); + * console.log(curriedNoArgFunc()); // 42 + */ +declare function curry(func: () => R): () => R; +/** + * Curries a function, allowing it to be called with a single argument at a time and returning a new function that takes the next argument. + * This process continues until all arguments have been provided, at which point the original function is called with all accumulated arguments. + * + * @param {(p: P) => R} func - The function to curry. + * @returns {(p: P) => R} A curried function. + * + * @example + * function oneArgFunc(a: number) { + * return a * 2; + * } + * const curriedOneArgFunc = curry(oneArgFunc); + * console.log(curriedOneArgFunc(5)); // 10 + */ +declare function curry(func: (p: P) => R): (p: P) => R; +/** + * Curries a function, allowing it to be called with a single argument at a time and returning a new function that takes the next argument. + * This process continues until all arguments have been provided, at which point the original function is called with all accumulated arguments. + * + * @param {(p1: P1, p2: P2) => R} func - The function to curry. + * @returns {(p1: P1) => (p2: P2) => R} A curried function. + * + * @example + * function twoArgFunc(a: number, b: number) { + * return a + b; + * } + * const curriedTwoArgFunc = curry(twoArgFunc); + * const add5 = curriedTwoArgFunc(5); + * console.log(add5(10)); // 15 + */ +declare function curry(func: (p1: P1, p2: P2) => R): (p1: P1) => (p2: P2) => R; +/** + * Curries a function, allowing it to be called with a single argument at a time and returning a new function that takes the next argument. + * This process continues until all arguments have been provided, at which point the original function is called with all accumulated arguments. + * + * @param {(p1: P1, p2: P2, p3: P3) => R} func - The function to curry. + * @returns {(p1: P1) => (p2: P2) => (p3: P3) => R} A curried function. + * + * @example + * function threeArgFunc(a: number, b: number, c: number) { + * return a + b + c; + * } + * const curriedThreeArgFunc = curry(threeArgFunc); + * const add1 = curriedThreeArgFunc(1); + * const add3 = add1(2); + * console.log(add3(3)); // 6 + */ +declare function curry(func: (p1: P1, p2: P2, p3: P3) => R): (p1: P1) => (p2: P2) => (p3: P3) => R; +/** + * Curries a function, allowing it to be called with a single argument at a time and returning a new function that takes the next argument. + * This process continues until all arguments have been provided, at which point the original function is called with all accumulated arguments. + * + * @param {(p1: P1, p2: P2, p3: P3, p4: P4) => R} func - The function to curry. + * @returns {(p1: P1) => (p2: P2) => (p3: P3) => (p4: P4) => R} A curried function. + * + * @example + * function fourArgFunc(a: number, b: number, c: number, d: number) { + * return a + b + c + d; + * } + * const curriedFourArgFunc = curry(fourArgFunc); + * const add1 = curriedFourArgFunc(1); + * const add3 = add1(2); + * const add6 = add3(3); + * console.log(add6(4)); // 10 + */ +declare function curry(func: (p1: P1, p2: P2, p3: P3, p4: P4) => R): (p1: P1) => (p2: P2) => (p3: P3) => (p4: P4) => R; +/** + * Curries a function, allowing it to be called with a single argument at a time and returning a new function that takes the next argument. + * This process continues until all arguments have been provided, at which point the original function is called with all accumulated arguments. + * + * @param {(p1: P1, p2: P2, p3: P3, p4: P4, p5: P5) => R} func - The function to curry. + * @returns {(p1: P1) => (p2: P2) => (p3: P3) => (p4: P4) => (p5: P5) => R} A curried function. + * + * @example + * function fiveArgFunc(a: number, b: number, c: number, d: number, e: number) { + * return a + b + c + d + e; + * } + * const curriedFiveArgFunc = curry(fiveArgFunc); + * const add1 = curriedFiveArgFunc(1); + * const add3 = add1(2); + * const add6 = add3(3); + * const add10 = add6(4); + * console.log(add10(5)); // 15 + */ +declare function curry(func: (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5) => R): (p1: P1) => (p2: P2) => (p3: P3) => (p4: P4) => (p5: P5) => R; +/** + * Curries a function, allowing it to be called with a single argument at a time and returning a new function that takes the next argument. + * This process continues until all arguments have been provided, at which point the original function is called with all accumulated arguments. + * + * @param {(...args: any[]) => any} func - The function to curry. + * @returns {(...args: any[]) => any} A curried function that can be called with a single argument at a time. + * + * @example + * function sum(a: number, b: number, c: number) { + * return a + b + c; + * } + * + * const curriedSum = curry(sum); + * + * // The parameter `a` should be given the value `10`. + * const add10 = curriedSum(10); + * + * // The parameter `b` should be given the value `15`. + * const add25 = add10(15); + * + * // The parameter `c` should be given the value `5`. The function 'sum' has received all its arguments and will now return a value. + * const result = add25(5); + */ +declare function curry(func: (...args: any[]) => any): (...args: any[]) => any; +//#endregion +export { curry }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/curry.js b/tools/ui/node_modules/es-toolkit/dist/function/curry.js new file mode 100644 index 0000000000000000000000000000000000000000..0fe851251903a63585b3bd2d1679f43169ae1148 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/curry.js @@ -0,0 +1,41 @@ +//#region src/function/curry.ts +/** +* Curries a function, allowing it to be called with a single argument at a time and returning a new function that takes the next argument. +* This process continues until all arguments have been provided, at which point the original function is called with all accumulated arguments. +* +* @param {(...args: any[]) => any} func - The function to curry. +* @returns {(...args: any[]) => any} A curried function that can be called with a single argument at a time. +* +* @example +* function sum(a: number, b: number, c: number) { +* return a + b + c; +* } +* +* const curriedSum = curry(sum); +* +* // The parameter `a` should be given the value `10`. +* const add10 = curriedSum(10); +* +* // The parameter `b` should be given the value `15`. +* const add25 = add10(15); +* +* // The parameter `c` should be given the value `5`. The function 'sum' has received all its arguments and will now return a value. +* const result = add25(5); +*/ +function curry(func) { + if (func.length === 0 || func.length === 1) return func; + return function(arg) { + return makeCurry(func, func.length, [arg]); + }; +} +function makeCurry(origin, argsLength, args) { + if (args.length === argsLength) return origin(...args); + else { + const next = function(arg) { + return makeCurry(origin, argsLength, [...args, arg]); + }; + return next; + } +} +//#endregion +exports.curry = curry; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/curry.mjs b/tools/ui/node_modules/es-toolkit/dist/function/curry.mjs new file mode 100644 index 0000000000000000000000000000000000000000..88b4193075cf4cc9a1e1f33c14b4338bd30c86c1 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/curry.mjs @@ -0,0 +1,41 @@ +//#region src/function/curry.ts +/** +* Curries a function, allowing it to be called with a single argument at a time and returning a new function that takes the next argument. +* This process continues until all arguments have been provided, at which point the original function is called with all accumulated arguments. +* +* @param {(...args: any[]) => any} func - The function to curry. +* @returns {(...args: any[]) => any} A curried function that can be called with a single argument at a time. +* +* @example +* function sum(a: number, b: number, c: number) { +* return a + b + c; +* } +* +* const curriedSum = curry(sum); +* +* // The parameter `a` should be given the value `10`. +* const add10 = curriedSum(10); +* +* // The parameter `b` should be given the value `15`. +* const add25 = add10(15); +* +* // The parameter `c` should be given the value `5`. The function 'sum' has received all its arguments and will now return a value. +* const result = add25(5); +*/ +function curry(func) { + if (func.length === 0 || func.length === 1) return func; + return function(arg) { + return makeCurry(func, func.length, [arg]); + }; +} +function makeCurry(origin, argsLength, args) { + if (args.length === argsLength) return origin(...args); + else { + const next = function(arg) { + return makeCurry(origin, argsLength, [...args, arg]); + }; + return next; + } +} +//#endregion +export { curry }; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/curryRight.d.mts b/tools/ui/node_modules/es-toolkit/dist/function/curryRight.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..f023816a33044a6b1a9045dd2412719b6d9041ce --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/curryRight.d.mts @@ -0,0 +1,141 @@ +//#region src/function/curryRight.d.ts +/** + * Curries a function, allowing it to be called with a single argument at a time and returning a new function that takes the next argument. + * This process continues until all arguments have been provided, at which point the original function is called with all accumulated arguments. + * + * Unlike `curry`, this function curries the function from right to left. + * + * @param {() => R} func - The function to curry. + * @returns {() => R} A curried function. + * + * @example + * function noArgFunc() { + * return 42; + * } + * const curriedNoArgFunc = curryRight(noArgFunc); + * console.log(curriedNoArgFunc()); // 42 + */ +declare function curryRight(func: () => R): () => R; +/** + * Curries a function, allowing it to be called with a single argument at a time and returning a new function that takes the next argument. + * This process continues until all arguments have been provided, at which point the original function is called with all accumulated arguments. + * + * Unlike `curry`, this function curries the function from right to left. + * + * @param {(p: P) => R} func - The function to curry. + * @returns {(p: P) => R} A curried function. + * + * @example + * function oneArgFunc(a: number) { + * return a * 2; + * } + * const curriedOneArgFunc = curryRight(oneArgFunc); + * console.log(curriedOneArgFunc(5)); // 10 + */ +declare function curryRight(func: (p: P) => R): (p: P) => R; +/** + * Curries a function, allowing it to be called with a single argument at a time and returning a new function that takes the next argument. + * This process continues until all arguments have been provided, at which point the original function is called with all accumulated arguments. + * + * Unlike `curry`, this function curries the function from right to left. + * + * @param {(p1: P1, p2: P2) => R} func - The function to curry. + * @returns {(p2: P2) => (p1: P1) => R} A curried function. + * + * @example + * function twoArgFunc(a: number, b: number) { + * return [a, b]; + * } + * const curriedTwoArgFunc = curryRight(twoArgFunc); + * const func = curriedTwoArgFunc(1); + * console.log(func(2)); // [2, 1] + */ +declare function curryRight(func: (p1: P1, p2: P2) => R): (p2: P2) => (p1: P1) => R; +/** + * Curries a function, allowing it to be called with a single argument at a time and returning a new function that takes the next argument. + * This process continues until all arguments have been provided, at which point the original function is called with all accumulated arguments. + * + * Unlike `curry`, this function curries the function from right to left. + * + * @param {(p1: P1, p2: P2, p3: P3) => R} func - The function to curry. + * @returns {(p3: P3) => (p2: P2) => (p1: P1) => R} A curried function. + * + * @example + * function threeArgFunc(a: number, b: number, c: number) { + * return [a, b, c]; + * } + * const curriedThreeArgFunc = curryRight(threeArgFunc); + * const func = curriedThreeArgFunc(1); + * const func2 = func(2); + * console.log(func2(3)); // [3, 2, 1] + */ +declare function curryRight(func: (p1: P1, p2: P2, p3: P3) => R): (p3: P3) => (p2: P2) => (p1: P1) => R; +/** + * Curries a function, allowing it to be called with a single argument at a time and returning a new function that takes the next argument. + * This process continues until all arguments have been provided, at which point the original function is called with all accumulated arguments. + * + * Unlike `curry`, this function curries the function from right to left. + * + * @param {(p1: P1, p2: P2, p3: P3, p4: P4) => R} func - The function to curry. + * @returns {(p4: P4) => (p3: P3) => (p2: P2) => (p1: P1) => R} A curried function. + * + * @example + * function fourArgFunc(a: number, b: number, c: number, d: number) { + * return [a, b, c, d]; + * } + * const curriedFourArgFunc = curryRight(fourArgFunc); + * const func = curriedFourArgFunc(1); + * const func2 = func(2); + * const func3 = func2(3); + * console.log(func3(4)); // [4, 3, 2, 1] + */ +declare function curryRight(func: (p1: P1, p2: P2, p3: P3, p4: P4) => R): (p4: P4) => (p3: P3) => (p2: P2) => (p1: P1) => R; +/** + * Curries a function, allowing it to be called with a single argument at a time and returning a new function that takes the next argument. + * This process continues until all arguments have been provided, at which point the original function is called with all accumulated arguments. + * + * Unlike `curry`, this function curries the function from right to left. + * + * @param {(p1: P1, p2: P2, p3: P3, p4: P4, p5: P5) => R} func - The function to curry. + * @returns {(p5: P5) => (p4: P4) => (p3: P3) => (p2: P2) => (p1: P1) => R} A curried function. + * + * @example + * function fiveArgFunc(a: number, b: number, c: number, d: number, e: number) { + * return [a, b, c, d, e]; + * } + * const curriedFiveArgFunc = curryRight(fiveArgFunc); + * const func = curriedFiveArgFunc(1); + * const func2 = func(2); + * const func3 = func2(3); + * const func4 = func3(4); + * console.log(func4(5)); // [5, 4, 3, 2, 1] + */ +declare function curryRight(func: (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5) => R): (p5: P5) => (p4: P4) => (p3: P3) => (p2: P2) => (p1: P1) => R; +/** + * Curries a function, allowing it to be called with a single argument at a time and returning a new function that takes the next argument. + * This process continues until all arguments have been provided, at which point the original function is called with all accumulated arguments. + * + * Unlike `curry`, this function curries the function from right to left. + * + * @param {(...args: any[]) => any} func - The function to curry. + * @returns {(...args: any[]) => any} A curried function. + * + * @example + * function sum(a: number, b: number, c: number) { + * return a + b + c; + * } + * + * const curriedSum = curryRight(sum); + * + * // The parameter `c` should be given the value `10`. + * const add10 = curriedSum(10); + * + * // The parameter `b` should be given the value `15`. + * const add25 = add10(15); + * + * // The parameter `a` should be given the value `5`. The function 'sum' has received all its arguments and will now return a value. + * const result = add25(5); // 30 + */ +declare function curryRight(func: (...args: any[]) => any): (...args: any[]) => any; +//#endregion +export { curryRight }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/curryRight.d.ts b/tools/ui/node_modules/es-toolkit/dist/function/curryRight.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f023816a33044a6b1a9045dd2412719b6d9041ce --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/curryRight.d.ts @@ -0,0 +1,141 @@ +//#region src/function/curryRight.d.ts +/** + * Curries a function, allowing it to be called with a single argument at a time and returning a new function that takes the next argument. + * This process continues until all arguments have been provided, at which point the original function is called with all accumulated arguments. + * + * Unlike `curry`, this function curries the function from right to left. + * + * @param {() => R} func - The function to curry. + * @returns {() => R} A curried function. + * + * @example + * function noArgFunc() { + * return 42; + * } + * const curriedNoArgFunc = curryRight(noArgFunc); + * console.log(curriedNoArgFunc()); // 42 + */ +declare function curryRight(func: () => R): () => R; +/** + * Curries a function, allowing it to be called with a single argument at a time and returning a new function that takes the next argument. + * This process continues until all arguments have been provided, at which point the original function is called with all accumulated arguments. + * + * Unlike `curry`, this function curries the function from right to left. + * + * @param {(p: P) => R} func - The function to curry. + * @returns {(p: P) => R} A curried function. + * + * @example + * function oneArgFunc(a: number) { + * return a * 2; + * } + * const curriedOneArgFunc = curryRight(oneArgFunc); + * console.log(curriedOneArgFunc(5)); // 10 + */ +declare function curryRight(func: (p: P) => R): (p: P) => R; +/** + * Curries a function, allowing it to be called with a single argument at a time and returning a new function that takes the next argument. + * This process continues until all arguments have been provided, at which point the original function is called with all accumulated arguments. + * + * Unlike `curry`, this function curries the function from right to left. + * + * @param {(p1: P1, p2: P2) => R} func - The function to curry. + * @returns {(p2: P2) => (p1: P1) => R} A curried function. + * + * @example + * function twoArgFunc(a: number, b: number) { + * return [a, b]; + * } + * const curriedTwoArgFunc = curryRight(twoArgFunc); + * const func = curriedTwoArgFunc(1); + * console.log(func(2)); // [2, 1] + */ +declare function curryRight(func: (p1: P1, p2: P2) => R): (p2: P2) => (p1: P1) => R; +/** + * Curries a function, allowing it to be called with a single argument at a time and returning a new function that takes the next argument. + * This process continues until all arguments have been provided, at which point the original function is called with all accumulated arguments. + * + * Unlike `curry`, this function curries the function from right to left. + * + * @param {(p1: P1, p2: P2, p3: P3) => R} func - The function to curry. + * @returns {(p3: P3) => (p2: P2) => (p1: P1) => R} A curried function. + * + * @example + * function threeArgFunc(a: number, b: number, c: number) { + * return [a, b, c]; + * } + * const curriedThreeArgFunc = curryRight(threeArgFunc); + * const func = curriedThreeArgFunc(1); + * const func2 = func(2); + * console.log(func2(3)); // [3, 2, 1] + */ +declare function curryRight(func: (p1: P1, p2: P2, p3: P3) => R): (p3: P3) => (p2: P2) => (p1: P1) => R; +/** + * Curries a function, allowing it to be called with a single argument at a time and returning a new function that takes the next argument. + * This process continues until all arguments have been provided, at which point the original function is called with all accumulated arguments. + * + * Unlike `curry`, this function curries the function from right to left. + * + * @param {(p1: P1, p2: P2, p3: P3, p4: P4) => R} func - The function to curry. + * @returns {(p4: P4) => (p3: P3) => (p2: P2) => (p1: P1) => R} A curried function. + * + * @example + * function fourArgFunc(a: number, b: number, c: number, d: number) { + * return [a, b, c, d]; + * } + * const curriedFourArgFunc = curryRight(fourArgFunc); + * const func = curriedFourArgFunc(1); + * const func2 = func(2); + * const func3 = func2(3); + * console.log(func3(4)); // [4, 3, 2, 1] + */ +declare function curryRight(func: (p1: P1, p2: P2, p3: P3, p4: P4) => R): (p4: P4) => (p3: P3) => (p2: P2) => (p1: P1) => R; +/** + * Curries a function, allowing it to be called with a single argument at a time and returning a new function that takes the next argument. + * This process continues until all arguments have been provided, at which point the original function is called with all accumulated arguments. + * + * Unlike `curry`, this function curries the function from right to left. + * + * @param {(p1: P1, p2: P2, p3: P3, p4: P4, p5: P5) => R} func - The function to curry. + * @returns {(p5: P5) => (p4: P4) => (p3: P3) => (p2: P2) => (p1: P1) => R} A curried function. + * + * @example + * function fiveArgFunc(a: number, b: number, c: number, d: number, e: number) { + * return [a, b, c, d, e]; + * } + * const curriedFiveArgFunc = curryRight(fiveArgFunc); + * const func = curriedFiveArgFunc(1); + * const func2 = func(2); + * const func3 = func2(3); + * const func4 = func3(4); + * console.log(func4(5)); // [5, 4, 3, 2, 1] + */ +declare function curryRight(func: (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5) => R): (p5: P5) => (p4: P4) => (p3: P3) => (p2: P2) => (p1: P1) => R; +/** + * Curries a function, allowing it to be called with a single argument at a time and returning a new function that takes the next argument. + * This process continues until all arguments have been provided, at which point the original function is called with all accumulated arguments. + * + * Unlike `curry`, this function curries the function from right to left. + * + * @param {(...args: any[]) => any} func - The function to curry. + * @returns {(...args: any[]) => any} A curried function. + * + * @example + * function sum(a: number, b: number, c: number) { + * return a + b + c; + * } + * + * const curriedSum = curryRight(sum); + * + * // The parameter `c` should be given the value `10`. + * const add10 = curriedSum(10); + * + * // The parameter `b` should be given the value `15`. + * const add25 = add10(15); + * + * // The parameter `a` should be given the value `5`. The function 'sum' has received all its arguments and will now return a value. + * const result = add25(5); // 30 + */ +declare function curryRight(func: (...args: any[]) => any): (...args: any[]) => any; +//#endregion +export { curryRight }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/curryRight.js b/tools/ui/node_modules/es-toolkit/dist/function/curryRight.js new file mode 100644 index 0000000000000000000000000000000000000000..46e7a8510f56b2382e28aa76eb809260d28a7c6c --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/curryRight.js @@ -0,0 +1,43 @@ +//#region src/function/curryRight.ts +/** +* Curries a function, allowing it to be called with a single argument at a time and returning a new function that takes the next argument. +* This process continues until all arguments have been provided, at which point the original function is called with all accumulated arguments. +* +* Unlike `curry`, this function curries the function from right to left. +* +* @param {(...args: any[]) => any} func - The function to curry. +* @returns {(...args: any[]) => any} A curried function. +* +* @example +* function sum(a: number, b: number, c: number) { +* return a + b + c; +* } +* +* const curriedSum = curryRight(sum); +* +* // The parameter `c` should be given the value `10`. +* const add10 = curriedSum(10); +* +* // The parameter `b` should be given the value `15`. +* const add25 = add10(15); +* +* // The parameter `a` should be given the value `5`. The function 'sum' has received all its arguments and will now return a value. +* const result = add25(5); // 30 +*/ +function curryRight(func) { + if (func.length === 0 || func.length === 1) return func; + return function(arg) { + return makeCurryRight(func, func.length, [arg]); + }; +} +function makeCurryRight(origin, argsLength, args) { + if (args.length === argsLength) return origin(...args); + else { + const next = function(arg) { + return makeCurryRight(origin, argsLength, [arg, ...args]); + }; + return next; + } +} +//#endregion +exports.curryRight = curryRight; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/curryRight.mjs b/tools/ui/node_modules/es-toolkit/dist/function/curryRight.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0d9e3073c5a5a28c9c66b0de5bed40a4fb0c1795 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/curryRight.mjs @@ -0,0 +1,43 @@ +//#region src/function/curryRight.ts +/** +* Curries a function, allowing it to be called with a single argument at a time and returning a new function that takes the next argument. +* This process continues until all arguments have been provided, at which point the original function is called with all accumulated arguments. +* +* Unlike `curry`, this function curries the function from right to left. +* +* @param {(...args: any[]) => any} func - The function to curry. +* @returns {(...args: any[]) => any} A curried function. +* +* @example +* function sum(a: number, b: number, c: number) { +* return a + b + c; +* } +* +* const curriedSum = curryRight(sum); +* +* // The parameter `c` should be given the value `10`. +* const add10 = curriedSum(10); +* +* // The parameter `b` should be given the value `15`. +* const add25 = add10(15); +* +* // The parameter `a` should be given the value `5`. The function 'sum' has received all its arguments and will now return a value. +* const result = add25(5); // 30 +*/ +function curryRight(func) { + if (func.length === 0 || func.length === 1) return func; + return function(arg) { + return makeCurryRight(func, func.length, [arg]); + }; +} +function makeCurryRight(origin, argsLength, args) { + if (args.length === argsLength) return origin(...args); + else { + const next = function(arg) { + return makeCurryRight(origin, argsLength, [arg, ...args]); + }; + return next; + } +} +//#endregion +export { curryRight }; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/debounce.d.mts b/tools/ui/node_modules/es-toolkit/dist/function/debounce.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..a334f51db1b7f82d120377b655161d6ff7ada246 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/debounce.d.mts @@ -0,0 +1,78 @@ +//#region src/function/debounce.d.ts +interface DebounceOptions { + /** + * An optional AbortSignal to cancel the debounced function. + */ + signal?: AbortSignal; + /** + * An optional array specifying whether the function should be invoked on the leading edge, trailing edge, or both. + * If `edges` includes "leading", the function will be invoked at the start of the delay period. + * If `edges` includes "trailing", the function will be invoked at the end of the delay period. + * If both "leading" and "trailing" are included, the function will be invoked at both the start and end of the delay period. + * @default ["trailing"] + */ + edges?: Array<'leading' | 'trailing'>; +} +interface DebouncedFunction void> { + (...args: Parameters): void; + /** + * Schedules the execution of the debounced function after the specified debounce delay. + * This method resets any existing timer, ensuring that the function is only invoked + * after the delay has elapsed since the last call to the debounced function. + * It is typically called internally whenever the debounced function is invoked. + * + * @returns {void} + */ + schedule: () => void; + /** + * Cancels any pending execution of the debounced function. + * This method clears the active timer and resets any stored context or arguments. + */ + cancel: () => void; + /** + * Immediately invokes the debounced function if there is a pending execution. + * This method executes the function right away if there is a pending execution. + */ + flush: () => void; +} +/** + * Creates a debounced function that delays invoking the provided function until after `debounceMs` milliseconds + * have elapsed since the last time the debounced function was invoked. The debounced function also has a `cancel` + * method to cancel any pending execution. + * + * @template F - The type of function. + * @param {F} func - The function to debounce. + * @param {number} debounceMs - The number of milliseconds to delay. + * @param {DebounceOptions} options - The options object + * @param {AbortSignal} options.signal - An optional AbortSignal to cancel the debounced function. + * @returns A new debounced function with a `cancel` method. + * + * @example + * const debouncedFunction = debounce(() => { + * console.log('Function executed'); + * }, 1000); + * + * // Will log 'Function executed' after 1 second if not called again in that time + * debouncedFunction(); + * + * // Will not log anything as the previous call is canceled + * debouncedFunction.cancel(); + * + * // With AbortSignal + * const controller = new AbortController(); + * const signal = controller.signal; + * const debouncedWithSignal = debounce(() => { + * console.log('Function executed'); + * }, 1000, { signal }); + * + * debouncedWithSignal(); + * + * // Will cancel the debounced function call + * controller.abort(); + */ +declare function debounce void>(func: F, debounceMs: number, { + signal, + edges +}?: DebounceOptions): DebouncedFunction; +//#endregion +export { DebounceOptions, DebouncedFunction, debounce }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/debounce.d.ts b/tools/ui/node_modules/es-toolkit/dist/function/debounce.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a334f51db1b7f82d120377b655161d6ff7ada246 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/debounce.d.ts @@ -0,0 +1,78 @@ +//#region src/function/debounce.d.ts +interface DebounceOptions { + /** + * An optional AbortSignal to cancel the debounced function. + */ + signal?: AbortSignal; + /** + * An optional array specifying whether the function should be invoked on the leading edge, trailing edge, or both. + * If `edges` includes "leading", the function will be invoked at the start of the delay period. + * If `edges` includes "trailing", the function will be invoked at the end of the delay period. + * If both "leading" and "trailing" are included, the function will be invoked at both the start and end of the delay period. + * @default ["trailing"] + */ + edges?: Array<'leading' | 'trailing'>; +} +interface DebouncedFunction void> { + (...args: Parameters): void; + /** + * Schedules the execution of the debounced function after the specified debounce delay. + * This method resets any existing timer, ensuring that the function is only invoked + * after the delay has elapsed since the last call to the debounced function. + * It is typically called internally whenever the debounced function is invoked. + * + * @returns {void} + */ + schedule: () => void; + /** + * Cancels any pending execution of the debounced function. + * This method clears the active timer and resets any stored context or arguments. + */ + cancel: () => void; + /** + * Immediately invokes the debounced function if there is a pending execution. + * This method executes the function right away if there is a pending execution. + */ + flush: () => void; +} +/** + * Creates a debounced function that delays invoking the provided function until after `debounceMs` milliseconds + * have elapsed since the last time the debounced function was invoked. The debounced function also has a `cancel` + * method to cancel any pending execution. + * + * @template F - The type of function. + * @param {F} func - The function to debounce. + * @param {number} debounceMs - The number of milliseconds to delay. + * @param {DebounceOptions} options - The options object + * @param {AbortSignal} options.signal - An optional AbortSignal to cancel the debounced function. + * @returns A new debounced function with a `cancel` method. + * + * @example + * const debouncedFunction = debounce(() => { + * console.log('Function executed'); + * }, 1000); + * + * // Will log 'Function executed' after 1 second if not called again in that time + * debouncedFunction(); + * + * // Will not log anything as the previous call is canceled + * debouncedFunction.cancel(); + * + * // With AbortSignal + * const controller = new AbortController(); + * const signal = controller.signal; + * const debouncedWithSignal = debounce(() => { + * console.log('Function executed'); + * }, 1000, { signal }); + * + * debouncedWithSignal(); + * + * // Will cancel the debounced function call + * controller.abort(); + */ +declare function debounce void>(func: F, debounceMs: number, { + signal, + edges +}?: DebounceOptions): DebouncedFunction; +//#endregion +export { DebounceOptions, DebouncedFunction, debounce }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/debounce.js b/tools/ui/node_modules/es-toolkit/dist/function/debounce.js new file mode 100644 index 0000000000000000000000000000000000000000..f7c9fe3177bc13be2eb8c90b46c647d873436429 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/debounce.js @@ -0,0 +1,90 @@ +//#region src/function/debounce.ts +/** +* Creates a debounced function that delays invoking the provided function until after `debounceMs` milliseconds +* have elapsed since the last time the debounced function was invoked. The debounced function also has a `cancel` +* method to cancel any pending execution. +* +* @template F - The type of function. +* @param {F} func - The function to debounce. +* @param {number} debounceMs - The number of milliseconds to delay. +* @param {DebounceOptions} options - The options object +* @param {AbortSignal} options.signal - An optional AbortSignal to cancel the debounced function. +* @returns A new debounced function with a `cancel` method. +* +* @example +* const debouncedFunction = debounce(() => { +* console.log('Function executed'); +* }, 1000); +* +* // Will log 'Function executed' after 1 second if not called again in that time +* debouncedFunction(); +* +* // Will not log anything as the previous call is canceled +* debouncedFunction.cancel(); +* +* // With AbortSignal +* const controller = new AbortController(); +* const signal = controller.signal; +* const debouncedWithSignal = debounce(() => { +* console.log('Function executed'); +* }, 1000, { signal }); +* +* debouncedWithSignal(); +* +* // Will cancel the debounced function call +* controller.abort(); +*/ +function debounce(func, debounceMs, { signal, edges } = {}) { + let pendingThis = void 0; + let pendingArgs = null; + const leading = edges != null && edges.includes("leading"); + const trailing = edges == null || edges.includes("trailing"); + const invoke = () => { + if (pendingArgs !== null) { + func.apply(pendingThis, pendingArgs); + pendingThis = void 0; + pendingArgs = null; + } + }; + const onTimerEnd = () => { + if (trailing) invoke(); + cancel(); + }; + let timeoutId = null; + const schedule = () => { + if (timeoutId != null) clearTimeout(timeoutId); + timeoutId = setTimeout(() => { + timeoutId = null; + onTimerEnd(); + }, debounceMs); + }; + const cancelTimer = () => { + if (timeoutId !== null) { + clearTimeout(timeoutId); + timeoutId = null; + } + }; + const cancel = () => { + cancelTimer(); + pendingThis = void 0; + pendingArgs = null; + }; + const flush = () => { + invoke(); + }; + const debounced = function(...args) { + if (signal?.aborted) return; + pendingThis = this; + pendingArgs = args; + const isFirstCall = timeoutId == null; + schedule(); + if (leading && isFirstCall) invoke(); + }; + debounced.schedule = schedule; + debounced.cancel = cancel; + debounced.flush = flush; + signal?.addEventListener("abort", cancel, { once: true }); + return debounced; +} +//#endregion +exports.debounce = debounce; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/debounce.mjs b/tools/ui/node_modules/es-toolkit/dist/function/debounce.mjs new file mode 100644 index 0000000000000000000000000000000000000000..da16c84f900aada6f81d95e01d13303b527d78bc --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/debounce.mjs @@ -0,0 +1,90 @@ +//#region src/function/debounce.ts +/** +* Creates a debounced function that delays invoking the provided function until after `debounceMs` milliseconds +* have elapsed since the last time the debounced function was invoked. The debounced function also has a `cancel` +* method to cancel any pending execution. +* +* @template F - The type of function. +* @param {F} func - The function to debounce. +* @param {number} debounceMs - The number of milliseconds to delay. +* @param {DebounceOptions} options - The options object +* @param {AbortSignal} options.signal - An optional AbortSignal to cancel the debounced function. +* @returns A new debounced function with a `cancel` method. +* +* @example +* const debouncedFunction = debounce(() => { +* console.log('Function executed'); +* }, 1000); +* +* // Will log 'Function executed' after 1 second if not called again in that time +* debouncedFunction(); +* +* // Will not log anything as the previous call is canceled +* debouncedFunction.cancel(); +* +* // With AbortSignal +* const controller = new AbortController(); +* const signal = controller.signal; +* const debouncedWithSignal = debounce(() => { +* console.log('Function executed'); +* }, 1000, { signal }); +* +* debouncedWithSignal(); +* +* // Will cancel the debounced function call +* controller.abort(); +*/ +function debounce(func, debounceMs, { signal, edges } = {}) { + let pendingThis = void 0; + let pendingArgs = null; + const leading = edges != null && edges.includes("leading"); + const trailing = edges == null || edges.includes("trailing"); + const invoke = () => { + if (pendingArgs !== null) { + func.apply(pendingThis, pendingArgs); + pendingThis = void 0; + pendingArgs = null; + } + }; + const onTimerEnd = () => { + if (trailing) invoke(); + cancel(); + }; + let timeoutId = null; + const schedule = () => { + if (timeoutId != null) clearTimeout(timeoutId); + timeoutId = setTimeout(() => { + timeoutId = null; + onTimerEnd(); + }, debounceMs); + }; + const cancelTimer = () => { + if (timeoutId !== null) { + clearTimeout(timeoutId); + timeoutId = null; + } + }; + const cancel = () => { + cancelTimer(); + pendingThis = void 0; + pendingArgs = null; + }; + const flush = () => { + invoke(); + }; + const debounced = function(...args) { + if (signal?.aborted) return; + pendingThis = this; + pendingArgs = args; + const isFirstCall = timeoutId == null; + schedule(); + if (leading && isFirstCall) invoke(); + }; + debounced.schedule = schedule; + debounced.cancel = cancel; + debounced.flush = flush; + signal?.addEventListener("abort", cancel, { once: true }); + return debounced; +} +//#endregion +export { debounce }; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/flow.d.mts b/tools/ui/node_modules/es-toolkit/dist/function/flow.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..b4f271a290fa2d0d81c4dede66c92ec5cc0f3422 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/flow.d.mts @@ -0,0 +1,133 @@ +//#region src/function/flow.d.ts +/** + * Creates a new function that executes the given functions in sequence. The return value of the previous function is passed as an argument to the next function. + * + * The `this` context of the returned function is also passed to the functions provided as parameters. + * + * @param {() => R} f The function to invoke. + * @returns {() => R} Returns the new composite function. + * + * @example + * function noArgFunc() { + * return 42; + * } + * + * const combined = flow(noArgFunc); + * console.log(combined()); // 42 + */ +declare function flow(f: () => R): () => R; +/** + * Creates a new function that executes the given functions in sequence. The return value of the previous function is passed as an argument to the next function. + * + * The `this` context of the returned function is also passed to the functions provided as parameters. + * + * @param {(...args: A) => R} f1 The function to invoke. + * @returns {(...args: A) => R} Returns the new composite function. + * + * @example + * function oneArgFunc(a: number) { + * return a * 2; + * } + * + * const combined = flow(oneArgFunc); + * console.log(combined(5)); // 10 + */ +declare function flow(f1: (...args: A) => R): (...args: A) => R; +/** + * Creates a new function that executes the given functions in sequence. The return value of the previous function is passed as an argument to the next function. + * + * The `this` context of the returned function is also passed to the functions provided as parameters. + * + * @param {(...args: A) => R1} f1 The function to invoke. + * @param {(a: R1) => R2} f2 The function to invoke. + * @returns {(...args: A) => R2} Returns the new composite function. + * + * @example + * const add = (x: number, y: number) => x + y; + * const square = (n: number) => n * n; + * + * const combined = flow(add, square); + * console.log(combined(1, 2)); // 9 + */ +declare function flow(f1: (...args: A) => R1, f2: (a: R1) => R2): (...args: A) => R2; +/** + * Creates a new function that executes the given functions in sequence. The return value of the previous function is passed as an argument to the next function. + * + * The `this` context of the returned function is also passed to the functions provided as parameters. + * + * @param {(...args: A) => R1} f1 The function to invoke. + * @param {(a: R1) => R2} f2 The function to invoke. + * @param {(a: R2) => R3} f3 The function to invoke. + * @returns {(...args: A) => R3} Returns the new composite function. + * + * @example + * const add = (x: number, y: number) => x + y; + * const square = (n: number) => n * n; + * const double = (n: number) => n * 2; + * + * const combined = flow(add, square, double); + * console.log(combined(1, 2)); // 18 + */ +declare function flow(f1: (...args: A) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3): (...args: A) => R3; +/** + * Creates a new function that executes the given functions in sequence. The return value of the previous function is passed as an argument to the next function. + * + * The `this` context of the returned function is also passed to the functions provided as parameters. + * + * @param {(...args: A) => R1} f1 The function to invoke. + * @param {(a: R1) => R2} f2 The function to invoke. + * @param {(a: R2) => R3} f3 The function to invoke. + * @param {(a: R3) => R4} f4 The function to invoke. + * @returns {(...args: A) => R4} Returns the new composite function. + * + * @example + * const add = (x: number, y: number) => x + y; + * const square = (n: number) => n * n; + * const double = (n: number) => n * 2; + * const toStr = (n: number) => n.toString(); + * + * const combined = flow(add, square, double, toStr); + * console.log(combined(1, 2)); // '18' + */ +declare function flow(f1: (...args: A) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): (...args: A) => R4; +/** + * Creates a new function that executes the given functions in sequence. The return value of the previous function is passed as an argument to the next function. + * + * The `this` context of the returned function is also passed to the functions provided as parameters. + * + * @param {(...args: A) => R1} f1 The function to invoke. + * @param {(a: R1) => R2} f2 The function to invoke. + * @param {(a: R2) => R3} f3 The function to invoke. + * @param {(a: R3) => R4} f4 The function to invoke. + * @param {(a: R4) => R5} f5 The function to invoke. + * @returns {(...args: A) => R5} Returns the new composite function. + * + * @example + * const add = (x: number, y: number) => x + y; + * const square = (n: number) => n * n; + * const double = (n: number) => n * 2; + * const toStr = (n: number) => n.toString(); + * const split = (s: string) => s.split(''); + * + * const combined = flow(add, square, double, toStr, split); + * console.log(combined(1, 2)); // ['1', '8'] + */ +declare function flow(f1: (...args: A) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): (...args: A) => R5; +/** + * Creates a new function that executes the given functions in sequence. The return value of the previous function is passed as an argument to the next function. + * + * The `this` context of the returned function is also passed to the functions provided as parameters. + * + * @param {Array<(...args: any[]) => any>} funcs The functions to invoke. + * @returns {(...args: any[]) => any} Returns the new composite function. + * + * @example + * const add = (x: number, y: number) => x + y; + * const square = (n: number) => n * n; + * + * const combined = flow(add, square); + * console.log(combined(1, 2)); // 9 + */ +declare function flow(...funcs: Array<(...args: any[]) => any>): (...args: any[]) => any; +//#endregion +export { flow }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/flow.d.ts b/tools/ui/node_modules/es-toolkit/dist/function/flow.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b4f271a290fa2d0d81c4dede66c92ec5cc0f3422 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/flow.d.ts @@ -0,0 +1,133 @@ +//#region src/function/flow.d.ts +/** + * Creates a new function that executes the given functions in sequence. The return value of the previous function is passed as an argument to the next function. + * + * The `this` context of the returned function is also passed to the functions provided as parameters. + * + * @param {() => R} f The function to invoke. + * @returns {() => R} Returns the new composite function. + * + * @example + * function noArgFunc() { + * return 42; + * } + * + * const combined = flow(noArgFunc); + * console.log(combined()); // 42 + */ +declare function flow(f: () => R): () => R; +/** + * Creates a new function that executes the given functions in sequence. The return value of the previous function is passed as an argument to the next function. + * + * The `this` context of the returned function is also passed to the functions provided as parameters. + * + * @param {(...args: A) => R} f1 The function to invoke. + * @returns {(...args: A) => R} Returns the new composite function. + * + * @example + * function oneArgFunc(a: number) { + * return a * 2; + * } + * + * const combined = flow(oneArgFunc); + * console.log(combined(5)); // 10 + */ +declare function flow(f1: (...args: A) => R): (...args: A) => R; +/** + * Creates a new function that executes the given functions in sequence. The return value of the previous function is passed as an argument to the next function. + * + * The `this` context of the returned function is also passed to the functions provided as parameters. + * + * @param {(...args: A) => R1} f1 The function to invoke. + * @param {(a: R1) => R2} f2 The function to invoke. + * @returns {(...args: A) => R2} Returns the new composite function. + * + * @example + * const add = (x: number, y: number) => x + y; + * const square = (n: number) => n * n; + * + * const combined = flow(add, square); + * console.log(combined(1, 2)); // 9 + */ +declare function flow(f1: (...args: A) => R1, f2: (a: R1) => R2): (...args: A) => R2; +/** + * Creates a new function that executes the given functions in sequence. The return value of the previous function is passed as an argument to the next function. + * + * The `this` context of the returned function is also passed to the functions provided as parameters. + * + * @param {(...args: A) => R1} f1 The function to invoke. + * @param {(a: R1) => R2} f2 The function to invoke. + * @param {(a: R2) => R3} f3 The function to invoke. + * @returns {(...args: A) => R3} Returns the new composite function. + * + * @example + * const add = (x: number, y: number) => x + y; + * const square = (n: number) => n * n; + * const double = (n: number) => n * 2; + * + * const combined = flow(add, square, double); + * console.log(combined(1, 2)); // 18 + */ +declare function flow(f1: (...args: A) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3): (...args: A) => R3; +/** + * Creates a new function that executes the given functions in sequence. The return value of the previous function is passed as an argument to the next function. + * + * The `this` context of the returned function is also passed to the functions provided as parameters. + * + * @param {(...args: A) => R1} f1 The function to invoke. + * @param {(a: R1) => R2} f2 The function to invoke. + * @param {(a: R2) => R3} f3 The function to invoke. + * @param {(a: R3) => R4} f4 The function to invoke. + * @returns {(...args: A) => R4} Returns the new composite function. + * + * @example + * const add = (x: number, y: number) => x + y; + * const square = (n: number) => n * n; + * const double = (n: number) => n * 2; + * const toStr = (n: number) => n.toString(); + * + * const combined = flow(add, square, double, toStr); + * console.log(combined(1, 2)); // '18' + */ +declare function flow(f1: (...args: A) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): (...args: A) => R4; +/** + * Creates a new function that executes the given functions in sequence. The return value of the previous function is passed as an argument to the next function. + * + * The `this` context of the returned function is also passed to the functions provided as parameters. + * + * @param {(...args: A) => R1} f1 The function to invoke. + * @param {(a: R1) => R2} f2 The function to invoke. + * @param {(a: R2) => R3} f3 The function to invoke. + * @param {(a: R3) => R4} f4 The function to invoke. + * @param {(a: R4) => R5} f5 The function to invoke. + * @returns {(...args: A) => R5} Returns the new composite function. + * + * @example + * const add = (x: number, y: number) => x + y; + * const square = (n: number) => n * n; + * const double = (n: number) => n * 2; + * const toStr = (n: number) => n.toString(); + * const split = (s: string) => s.split(''); + * + * const combined = flow(add, square, double, toStr, split); + * console.log(combined(1, 2)); // ['1', '8'] + */ +declare function flow(f1: (...args: A) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): (...args: A) => R5; +/** + * Creates a new function that executes the given functions in sequence. The return value of the previous function is passed as an argument to the next function. + * + * The `this` context of the returned function is also passed to the functions provided as parameters. + * + * @param {Array<(...args: any[]) => any>} funcs The functions to invoke. + * @returns {(...args: any[]) => any} Returns the new composite function. + * + * @example + * const add = (x: number, y: number) => x + y; + * const square = (n: number) => n * n; + * + * const combined = flow(add, square); + * console.log(combined(1, 2)); // 9 + */ +declare function flow(...funcs: Array<(...args: any[]) => any>): (...args: any[]) => any; +//#endregion +export { flow }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/flow.js b/tools/ui/node_modules/es-toolkit/dist/function/flow.js new file mode 100644 index 0000000000000000000000000000000000000000..b576507ce703c9a4e9a7aae62280bae7a472daeb --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/flow.js @@ -0,0 +1,25 @@ +//#region src/function/flow.ts +/** +* Creates a new function that executes the given functions in sequence. The return value of the previous function is passed as an argument to the next function. +* +* The `this` context of the returned function is also passed to the functions provided as parameters. +* +* @param {Array<(...args: any[]) => any>} funcs The functions to invoke. +* @returns {(...args: any[]) => any} Returns the new composite function. +* +* @example +* const add = (x: number, y: number) => x + y; +* const square = (n: number) => n * n; +* +* const combined = flow(add, square); +* console.log(combined(1, 2)); // 9 +*/ +function flow(...funcs) { + return function(...args) { + let result = funcs.length ? funcs[0].apply(this, args) : args[0]; + for (let i = 1; i < funcs.length; i++) result = funcs[i].call(this, result); + return result; + }; +} +//#endregion +exports.flow = flow; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/flow.mjs b/tools/ui/node_modules/es-toolkit/dist/function/flow.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3ea2a092e73465c665ab8e43d056822a5646ac72 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/flow.mjs @@ -0,0 +1,25 @@ +//#region src/function/flow.ts +/** +* Creates a new function that executes the given functions in sequence. The return value of the previous function is passed as an argument to the next function. +* +* The `this` context of the returned function is also passed to the functions provided as parameters. +* +* @param {Array<(...args: any[]) => any>} funcs The functions to invoke. +* @returns {(...args: any[]) => any} Returns the new composite function. +* +* @example +* const add = (x: number, y: number) => x + y; +* const square = (n: number) => n * n; +* +* const combined = flow(add, square); +* console.log(combined(1, 2)); // 9 +*/ +function flow(...funcs) { + return function(...args) { + let result = funcs.length ? funcs[0].apply(this, args) : args[0]; + for (let i = 1; i < funcs.length; i++) result = funcs[i].call(this, result); + return result; + }; +} +//#endregion +export { flow }; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/flowRight.d.mts b/tools/ui/node_modules/es-toolkit/dist/function/flowRight.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..7ed990cc9dfacc972cb53b2cb4d6ac6e953be4fd --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/flowRight.d.mts @@ -0,0 +1,145 @@ +//#region src/function/flowRight.d.ts +/** + * Creates a new function that executes the given functions in sequence from right to left. The return value of the previous function is passed as an argument to the next function. + * + * The `this` context of the returned function is also passed to the functions provided as parameters. + * + * This method is like `flow` except that it creates a function that invokes the given functions from right to left. + * + * @param {() => R} f The function to invoke. + * @returns {() => R} Returns the new composite function. + * + * @example + * function noArgFunc() { + * return 42; + * } + * const combined = flowRight(noArgFunc); + * console.log(combined()); // 42 + */ +declare function flowRight(f: () => R): () => R; +/** + * Creates a new function that executes the given functions in sequence from right to left. The return value of the previous function is passed as an argument to the next function. + * + * The `this` context of the returned function is also passed to the functions provided as parameters. + * + * This method is like `flow` except that it creates a function that invokes the given functions from right to left. + * + * @param {(...args: A) => R} f1 The function to invoke. + * @returns {(...args: A) => R} Returns the new composite function. + * + * @example + * function oneArgFunc(a: number) { + * return a * 2; + * } + * const combined = flowRight(oneArgFunc); + * console.log(combined(5)); // 10 + */ +declare function flowRight(f1: (...args: A) => R): (...args: A) => R; +/** + * Creates a new function that executes the given functions in sequence from right to left. The return value of the previous function is passed as an argument to the next function. + * + * The `this` context of the returned function is also passed to the functions provided as parameters. + * + * This method is like `flow` except that it creates a function that invokes the given functions from right to left. + * + * @param {(a: R1) => R2} f2 The function to invoke. + * @param {(...args: A) => R1} f1 The function to invoke. + * @returns {(...args: A) => R2} Returns the new composite function. + * + * @example + * const add = (x: number, y: number) => x + y; + * const square = (n: number) => n * n; + * + * const combined = flowRight(square, add); + * console.log(combined(1, 2)); // 9 + */ +declare function flowRight(f2: (a: R1) => R2, f1: (...args: A) => R1): (...args: A) => R2; +/** + * Creates a new function that executes the given functions in sequence from right to left. The return value of the previous function is passed as an argument to the next function. + * + * The `this` context of the returned function is also passed to the functions provided as parameters. + * + * This method is like `flow` except that it creates a function that invokes the given functions from right to left. + * + * @param {(a: R2) => R3} f3 The function to invoke. + * @param {(a: R1) => R2} f2 The function to invoke. + * @param {(...args: A) => R1} f1 The function to invoke. + * @returns {(...args: A) => R3} Returns the new composite function. + * + * @example + * const add = (x: number, y: number) => x + y; + * const square = (n: number) => n * n; + * const double = (n: number) => n * 2; + * + * const combined = flowRight(double, square, add); + * console.log(combined(1, 2)); // 18 + */ +declare function flowRight(f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: A) => R1): (...args: A) => R3; +/** + * Creates a new function that executes the given functions in sequence from right to left. The return value of the previous function is passed as an argument to the next function. + * + * The `this` context of the returned function is also passed to the functions provided as parameters. + * + * This method is like `flow` except that it creates a function that invokes the given functions from right to left. + * + * @param {(a: R3) => R4} f4 The function to invoke. + * @param {(a: R2) => R3} f3 The function to invoke. + * @param {(a: R1) => R2} f2 The function to invoke. + * @param {(...args: A) => R1} f1 The function to invoke. + * @returns {(...args: A) => R4} Returns the new composite function. + * + * @example + * const add = (x: number, y: number) => x + y; + * const square = (n: number) => n * n; + * const double = (n: number) => n * 2; + * const toStr = (n: number) => n.toString(); + * + * const combined = flowRight(toStr, double, square, add); + * console.log(combined(1, 2)); // '18' + */ +declare function flowRight(f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: A) => R1): (...args: A) => R4; +/** + * Creates a new function that executes the given functions in sequence from right to left. The return value of the previous function is passed as an argument to the next function. + * + * The `this` context of the returned function is also passed to the functions provided as parameters. + * + * This method is like `flow` except that it creates a function that invokes the given functions from right to left. + * + * @param {(a: R4) => R5} f5 The function to invoke. + * @param {(a: R3) => R4} f4 The function to invoke. + * @param {(a: R2) => R3} f3 The function to invoke. + * @param {(a: R1) => R2} f2 The function to invoke. + * @param {(...args: A) => R1} f1 The function to invoke. + * @returns {(...args: A) => R5} Returns the new composite function. + * + * @example + * const add = (x: number, y: number) => x + y; + * const square = (n: number) => n * n; + * const double = (n: number) => n * 2; + * const toStr = (n: number) => n.toString(); + * const split = (s: string) => s.split(''); + * + * const combined = flowRight(split, toStr, double, square, add); + * console.log(combined(1, 2)); // ['1', '8'] + */ +declare function flowRight(f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: A) => R1): (...args: A) => R5; +/** + * Creates a new function that executes the given functions in sequence from right to left. The return value of the previous function is passed as an argument to the next function. + * + * The `this` context of the returned function is also passed to the functions provided as parameters. + * + * This method is like `flow` except that it creates a function that invokes the given functions from right to left. + * + * @param {(...args: any[]) => any} funcs The functions to invoke. + * @returns {(...args: any[]) => any} Returns the new composite function. + * + * @example + * const add = (x: number, y: number) => x + y; + * const square = (n: number) => n * n; + * + * const combined = flowRight(square, add); + * console.log(combined(1, 2)); // 9 + */ +declare function flowRight(...funcs: Array<(...args: any[]) => any>): (...args: any[]) => any; +//#endregion +export { flowRight }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/flowRight.d.ts b/tools/ui/node_modules/es-toolkit/dist/function/flowRight.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7ed990cc9dfacc972cb53b2cb4d6ac6e953be4fd --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/flowRight.d.ts @@ -0,0 +1,145 @@ +//#region src/function/flowRight.d.ts +/** + * Creates a new function that executes the given functions in sequence from right to left. The return value of the previous function is passed as an argument to the next function. + * + * The `this` context of the returned function is also passed to the functions provided as parameters. + * + * This method is like `flow` except that it creates a function that invokes the given functions from right to left. + * + * @param {() => R} f The function to invoke. + * @returns {() => R} Returns the new composite function. + * + * @example + * function noArgFunc() { + * return 42; + * } + * const combined = flowRight(noArgFunc); + * console.log(combined()); // 42 + */ +declare function flowRight(f: () => R): () => R; +/** + * Creates a new function that executes the given functions in sequence from right to left. The return value of the previous function is passed as an argument to the next function. + * + * The `this` context of the returned function is also passed to the functions provided as parameters. + * + * This method is like `flow` except that it creates a function that invokes the given functions from right to left. + * + * @param {(...args: A) => R} f1 The function to invoke. + * @returns {(...args: A) => R} Returns the new composite function. + * + * @example + * function oneArgFunc(a: number) { + * return a * 2; + * } + * const combined = flowRight(oneArgFunc); + * console.log(combined(5)); // 10 + */ +declare function flowRight(f1: (...args: A) => R): (...args: A) => R; +/** + * Creates a new function that executes the given functions in sequence from right to left. The return value of the previous function is passed as an argument to the next function. + * + * The `this` context of the returned function is also passed to the functions provided as parameters. + * + * This method is like `flow` except that it creates a function that invokes the given functions from right to left. + * + * @param {(a: R1) => R2} f2 The function to invoke. + * @param {(...args: A) => R1} f1 The function to invoke. + * @returns {(...args: A) => R2} Returns the new composite function. + * + * @example + * const add = (x: number, y: number) => x + y; + * const square = (n: number) => n * n; + * + * const combined = flowRight(square, add); + * console.log(combined(1, 2)); // 9 + */ +declare function flowRight(f2: (a: R1) => R2, f1: (...args: A) => R1): (...args: A) => R2; +/** + * Creates a new function that executes the given functions in sequence from right to left. The return value of the previous function is passed as an argument to the next function. + * + * The `this` context of the returned function is also passed to the functions provided as parameters. + * + * This method is like `flow` except that it creates a function that invokes the given functions from right to left. + * + * @param {(a: R2) => R3} f3 The function to invoke. + * @param {(a: R1) => R2} f2 The function to invoke. + * @param {(...args: A) => R1} f1 The function to invoke. + * @returns {(...args: A) => R3} Returns the new composite function. + * + * @example + * const add = (x: number, y: number) => x + y; + * const square = (n: number) => n * n; + * const double = (n: number) => n * 2; + * + * const combined = flowRight(double, square, add); + * console.log(combined(1, 2)); // 18 + */ +declare function flowRight(f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: A) => R1): (...args: A) => R3; +/** + * Creates a new function that executes the given functions in sequence from right to left. The return value of the previous function is passed as an argument to the next function. + * + * The `this` context of the returned function is also passed to the functions provided as parameters. + * + * This method is like `flow` except that it creates a function that invokes the given functions from right to left. + * + * @param {(a: R3) => R4} f4 The function to invoke. + * @param {(a: R2) => R3} f3 The function to invoke. + * @param {(a: R1) => R2} f2 The function to invoke. + * @param {(...args: A) => R1} f1 The function to invoke. + * @returns {(...args: A) => R4} Returns the new composite function. + * + * @example + * const add = (x: number, y: number) => x + y; + * const square = (n: number) => n * n; + * const double = (n: number) => n * 2; + * const toStr = (n: number) => n.toString(); + * + * const combined = flowRight(toStr, double, square, add); + * console.log(combined(1, 2)); // '18' + */ +declare function flowRight(f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: A) => R1): (...args: A) => R4; +/** + * Creates a new function that executes the given functions in sequence from right to left. The return value of the previous function is passed as an argument to the next function. + * + * The `this` context of the returned function is also passed to the functions provided as parameters. + * + * This method is like `flow` except that it creates a function that invokes the given functions from right to left. + * + * @param {(a: R4) => R5} f5 The function to invoke. + * @param {(a: R3) => R4} f4 The function to invoke. + * @param {(a: R2) => R3} f3 The function to invoke. + * @param {(a: R1) => R2} f2 The function to invoke. + * @param {(...args: A) => R1} f1 The function to invoke. + * @returns {(...args: A) => R5} Returns the new composite function. + * + * @example + * const add = (x: number, y: number) => x + y; + * const square = (n: number) => n * n; + * const double = (n: number) => n * 2; + * const toStr = (n: number) => n.toString(); + * const split = (s: string) => s.split(''); + * + * const combined = flowRight(split, toStr, double, square, add); + * console.log(combined(1, 2)); // ['1', '8'] + */ +declare function flowRight(f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: A) => R1): (...args: A) => R5; +/** + * Creates a new function that executes the given functions in sequence from right to left. The return value of the previous function is passed as an argument to the next function. + * + * The `this` context of the returned function is also passed to the functions provided as parameters. + * + * This method is like `flow` except that it creates a function that invokes the given functions from right to left. + * + * @param {(...args: any[]) => any} funcs The functions to invoke. + * @returns {(...args: any[]) => any} Returns the new composite function. + * + * @example + * const add = (x: number, y: number) => x + y; + * const square = (n: number) => n * n; + * + * const combined = flowRight(square, add); + * console.log(combined(1, 2)); // 9 + */ +declare function flowRight(...funcs: Array<(...args: any[]) => any>): (...args: any[]) => any; +//#endregion +export { flowRight }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/flowRight.js b/tools/ui/node_modules/es-toolkit/dist/function/flowRight.js new file mode 100644 index 0000000000000000000000000000000000000000..0be453c520e99b602963ca492c7ba9ef52b023fd --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/flowRight.js @@ -0,0 +1,24 @@ +const require_flow = require("./flow.js"); +//#region src/function/flowRight.ts +/** +* Creates a new function that executes the given functions in sequence from right to left. The return value of the previous function is passed as an argument to the next function. +* +* The `this` context of the returned function is also passed to the functions provided as parameters. +* +* This method is like `flow` except that it creates a function that invokes the given functions from right to left. +* +* @param {(...args: any[]) => any} funcs The functions to invoke. +* @returns {(...args: any[]) => any} Returns the new composite function. +* +* @example +* const add = (x: number, y: number) => x + y; +* const square = (n: number) => n * n; +* +* const combined = flowRight(square, add); +* console.log(combined(1, 2)); // 9 +*/ +function flowRight(...funcs) { + return require_flow.flow(...funcs.reverse()); +} +//#endregion +exports.flowRight = flowRight; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/flowRight.mjs b/tools/ui/node_modules/es-toolkit/dist/function/flowRight.mjs new file mode 100644 index 0000000000000000000000000000000000000000..957a08ff0a0c833e86ef1ee6906ebd9e096e5fa5 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/flowRight.mjs @@ -0,0 +1,24 @@ +import { flow } from "./flow.mjs"; +//#region src/function/flowRight.ts +/** +* Creates a new function that executes the given functions in sequence from right to left. The return value of the previous function is passed as an argument to the next function. +* +* The `this` context of the returned function is also passed to the functions provided as parameters. +* +* This method is like `flow` except that it creates a function that invokes the given functions from right to left. +* +* @param {(...args: any[]) => any} funcs The functions to invoke. +* @returns {(...args: any[]) => any} Returns the new composite function. +* +* @example +* const add = (x: number, y: number) => x + y; +* const square = (n: number) => n * n; +* +* const combined = flowRight(square, add); +* console.log(combined(1, 2)); // 9 +*/ +function flowRight(...funcs) { + return flow(...funcs.reverse()); +} +//#endregion +export { flowRight }; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/identity.d.mts b/tools/ui/node_modules/es-toolkit/dist/function/identity.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..ec7a5d094322254fa20859b4f88eaa785da57a04 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/identity.d.mts @@ -0,0 +1,23 @@ +//#region src/function/identity.d.ts +/** + * Returns the input value unchanged. + * + * @template T - The type of the input value. + * @param {T} x - The value to be returned. + * @returns {T} The input value. + * + * @example + * // Returns 5 + * identity(5); + * + * @example + * // Returns 'hello' + * identity('hello'); + * + * @example + * // Returns { key: 'value' } + * identity({ key: 'value' }); + */ +declare function identity(x: T): T; +//#endregion +export { identity }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/identity.d.ts b/tools/ui/node_modules/es-toolkit/dist/function/identity.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ec7a5d094322254fa20859b4f88eaa785da57a04 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/identity.d.ts @@ -0,0 +1,23 @@ +//#region src/function/identity.d.ts +/** + * Returns the input value unchanged. + * + * @template T - The type of the input value. + * @param {T} x - The value to be returned. + * @returns {T} The input value. + * + * @example + * // Returns 5 + * identity(5); + * + * @example + * // Returns 'hello' + * identity('hello'); + * + * @example + * // Returns { key: 'value' } + * identity({ key: 'value' }); + */ +declare function identity(x: T): T; +//#endregion +export { identity }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/identity.js b/tools/ui/node_modules/es-toolkit/dist/function/identity.js new file mode 100644 index 0000000000000000000000000000000000000000..ebedc756b730cae0d6b43184788b78001843ccba --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/identity.js @@ -0,0 +1,25 @@ +//#region src/function/identity.ts +/** +* Returns the input value unchanged. +* +* @template T - The type of the input value. +* @param {T} x - The value to be returned. +* @returns {T} The input value. +* +* @example +* // Returns 5 +* identity(5); +* +* @example +* // Returns 'hello' +* identity('hello'); +* +* @example +* // Returns { key: 'value' } +* identity({ key: 'value' }); +*/ +function identity(x) { + return x; +} +//#endregion +exports.identity = identity; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/identity.mjs b/tools/ui/node_modules/es-toolkit/dist/function/identity.mjs new file mode 100644 index 0000000000000000000000000000000000000000..88abff0d0f5fcd8694385655f476d9b8cfceab68 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/identity.mjs @@ -0,0 +1,25 @@ +//#region src/function/identity.ts +/** +* Returns the input value unchanged. +* +* @template T - The type of the input value. +* @param {T} x - The value to be returned. +* @returns {T} The input value. +* +* @example +* // Returns 5 +* identity(5); +* +* @example +* // Returns 'hello' +* identity('hello'); +* +* @example +* // Returns { key: 'value' } +* identity({ key: 'value' }); +*/ +function identity(x) { + return x; +} +//#endregion +export { identity }; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/index.d.mts b/tools/ui/node_modules/es-toolkit/dist/function/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..44c5420fd4df99d79a0abba87651441f1d39ff12 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/index.d.mts @@ -0,0 +1,22 @@ +import { after } from "./after.mjs"; +import { ary } from "./ary.mjs"; +import { asyncNoop } from "./asyncNoop.mjs"; +import { before } from "./before.mjs"; +import { curry } from "./curry.mjs"; +import { curryRight } from "./curryRight.mjs"; +import { DebounceOptions, DebouncedFunction, debounce } from "./debounce.mjs"; +import { flow } from "./flow.mjs"; +import { flowRight } from "./flowRight.mjs"; +import { identity } from "./identity.mjs"; +import { MemoizeCache, memoize } from "./memoize.mjs"; +import { negate } from "./negate.mjs"; +import { noop } from "./noop.mjs"; +import { once } from "./once.mjs"; +import { partial } from "./partial.mjs"; +import { partialRight } from "./partialRight.mjs"; +import { rest } from "./rest.mjs"; +import { retry } from "./retry.mjs"; +import { spread } from "./spread.mjs"; +import { ThrottleOptions, ThrottledFunction, throttle } from "./throttle.mjs"; +import { unary } from "./unary.mjs"; +export { type DebounceOptions, type DebouncedFunction, type MemoizeCache, type ThrottleOptions, type ThrottledFunction, after, ary, asyncNoop, before, curry, curryRight, debounce, flow, flowRight, identity, memoize, negate, noop, once, partial, partialRight, rest, retry, spread, throttle, unary }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/index.d.ts b/tools/ui/node_modules/es-toolkit/dist/function/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..07ffcc1f3814f0214bf17041374356117cad33d7 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/index.d.ts @@ -0,0 +1,22 @@ +import { after } from "./after.js"; +import { ary } from "./ary.js"; +import { asyncNoop } from "./asyncNoop.js"; +import { before } from "./before.js"; +import { curry } from "./curry.js"; +import { curryRight } from "./curryRight.js"; +import { DebounceOptions, DebouncedFunction, debounce } from "./debounce.js"; +import { flow } from "./flow.js"; +import { flowRight } from "./flowRight.js"; +import { identity } from "./identity.js"; +import { MemoizeCache, memoize } from "./memoize.js"; +import { negate } from "./negate.js"; +import { noop } from "./noop.js"; +import { once } from "./once.js"; +import { partial } from "./partial.js"; +import { partialRight } from "./partialRight.js"; +import { rest } from "./rest.js"; +import { retry } from "./retry.js"; +import { spread } from "./spread.js"; +import { ThrottleOptions, ThrottledFunction, throttle } from "./throttle.js"; +import { unary } from "./unary.js"; +export { type DebounceOptions, type DebouncedFunction, type MemoizeCache, type ThrottleOptions, type ThrottledFunction, after, ary, asyncNoop, before, curry, curryRight, debounce, flow, flowRight, identity, memoize, negate, noop, once, partial, partialRight, rest, retry, spread, throttle, unary }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/index.js b/tools/ui/node_modules/es-toolkit/dist/function/index.js new file mode 100644 index 0000000000000000000000000000000000000000..2d2844e625b1da84e54570fe9c73ad4d2766efe9 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/index.js @@ -0,0 +1,43 @@ +Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); +const require_after = require("./after.js"); +const require_ary = require("./ary.js"); +const require_asyncNoop = require("./asyncNoop.js"); +const require_before = require("./before.js"); +const require_curry = require("./curry.js"); +const require_curryRight = require("./curryRight.js"); +const require_debounce = require("./debounce.js"); +const require_flow = require("./flow.js"); +const require_flowRight = require("./flowRight.js"); +const require_identity = require("./identity.js"); +const require_memoize = require("./memoize.js"); +const require_negate = require("./negate.js"); +const require_noop = require("./noop.js"); +const require_once = require("./once.js"); +const require_partial = require("./partial.js"); +const require_partialRight = require("./partialRight.js"); +const require_rest = require("./rest.js"); +const require_retry = require("./retry.js"); +const require_spread = require("./spread.js"); +const require_throttle = require("./throttle.js"); +const require_unary = require("./unary.js"); +exports.after = require_after.after; +exports.ary = require_ary.ary; +exports.asyncNoop = require_asyncNoop.asyncNoop; +exports.before = require_before.before; +exports.curry = require_curry.curry; +exports.curryRight = require_curryRight.curryRight; +exports.debounce = require_debounce.debounce; +exports.flow = require_flow.flow; +exports.flowRight = require_flowRight.flowRight; +exports.identity = require_identity.identity; +exports.memoize = require_memoize.memoize; +exports.negate = require_negate.negate; +exports.noop = require_noop.noop; +exports.once = require_once.once; +exports.partial = require_partial.partial; +exports.partialRight = require_partialRight.partialRight; +exports.rest = require_rest.rest; +exports.retry = require_retry.retry; +exports.spread = require_spread.spread; +exports.throttle = require_throttle.throttle; +exports.unary = require_unary.unary; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/index.mjs b/tools/ui/node_modules/es-toolkit/dist/function/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d36bd98f0ce255f524e588bfbd0be7d9eff99120 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/index.mjs @@ -0,0 +1,22 @@ +import { after } from "./after.mjs"; +import { ary } from "./ary.mjs"; +import { asyncNoop } from "./asyncNoop.mjs"; +import { before } from "./before.mjs"; +import { curry } from "./curry.mjs"; +import { curryRight } from "./curryRight.mjs"; +import { debounce } from "./debounce.mjs"; +import { flow } from "./flow.mjs"; +import { flowRight } from "./flowRight.mjs"; +import { identity } from "./identity.mjs"; +import { memoize } from "./memoize.mjs"; +import { negate } from "./negate.mjs"; +import { noop } from "./noop.mjs"; +import { once } from "./once.mjs"; +import { partial } from "./partial.mjs"; +import { partialRight } from "./partialRight.mjs"; +import { rest } from "./rest.mjs"; +import { retry } from "./retry.mjs"; +import { spread } from "./spread.mjs"; +import { throttle } from "./throttle.mjs"; +import { unary } from "./unary.mjs"; +export { after, ary, asyncNoop, before, curry, curryRight, debounce, flow, flowRight, identity, memoize, negate, noop, once, partial, partialRight, rest, retry, spread, throttle, unary }; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/memoize.d.mts b/tools/ui/node_modules/es-toolkit/dist/function/memoize.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..bee2eeeabe92e277703b5d474bd8c2a3ac1b29ea --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/memoize.d.mts @@ -0,0 +1,125 @@ +//#region src/function/memoize.d.ts +/** + * Creates a memoized version of the provided function. The memoized function caches + * results based on the argument it receives, so if the same argument is passed again, + * it returns the cached result instead of recomputing it. + * + * This function works with functions that take zero or just one argument. If your function + * originally takes multiple arguments, you should refactor it to take a single object or array + * that combines those arguments. + * + * If the argument is not primitive (e.g., arrays or objects), provide a + * `getCacheKey` function to generate a unique cache key for proper caching. + * + * @template F - The type of the function to be memoized. + * @param {F} fn - The function to be memoized. It should accept a single argument and return a value. + * @param {MemoizeOptions[0], ReturnType>} [options={}] - Optional configuration for the memoization. + * @param {MemoizeCache} [options.cache] - The cache object used to store results. Defaults to a new `Map`. + * @param {(args: A) => unknown} [options.getCacheKey] - An optional function to generate a unique cache key for each argument. + * + * @returns The memoized function with an additional `cache` property that exposes the internal cache. + * + * @example + * // Example using the default cache + * const add = (x: number) => x + 10; + * const memoizedAdd = memoize(add); + * + * console.log(memoizedAdd(5)); // 15 + * console.log(memoizedAdd(5)); // 15 (cached result) + * console.log(memoizedAdd.cache.size); // 1 + * + * @example + * // Example using a custom resolver + * const sum = (arr: number[]) => arr.reduce((x, y) => x + y, 0); + * const memoizedSum = memoize(sum, { getCacheKey: (arr: number[]) => arr.join(',') }); + * console.log(memoizedSum([1, 2])); // 3 + * console.log(memoizedSum([1, 2])); // 3 (cached result) + * console.log(memoizedSum.cache.size); // 1 + * + * @example + * // Example using a custom cache implementation + * class CustomCache implements MemoizeCache { + * private cache = new Map(); + * + * set(key: K, value: T): void { + * this.cache.set(key, value); + * } + * + * get(key: K): T | undefined { + * return this.cache.get(key); + * } + * + * has(key: K): boolean { + * return this.cache.has(key); + * } + * + * delete(key: K): boolean { + * return this.cache.delete(key); + * } + * + * clear(): void { + * this.cache.clear(); + * } + * + * get size(): number { + * return this.cache.size; + * } + * } + * const customCache = new CustomCache(); + * const memoizedSumWithCustomCache = memoize(sum, { cache: customCache }); + * console.log(memoizedSumWithCustomCache([1, 2])); // 3 + * console.log(memoizedSumWithCustomCache([1, 2])); // 3 (cached result) + * console.log(memoizedSumWithCustomCache.cache.size); // 1 + */ +declare function memoize any>(fn: F, options?: { + cache?: MemoizeCache>; + getCacheKey?: (args: Parameters[0]) => unknown; +}): F & { + cache: MemoizeCache>; +}; +/** + * Represents a cache for memoization, allowing storage and retrieval of computed values. + * + * @template K - The type of keys used to store values in the cache. + * @template V - The type of values stored in the cache. + */ +interface MemoizeCache { + /** + * Stores a value in the cache with the specified key. + * + * @param key - The key to associate with the value. + * @param value - The value to store in the cache. + */ + set(key: K, value: V): void; + /** + * Retrieves a value from the cache by its key. + * + * @param key - The key of the value to retrieve. + * @returns The value associated with the key, or undefined if the key does not exist. + */ + get(key: K): V | undefined; + /** + * Checks if a value exists in the cache for the specified key. + * + * @param key - The key to check for existence in the cache. + * @returns True if the cache contains the key, false otherwise. + */ + has(key: K): boolean; + /** + * Deletes a value from the cache by its key. + * + * @param key - The key of the value to delete. + * @returns True if the value was successfully deleted, false otherwise. + */ + delete(key: K): boolean | void; + /** + * Clears all values from the cache. + */ + clear(): void; + /** + * The number of entries in the cache. + */ + size: number; +} +//#endregion +export { MemoizeCache, memoize }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/memoize.d.ts b/tools/ui/node_modules/es-toolkit/dist/function/memoize.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bee2eeeabe92e277703b5d474bd8c2a3ac1b29ea --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/memoize.d.ts @@ -0,0 +1,125 @@ +//#region src/function/memoize.d.ts +/** + * Creates a memoized version of the provided function. The memoized function caches + * results based on the argument it receives, so if the same argument is passed again, + * it returns the cached result instead of recomputing it. + * + * This function works with functions that take zero or just one argument. If your function + * originally takes multiple arguments, you should refactor it to take a single object or array + * that combines those arguments. + * + * If the argument is not primitive (e.g., arrays or objects), provide a + * `getCacheKey` function to generate a unique cache key for proper caching. + * + * @template F - The type of the function to be memoized. + * @param {F} fn - The function to be memoized. It should accept a single argument and return a value. + * @param {MemoizeOptions[0], ReturnType>} [options={}] - Optional configuration for the memoization. + * @param {MemoizeCache} [options.cache] - The cache object used to store results. Defaults to a new `Map`. + * @param {(args: A) => unknown} [options.getCacheKey] - An optional function to generate a unique cache key for each argument. + * + * @returns The memoized function with an additional `cache` property that exposes the internal cache. + * + * @example + * // Example using the default cache + * const add = (x: number) => x + 10; + * const memoizedAdd = memoize(add); + * + * console.log(memoizedAdd(5)); // 15 + * console.log(memoizedAdd(5)); // 15 (cached result) + * console.log(memoizedAdd.cache.size); // 1 + * + * @example + * // Example using a custom resolver + * const sum = (arr: number[]) => arr.reduce((x, y) => x + y, 0); + * const memoizedSum = memoize(sum, { getCacheKey: (arr: number[]) => arr.join(',') }); + * console.log(memoizedSum([1, 2])); // 3 + * console.log(memoizedSum([1, 2])); // 3 (cached result) + * console.log(memoizedSum.cache.size); // 1 + * + * @example + * // Example using a custom cache implementation + * class CustomCache implements MemoizeCache { + * private cache = new Map(); + * + * set(key: K, value: T): void { + * this.cache.set(key, value); + * } + * + * get(key: K): T | undefined { + * return this.cache.get(key); + * } + * + * has(key: K): boolean { + * return this.cache.has(key); + * } + * + * delete(key: K): boolean { + * return this.cache.delete(key); + * } + * + * clear(): void { + * this.cache.clear(); + * } + * + * get size(): number { + * return this.cache.size; + * } + * } + * const customCache = new CustomCache(); + * const memoizedSumWithCustomCache = memoize(sum, { cache: customCache }); + * console.log(memoizedSumWithCustomCache([1, 2])); // 3 + * console.log(memoizedSumWithCustomCache([1, 2])); // 3 (cached result) + * console.log(memoizedSumWithCustomCache.cache.size); // 1 + */ +declare function memoize any>(fn: F, options?: { + cache?: MemoizeCache>; + getCacheKey?: (args: Parameters[0]) => unknown; +}): F & { + cache: MemoizeCache>; +}; +/** + * Represents a cache for memoization, allowing storage and retrieval of computed values. + * + * @template K - The type of keys used to store values in the cache. + * @template V - The type of values stored in the cache. + */ +interface MemoizeCache { + /** + * Stores a value in the cache with the specified key. + * + * @param key - The key to associate with the value. + * @param value - The value to store in the cache. + */ + set(key: K, value: V): void; + /** + * Retrieves a value from the cache by its key. + * + * @param key - The key of the value to retrieve. + * @returns The value associated with the key, or undefined if the key does not exist. + */ + get(key: K): V | undefined; + /** + * Checks if a value exists in the cache for the specified key. + * + * @param key - The key to check for existence in the cache. + * @returns True if the cache contains the key, false otherwise. + */ + has(key: K): boolean; + /** + * Deletes a value from the cache by its key. + * + * @param key - The key of the value to delete. + * @returns True if the value was successfully deleted, false otherwise. + */ + delete(key: K): boolean | void; + /** + * Clears all values from the cache. + */ + clear(): void; + /** + * The number of entries in the cache. + */ + size: number; +} +//#endregion +export { MemoizeCache, memoize }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/memoize.js b/tools/ui/node_modules/es-toolkit/dist/function/memoize.js new file mode 100644 index 0000000000000000000000000000000000000000..0962f23621804d1c49ecf502f692e98916f90f0f --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/memoize.js @@ -0,0 +1,87 @@ +//#region src/function/memoize.ts +/** +* Creates a memoized version of the provided function. The memoized function caches +* results based on the argument it receives, so if the same argument is passed again, +* it returns the cached result instead of recomputing it. +* +* This function works with functions that take zero or just one argument. If your function +* originally takes multiple arguments, you should refactor it to take a single object or array +* that combines those arguments. +* +* If the argument is not primitive (e.g., arrays or objects), provide a +* `getCacheKey` function to generate a unique cache key for proper caching. +* +* @template F - The type of the function to be memoized. +* @param {F} fn - The function to be memoized. It should accept a single argument and return a value. +* @param {MemoizeOptions[0], ReturnType>} [options={}] - Optional configuration for the memoization. +* @param {MemoizeCache} [options.cache] - The cache object used to store results. Defaults to a new `Map`. +* @param {(args: A) => unknown} [options.getCacheKey] - An optional function to generate a unique cache key for each argument. +* +* @returns The memoized function with an additional `cache` property that exposes the internal cache. +* +* @example +* // Example using the default cache +* const add = (x: number) => x + 10; +* const memoizedAdd = memoize(add); +* +* console.log(memoizedAdd(5)); // 15 +* console.log(memoizedAdd(5)); // 15 (cached result) +* console.log(memoizedAdd.cache.size); // 1 +* +* @example +* // Example using a custom resolver +* const sum = (arr: number[]) => arr.reduce((x, y) => x + y, 0); +* const memoizedSum = memoize(sum, { getCacheKey: (arr: number[]) => arr.join(',') }); +* console.log(memoizedSum([1, 2])); // 3 +* console.log(memoizedSum([1, 2])); // 3 (cached result) +* console.log(memoizedSum.cache.size); // 1 +* +* @example +* // Example using a custom cache implementation +* class CustomCache implements MemoizeCache { +* private cache = new Map(); +* +* set(key: K, value: T): void { +* this.cache.set(key, value); +* } +* +* get(key: K): T | undefined { +* return this.cache.get(key); +* } +* +* has(key: K): boolean { +* return this.cache.has(key); +* } +* +* delete(key: K): boolean { +* return this.cache.delete(key); +* } +* +* clear(): void { +* this.cache.clear(); +* } +* +* get size(): number { +* return this.cache.size; +* } +* } +* const customCache = new CustomCache(); +* const memoizedSumWithCustomCache = memoize(sum, { cache: customCache }); +* console.log(memoizedSumWithCustomCache([1, 2])); // 3 +* console.log(memoizedSumWithCustomCache([1, 2])); // 3 (cached result) +* console.log(memoizedSumWithCustomCache.cache.size); // 1 +*/ +function memoize(fn, options = {}) { + const { cache = /* @__PURE__ */ new Map(), getCacheKey } = options; + const memoizedFn = function(arg) { + const key = getCacheKey ? getCacheKey(arg) : arg; + if (cache.has(key)) return cache.get(key); + const result = fn.call(this, arg); + cache.set(key, result); + return result; + }; + memoizedFn.cache = cache; + return memoizedFn; +} +//#endregion +exports.memoize = memoize; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/memoize.mjs b/tools/ui/node_modules/es-toolkit/dist/function/memoize.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a01217e86d4c659854ed77bb9b04fbd74c6653b8 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/memoize.mjs @@ -0,0 +1,87 @@ +//#region src/function/memoize.ts +/** +* Creates a memoized version of the provided function. The memoized function caches +* results based on the argument it receives, so if the same argument is passed again, +* it returns the cached result instead of recomputing it. +* +* This function works with functions that take zero or just one argument. If your function +* originally takes multiple arguments, you should refactor it to take a single object or array +* that combines those arguments. +* +* If the argument is not primitive (e.g., arrays or objects), provide a +* `getCacheKey` function to generate a unique cache key for proper caching. +* +* @template F - The type of the function to be memoized. +* @param {F} fn - The function to be memoized. It should accept a single argument and return a value. +* @param {MemoizeOptions[0], ReturnType>} [options={}] - Optional configuration for the memoization. +* @param {MemoizeCache} [options.cache] - The cache object used to store results. Defaults to a new `Map`. +* @param {(args: A) => unknown} [options.getCacheKey] - An optional function to generate a unique cache key for each argument. +* +* @returns The memoized function with an additional `cache` property that exposes the internal cache. +* +* @example +* // Example using the default cache +* const add = (x: number) => x + 10; +* const memoizedAdd = memoize(add); +* +* console.log(memoizedAdd(5)); // 15 +* console.log(memoizedAdd(5)); // 15 (cached result) +* console.log(memoizedAdd.cache.size); // 1 +* +* @example +* // Example using a custom resolver +* const sum = (arr: number[]) => arr.reduce((x, y) => x + y, 0); +* const memoizedSum = memoize(sum, { getCacheKey: (arr: number[]) => arr.join(',') }); +* console.log(memoizedSum([1, 2])); // 3 +* console.log(memoizedSum([1, 2])); // 3 (cached result) +* console.log(memoizedSum.cache.size); // 1 +* +* @example +* // Example using a custom cache implementation +* class CustomCache implements MemoizeCache { +* private cache = new Map(); +* +* set(key: K, value: T): void { +* this.cache.set(key, value); +* } +* +* get(key: K): T | undefined { +* return this.cache.get(key); +* } +* +* has(key: K): boolean { +* return this.cache.has(key); +* } +* +* delete(key: K): boolean { +* return this.cache.delete(key); +* } +* +* clear(): void { +* this.cache.clear(); +* } +* +* get size(): number { +* return this.cache.size; +* } +* } +* const customCache = new CustomCache(); +* const memoizedSumWithCustomCache = memoize(sum, { cache: customCache }); +* console.log(memoizedSumWithCustomCache([1, 2])); // 3 +* console.log(memoizedSumWithCustomCache([1, 2])); // 3 (cached result) +* console.log(memoizedSumWithCustomCache.cache.size); // 1 +*/ +function memoize(fn, options = {}) { + const { cache = /* @__PURE__ */ new Map(), getCacheKey } = options; + const memoizedFn = function(arg) { + const key = getCacheKey ? getCacheKey(arg) : arg; + if (cache.has(key)) return cache.get(key); + const result = fn.call(this, arg); + cache.set(key, result); + return result; + }; + memoizedFn.cache = cache; + return memoizedFn; +} +//#endregion +export { memoize }; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/negate.d.mts b/tools/ui/node_modules/es-toolkit/dist/function/negate.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..032603c6b88a8b7dd7caeaac6e3142e9489de563 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/negate.d.mts @@ -0,0 +1,17 @@ +//#region src/function/negate.d.ts +/** + * Creates a function that negates the result of the predicate function. + * + * @template F - The type of the function to negate. + * @param {F} func - The function to negate. + * @returns {F} The new negated function, which negates the boolean result of `func`. + * + * @example + * const array = [1, 2, 3, 4, 5, 6]; + * const isEven = (n: number) => n % 2 === 0; + * const result = array.filter(negate(isEven)); + * // result will be [1, 3, 5] + */ +declare function negate boolean>(func: F): F; +//#endregion +export { negate }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/negate.d.ts b/tools/ui/node_modules/es-toolkit/dist/function/negate.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..032603c6b88a8b7dd7caeaac6e3142e9489de563 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/negate.d.ts @@ -0,0 +1,17 @@ +//#region src/function/negate.d.ts +/** + * Creates a function that negates the result of the predicate function. + * + * @template F - The type of the function to negate. + * @param {F} func - The function to negate. + * @returns {F} The new negated function, which negates the boolean result of `func`. + * + * @example + * const array = [1, 2, 3, 4, 5, 6]; + * const isEven = (n: number) => n % 2 === 0; + * const result = array.filter(negate(isEven)); + * // result will be [1, 3, 5] + */ +declare function negate boolean>(func: F): F; +//#endregion +export { negate }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/negate.js b/tools/ui/node_modules/es-toolkit/dist/function/negate.js new file mode 100644 index 0000000000000000000000000000000000000000..e46d4fdde4424cb44bc1620852a27eef7f561142 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/negate.js @@ -0,0 +1,19 @@ +//#region src/function/negate.ts +/** +* Creates a function that negates the result of the predicate function. +* +* @template F - The type of the function to negate. +* @param {F} func - The function to negate. +* @returns {F} The new negated function, which negates the boolean result of `func`. +* +* @example +* const array = [1, 2, 3, 4, 5, 6]; +* const isEven = (n: number) => n % 2 === 0; +* const result = array.filter(negate(isEven)); +* // result will be [1, 3, 5] +*/ +function negate(func) { + return ((...args) => !func(...args)); +} +//#endregion +exports.negate = negate; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/negate.mjs b/tools/ui/node_modules/es-toolkit/dist/function/negate.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6151fb0249b456755aebad0424306b5678df8242 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/negate.mjs @@ -0,0 +1,19 @@ +//#region src/function/negate.ts +/** +* Creates a function that negates the result of the predicate function. +* +* @template F - The type of the function to negate. +* @param {F} func - The function to negate. +* @returns {F} The new negated function, which negates the boolean result of `func`. +* +* @example +* const array = [1, 2, 3, 4, 5, 6]; +* const isEven = (n: number) => n % 2 === 0; +* const result = array.filter(negate(isEven)); +* // result will be [1, 3, 5] +*/ +function negate(func) { + return ((...args) => !func(...args)); +} +//#endregion +export { negate }; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/noop.d.mts b/tools/ui/node_modules/es-toolkit/dist/function/noop.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..fbe10e3c595baf676b024f828cf688de546c1792 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/noop.d.mts @@ -0,0 +1,13 @@ +//#region src/function/noop.d.ts +/** + * A no-operation function that does nothing. + * This can be used as a placeholder or default function. + * + * @example + * noop(); // Does nothing + * + * @returns {void} This function does not return anything. + */ +declare function noop(): void; +//#endregion +export { noop }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/noop.d.ts b/tools/ui/node_modules/es-toolkit/dist/function/noop.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fbe10e3c595baf676b024f828cf688de546c1792 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/noop.d.ts @@ -0,0 +1,13 @@ +//#region src/function/noop.d.ts +/** + * A no-operation function that does nothing. + * This can be used as a placeholder or default function. + * + * @example + * noop(); // Does nothing + * + * @returns {void} This function does not return anything. + */ +declare function noop(): void; +//#endregion +export { noop }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/noop.js b/tools/ui/node_modules/es-toolkit/dist/function/noop.js new file mode 100644 index 0000000000000000000000000000000000000000..c4a3c42057ada554a90196033161cca9577de5ae --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/noop.js @@ -0,0 +1,13 @@ +//#region src/function/noop.ts +/** +* A no-operation function that does nothing. +* This can be used as a placeholder or default function. +* +* @example +* noop(); // Does nothing +* +* @returns {void} This function does not return anything. +*/ +function noop() {} +//#endregion +exports.noop = noop; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/noop.mjs b/tools/ui/node_modules/es-toolkit/dist/function/noop.mjs new file mode 100644 index 0000000000000000000000000000000000000000..367b985546d1166a43d024da5b11e333dc612b61 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/noop.mjs @@ -0,0 +1,13 @@ +//#region src/function/noop.ts +/** +* A no-operation function that does nothing. +* This can be used as a placeholder or default function. +* +* @example +* noop(); // Does nothing +* +* @returns {void} This function does not return anything. +*/ +function noop() {} +//#endregion +export { noop }; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/once.d.mts b/tools/ui/node_modules/es-toolkit/dist/function/once.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..73a1f949d3cc3ef7db61eec3437da745c0e922be --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/once.d.mts @@ -0,0 +1,18 @@ +//#region src/function/once.d.ts +/** + * Creates a function that is restricted to invoking func once. Repeat calls to the function return the value of the first invocation. + * + * @template F - The type of the function. + * @param {F} func - The function to restrict. + * @returns {F} Returns the new restricted function. + * + * @example + * const initialize = once(createApplication); + * + * initialize(); + * initialize(); + * // => `createApplication` is invoked once + */ +declare function once any>(func: F): F; +//#endregion +export { once }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/once.d.ts b/tools/ui/node_modules/es-toolkit/dist/function/once.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..73a1f949d3cc3ef7db61eec3437da745c0e922be --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/once.d.ts @@ -0,0 +1,18 @@ +//#region src/function/once.d.ts +/** + * Creates a function that is restricted to invoking func once. Repeat calls to the function return the value of the first invocation. + * + * @template F - The type of the function. + * @param {F} func - The function to restrict. + * @returns {F} Returns the new restricted function. + * + * @example + * const initialize = once(createApplication); + * + * initialize(); + * initialize(); + * // => `createApplication` is invoked once + */ +declare function once any>(func: F): F; +//#endregion +export { once }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/once.js b/tools/ui/node_modules/es-toolkit/dist/function/once.js new file mode 100644 index 0000000000000000000000000000000000000000..3a71e79dc7512000979a26f4c3cdf2a8224ab5c4 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/once.js @@ -0,0 +1,31 @@ +//#region src/function/once.ts +/** +* Creates a function that is restricted to invoking the provided function `func` once. +* Repeated calls to the function will return the value from the first invocation. +* +* @template F - The type of function. +* @param {F} func - The function to restrict. +* @returns {F} A new function that invokes `func` once and caches the result. +* +* @example +* const initialize = once(() => { +* console.log('Initialized!'); +* return true; +* }); +* +* initialize(); // Logs: 'Initialized!' and returns true +* initialize(); // Returns true without logging +*/ +function once(func) { + let called = false; + let cache; + return function(...args) { + if (!called) { + called = true; + cache = func(...args); + } + return cache; + }; +} +//#endregion +exports.once = once; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/once.mjs b/tools/ui/node_modules/es-toolkit/dist/function/once.mjs new file mode 100644 index 0000000000000000000000000000000000000000..91fc85cfbf958a94a6517237d5aacd634a573559 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/once.mjs @@ -0,0 +1,31 @@ +//#region src/function/once.ts +/** +* Creates a function that is restricted to invoking the provided function `func` once. +* Repeated calls to the function will return the value from the first invocation. +* +* @template F - The type of function. +* @param {F} func - The function to restrict. +* @returns {F} A new function that invokes `func` once and caches the result. +* +* @example +* const initialize = once(() => { +* console.log('Initialized!'); +* return true; +* }); +* +* initialize(); // Logs: 'Initialized!' and returns true +* initialize(); // Returns true without logging +*/ +function once(func) { + let called = false; + let cache; + return function(...args) { + if (!called) { + called = true; + cache = func(...args); + } + return cache; + }; +} +//#endregion +export { once }; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/partial.d.mts b/tools/ui/node_modules/es-toolkit/dist/function/partial.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..19b59c169c63244b72150bc1db56651b196b1b66 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/partial.d.mts @@ -0,0 +1,622 @@ +//#region src/function/partial.d.ts +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template R The return type of the function. + * @param {function(arg1: T1): R} func The function to partially apply. + * @param {T1} arg1 The first argument to apply. + * @returns {function(): R} A new function that takes no arguments and returns the result of the original function. + * + * @example + * const addOne = (x: number) => x + 1; + * const addOneToFive = partial(addOne, 5); + * console.log(addOneToFive()); // => 6 + */ +declare function partial(func: (arg1: T1) => R, arg1: T1): () => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2): R} func The function to partially apply. + * @param {T1} arg1 The first argument to apply. + * @returns {function(arg2: T2): R} A new function that takes the second argument and returns the result of the original function. + * + * @example + * const multiply = (x: number, y: number) => x * y; + * const double = partial(multiply, 2); + * console.log(double(5)); // => 10 + */ +declare function partial(func: (arg1: T1, arg2: T2) => R, arg1: T1): (arg2: T2) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2): R} func The function to partially apply. + * @param {Placeholder} placeholder The placeholder for the first argument. + * @param {T2} arg2 The second argument to apply. + * @returns {function(arg1: T1): R} A new function that takes the first argument and returns the result of the original function. + * + * @example + * const greet = (greeting: string, name: string) => `${greeting}, ${name}!`; + * const greetWithHello = partial(greet, partial.placeholder, 'John'); + * console.log(greetWithHello('Hello')); // => 'Hello, John!' + */ +declare function partial(func: (arg1: T1, arg2: T2) => R, placeholder: Placeholder, arg2: T2): (arg1: T1) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2): R} func The function to partially apply. + * @param {T1} arg1 The first argument to apply. + * @param {T2} arg2 The second argument to apply. + * @returns {function(): R} A new function that takes no arguments and returns the result of the original function. + * + * @example + * const add = (x: number, y: number) => x + y; + * const addThree = partial(add, 1, 2); + * console.log(addThree()); // => 3 + */ +declare function partial(func: (arg1: T1, arg2: T2) => R, arg1: T1, arg2: T2): () => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3): R} func The function to partially apply. + * @param {T1} arg1 The first argument to apply. + * @returns {function(arg2: T2, arg3: T3): R} A new function that takes the second and third arguments and returns the result of the original function. + * + * @example + * const sumThree = (a: number, b: number, c: number) => a + b + c; + * const addFive = partial(sumThree, 5); + * console.log(addFive(3, 2)); // => 10 + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3) => R, arg1: T1): (arg2: T2, arg3: T3) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3): R} func The function to partially apply. + * @param {Placeholder} arg1 The placeholder for the first argument. + * @param {T2} arg2 The second argument to apply. + * @returns {function(arg1: T1, arg3: T3): R} A new function that takes the first and third arguments and returns the result of the original function. + * + * @example + * const greet = (greeting: string, name: string) => `${greeting}, ${name}!`; + * const greetWithPlaceholder = partial(greet, partial.placeholder, 'John'); + * console.log(greetWithPlaceholder('Hello')); // => 'Hello, John!' + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3) => R, arg1: Placeholder, arg2: T2): (arg1: T1, arg3: T3) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3): R} func The function to partially apply. + * @param {Placeholder} arg1 The placeholder for the first argument. + * @param {Placeholder} arg2 The placeholder for the second argument. + * @param {T3} arg3 The third argument to apply. + * @returns {function(arg1: T1, arg2: T2): R} A new function that takes the first and second arguments and returns the result of the original function. + * + * @example + * const multiply = (x: number, y: number, z: number) => x * y * z; + * const multiplyWithPlaceholders = partial(multiply, partial.placeholder, partial.placeholder, 2); + * console.log(multiplyWithPlaceholders(3, 4)); // => 24 + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3) => R, arg1: Placeholder, arg2: Placeholder, arg3: T3): (arg1: T1, arg2: T2) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3): R} func The function to partially apply. + * @param {T1} arg1 The first argument to apply. + * @param {Placeholder} arg2 The placeholder for the second argument. + * @param {T3} arg3 The third argument to apply. + * @returns {function(arg2: T2): R} A new function that takes the second argument and returns the result of the original function. + * + * @example + * const greet = (greeting: string, name: string) => `${greeting}, ${name}!`; + * const greetWithPlaceholder = partial(greet, 'Hello', partial.placeholder); + * console.log(greetWithPlaceholder('John')); // => 'Hello, John!' + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3) => R, arg1: T1, arg2: Placeholder, arg3: T3): (arg2: T2) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3): R} func The function to partially apply. + * @param {Placeholder} arg1 The first argument to apply. + * @param {T2} arg2 The placeholder for the second argument. + * @param {T3} arg3 The third argument to apply. + * @returns {function(arg2: T2): R} A new function that takes the second argument and returns the result of the original function. + * + * @example + * const greet = (greeting: string, name: string) => `${greeting}, ${name}!`; + * const greetWithPlaceholder = partial(greet, 'Hello', partial.placeholder); + * console.log(greetWithPlaceholder('John')); // => 'Hello, John!' + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3) => R, plc1: Placeholder, arg2: T2, arg3: T3): (arg1: T1) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3): R} func The function to partially apply. + * @param {T1} arg1 The first argument to apply. + * @param {T2} arg2 The second argument to apply. + * @param {T3} arg3 The third argument to apply. + * @returns {function(): R} A new function that takes no arguments and returns the result of the original function. + * + * @example + * const sum = (a: number, b: number, c: number) => a + b + c; + * const sumAll = partial(sum, 1, 2, 3); + * console.log(sumAll()); // => 6 + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3) => R, arg1: T1, arg2: T2, arg3: T3): () => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3, arg4: T4): R} func The function to partially apply. + * @param {T1} arg1 The first argument to apply. + * @returns {function(arg2: T2): R} A new function that takes the second argument and returns the result of the original function. + * + * @example + * const multiply = (x: number, y: number, z: number, w: number) => x * y * z * w; + * const double = partial(multiply, 2); + * console.log(double(5, 4, 3)); // => 120 + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: T1): (arg2: T2, arg3: T3, arg4: T4) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3, arg4: T4): R} func The function to partially apply. + * @param {Placeholder} arg1 The placeholder for the first argument. + * @param {Placeholder} arg2 The placeholder for the second argument. + * @param {T3} arg3 The third argument to apply. + * @param {T4} arg4 The fourth argument to apply. + * @returns {function(arg1: T1, arg2: T2): R} A new function that takes the first and second arguments and returns the result of the original function. + * + * @example + * const multiply = (x: number, y: number, z: number, w: number) => x * y * z * w; + * const multiplyWithPlaceholders = partial(multiply, partial.placeholder, partial.placeholder, 2, 3); + * console.log(multiplyWithPlaceholders(4, 5)); // => 120 + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: Placeholder, arg2: Placeholder, arg3: T3, arg4: T4): (arg1: T1, arg2: T2) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3, arg4: T4): R} func The function to partially apply. + * @param {T1} arg1 The first argument to apply. + * @param {T2} arg2 The second argument to apply. + * @returns {function(arg3: T3, arg4: T4): R} A new function that takes the third and fourth arguments and returns the result of the original function. + * + * @example + * const sumFour = (a: number, b: number, c: number, d: number) => a + b + c + d; + * const addOneAndTwo = partial(sumFour, 1, 2); + * console.log(addOneAndTwo(3, 4)); // => 10 + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: T1, arg2: T2): (arg3: T3, arg4: T4) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3, arg4: T4): R} func The function to partially apply. + * @param {T1} arg1 The first argument to apply. + * @param {Placeholder} arg2 The placeholder for the second argument. + * @param {T3} arg3 The third argument to apply. + * @param {T4} arg4 The fourth argument to apply. + * @returns {function(arg2: T2, arg4: T4): R} A new function that takes the second and fourth arguments and returns the result of the original function. + * + * @example + * const greet = (greeting: string, name: string, punctuation: string) => `${greeting}, ${name}${punctuation}`; + * const greetWithPlaceholder = partial(greet, 'Hello', partial.placeholder, '!'); + * console.log(greetWithPlaceholder('John')); // => 'Hello, John!' + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: T1, arg2: Placeholder, arg3: T3): (arg2: T2, arg4: T4) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3, arg4: T4): R} func The function to partially apply. + * @param {Placeholder} arg1 The placeholder for the first argument. + * @param {T2} arg2 The second argument to apply. + * @param {T3} arg3 The third argument to apply. + * @param {T4} arg4 The fourth argument to apply. + * @returns {function(arg1: T1, arg3: T3): R} A new function that takes the first and third arguments and returns the result of the original function. + * + * @example + * const multiply = (x: number, y: number, z: number, w: number) => x * y * z * w; + * const multiplyWithPlaceholder = partial(multiply, partial.placeholder, 2, 3); + * console.log(multiplyWithPlaceholder(4)); // => 24 + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: Placeholder, arg2: T2, arg3: T3): (arg1: T1, arg4: T4) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3, arg4: T4): R} func The function to partially apply. + * @param {Placeholder} arg1 The placeholder for the first argument. + * @param {T2} arg2 The second argument to apply. + * @param {Placeholder} arg3 The placeholder for the third argument. + * @param {T4} arg4 The fourth argument to apply. + * @returns {function(arg1: T1, arg3: T3): R} A new function that takes the first and third arguments and returns the result of the original function. + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: Placeholder, arg2: T2, arg3: Placeholder, arg4: T4): (arg1: T1, arg3: T3) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3, arg4: T4): R} func The function to partially apply. + * @param {Placeholder} arg1 The placeholder for the first argument. + * @param {Placeholder} arg2 The placeholder for the second argument. + * @param {T3} arg3 The third argument to apply. + * @param {T4} arg4 The fourth argument to apply. + * @returns {function(arg1: T1, arg2: T2): R} A new function that takes the first and second arguments and returns the result of the original function. + * + * @example + * const multiply = (x: number, y: number, z: number, w: number) => x * y * z * w; + * const multiplyWithPlaceholders = partial(multiply, partial.placeholder, partial.placeholder, 2, 3); + * console.log(multiplyWithPlaceholders(4, 5)); // => 120 + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: Placeholder, arg2: Placeholder, arg3: T3, arg4: T4): (arg1: T1, arg2: T2) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3, arg4: T4): R} func The function to partially apply. + * @param {T1} arg1 The first argument to apply. + * @param {T2} arg2 The second argument to apply. + * @param {T3} arg3 The third argument to apply. + * @returns {function(arg4: T4): R} A new function that takes the fourth argument and returns the result of the original function. + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: T1, arg2: T2, arg3: T3): (arg4: T4) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3, arg4: T4): R} func The function to partially apply. + * @param {T1} arg1 The first argument to apply. + * @param {T2} arg2 The second argument to apply. + * @param {Placeholder} arg3 The placeholder for the third argument. + * @param {T4} arg4 The fourth argument to apply. + * @returns {function(arg3: T3): R} A new function that takes the third argument and returns the result of the original function. + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: T1, arg2: T2, arg3: Placeholder, arg4: T4): (arg3: T3) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3, arg4: T4): R} func The function to partially apply. + * @param {T1} arg1 The first argument to apply. + * @param {Placeholder} arg2 The placeholder for the second argument. + * @param {T3} arg3 The third argument to apply. + * @param {T4} arg4 The fourth argument to apply. + * @returns {function(arg2: T2): R} A new function that takes the second argument and returns the result of the original function. + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: T1, arg2: Placeholder, arg3: T3, arg4: T4): (arg2: T2) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3, arg4: T4): R} func The function to partially apply. + * @param {Placeholder} arg1 The placeholder for the first argument. + * @param {T2} arg2 The second argument to apply. + * @param {T3} arg3 The third argument to apply. + * @param {T4} arg4 The fourth argument to apply. + * @returns {function(arg1: T1): R} A new function that takes the first argument and returns the result of the original function. + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: Placeholder, arg2: T2, arg3: T3, arg4: T4): (arg1: T1) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3, arg4: T4): R} func The function to partially apply. + * @param {T1} arg1 The first argument to apply. + * @param {T2} arg2 The second argument to apply. + * @param {T3} arg3 The third argument to apply. + * @param {T4} arg4 The fourth argument to apply. + * @returns {function(): R} A new function that takes no arguments and returns the result of the original function. + * + * @example + * const sumFour = (a: number, b: number, c: number, d: number) => a + b + c + d; + * const sumAll = partial(sumFour, 1, 2, 3, 4); + * console.log(sumAll()); // => 10 + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: T1, arg2: T2, arg3: T3, arg4: T4): () => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template TS The types of the arguments. + * @template R The return type of the function. + * @param {function(...args: TS): R} func The function to partially apply. + * @returns {function(...args: TS): R} A new function that takes the same arguments as the original function. + * + * @example + * const add = (...numbers: number[]) => numbers.reduce((sum, n) => sum + n, 0); + * const addFive = partial(add, 5); + * console.log(addFive(1, 2, 3)); // => 11 + */ +declare function partial(func: (...args: TS) => R): (...args: TS) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template TS The types of the arguments. + * @template T1 The type of the first argument. + * @template R The return type of the function. + * @param {function(arg1: T1, ...args: TS): R} func The function to partially apply. + * @param {T1} arg1 The first argument to apply. + * @returns {function(...args: TS): R} A new function that takes the remaining arguments and returns the result of the original function. + * + * @example + * const greet = (greeting: string, ...names: string[]) => `${greeting}, ${names.join(', ')}!`; + * const greetHello = partial(greet, 'Hello'); + * console.log(greetHello('Alice', 'Bob')); // => 'Hello, Alice, Bob!' + */ +declare function partial(func: (arg1: T1, ...args: TS) => R, arg1: T1): (...args: TS) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template TS The types of the arguments. + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, ...args: TS): R} func The function to partially apply. + * @param {T1} arg1 The first argument to apply. + * @param {T2} arg2 The second argument to apply. + * @returns {function(...args: TS): R} A new function that takes the remaining arguments and returns the result of the original function. + * + * @example + * const greet = (greeting: string, name: string, punctuation: string) => `${greeting}, ${name}${punctuation}`; + * const greetWithHello = partial(greet, 'Hello', '!'); + * console.log(greetWithHello('John')); // => 'Hello, John!' + */ +declare function partial(func: (arg1: T1, arg2: T2, ...args: TS) => R, t1: T1, arg2: T2): (...args: TS) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template TS The types of the arguments. + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template R The return type of the function. + * @param {function(t1: T1, arg2: T2, arg3: T3, ...args: TS): R} func The function to partially apply. + * @param {T1} t1 The first argument to apply. + * @param {T2} arg2 The second argument to apply. + * @param {T3} arg3 The third argument to apply. + * @returns {function(...args: TS): R} A new function that takes the remaining arguments and returns the result of the original function. + * + * @example + * const greet = (greeting: string, name: string, punctuation: string) => `${greeting}, ${name}${punctuation}`; + * const greetWithHello = partial(greet, 'Hello', 'John', '!'); + * console.log(greetWithHello()); // => 'Hello, John!' + */ +declare function partial(func: (t1: T1, arg2: T2, arg3: T3, ...args: TS) => R, t1: T1, arg2: T2, arg3: T3): (...args: TS) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template TS The types of the arguments. + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {function(t1: T1, arg2: T2, arg3: T3, arg4: T4, ...args: TS): R} func The function to partially apply. + * @param {T1} t1 The first argument to apply. + * @param {T2} arg2 The second argument to apply. + * @param {T3} arg3 The third argument to apply. + * @param {T4} arg4 The fourth argument to apply. + * @returns {function(...args: TS): R} A new function that takes the remaining arguments and returns the result of the original function. + * + * @example + * const greet = (greeting: string, name: string, punctuation: string) => `${greeting}, ${name}${punctuation}`; + * const greetWithHello = partial(greet, 'Hello', 'John', '!'); + * console.log(greetWithHello()); // => 'Hello, John!' + */ +declare function partial(func: (t1: T1, arg2: T2, arg3: T3, arg4: T4, ...args: TS) => R, t1: T1, arg2: T2, arg3: T3, arg4: T4): (...args: TS) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template F The type of the function to partially apply. + * @param {F} func The function to partially apply. + * @param {...any[]} partialArgs The arguments to be partially applied. + * @returns {function(...args: any[]): ReturnType} A new function that takes the remaining arguments and returns the result of the original function. + * + * @example + * const add = (...numbers: number[]) => numbers.reduce((sum, n) => sum + n, 0); + * const addFive = partial(add, 5); + * console.log(addFive(1, 2, 3)); // => 11 + */ +declare function partial any>(func: F, ...partialArgs: any[]): (...args: any[]) => ReturnType; +declare namespace partial { + var placeholder: typeof placeholderSymbol; +} +declare function partialImpl any, P>(func: F, placeholder: P, ...partialArgs: any[]): (...args: any[]) => ReturnType; +declare const placeholderSymbol: unique symbol; +type Placeholder = typeof placeholderSymbol; +//#endregion +export { partial }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/partial.d.ts b/tools/ui/node_modules/es-toolkit/dist/function/partial.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..19b59c169c63244b72150bc1db56651b196b1b66 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/partial.d.ts @@ -0,0 +1,622 @@ +//#region src/function/partial.d.ts +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template R The return type of the function. + * @param {function(arg1: T1): R} func The function to partially apply. + * @param {T1} arg1 The first argument to apply. + * @returns {function(): R} A new function that takes no arguments and returns the result of the original function. + * + * @example + * const addOne = (x: number) => x + 1; + * const addOneToFive = partial(addOne, 5); + * console.log(addOneToFive()); // => 6 + */ +declare function partial(func: (arg1: T1) => R, arg1: T1): () => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2): R} func The function to partially apply. + * @param {T1} arg1 The first argument to apply. + * @returns {function(arg2: T2): R} A new function that takes the second argument and returns the result of the original function. + * + * @example + * const multiply = (x: number, y: number) => x * y; + * const double = partial(multiply, 2); + * console.log(double(5)); // => 10 + */ +declare function partial(func: (arg1: T1, arg2: T2) => R, arg1: T1): (arg2: T2) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2): R} func The function to partially apply. + * @param {Placeholder} placeholder The placeholder for the first argument. + * @param {T2} arg2 The second argument to apply. + * @returns {function(arg1: T1): R} A new function that takes the first argument and returns the result of the original function. + * + * @example + * const greet = (greeting: string, name: string) => `${greeting}, ${name}!`; + * const greetWithHello = partial(greet, partial.placeholder, 'John'); + * console.log(greetWithHello('Hello')); // => 'Hello, John!' + */ +declare function partial(func: (arg1: T1, arg2: T2) => R, placeholder: Placeholder, arg2: T2): (arg1: T1) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2): R} func The function to partially apply. + * @param {T1} arg1 The first argument to apply. + * @param {T2} arg2 The second argument to apply. + * @returns {function(): R} A new function that takes no arguments and returns the result of the original function. + * + * @example + * const add = (x: number, y: number) => x + y; + * const addThree = partial(add, 1, 2); + * console.log(addThree()); // => 3 + */ +declare function partial(func: (arg1: T1, arg2: T2) => R, arg1: T1, arg2: T2): () => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3): R} func The function to partially apply. + * @param {T1} arg1 The first argument to apply. + * @returns {function(arg2: T2, arg3: T3): R} A new function that takes the second and third arguments and returns the result of the original function. + * + * @example + * const sumThree = (a: number, b: number, c: number) => a + b + c; + * const addFive = partial(sumThree, 5); + * console.log(addFive(3, 2)); // => 10 + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3) => R, arg1: T1): (arg2: T2, arg3: T3) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3): R} func The function to partially apply. + * @param {Placeholder} arg1 The placeholder for the first argument. + * @param {T2} arg2 The second argument to apply. + * @returns {function(arg1: T1, arg3: T3): R} A new function that takes the first and third arguments and returns the result of the original function. + * + * @example + * const greet = (greeting: string, name: string) => `${greeting}, ${name}!`; + * const greetWithPlaceholder = partial(greet, partial.placeholder, 'John'); + * console.log(greetWithPlaceholder('Hello')); // => 'Hello, John!' + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3) => R, arg1: Placeholder, arg2: T2): (arg1: T1, arg3: T3) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3): R} func The function to partially apply. + * @param {Placeholder} arg1 The placeholder for the first argument. + * @param {Placeholder} arg2 The placeholder for the second argument. + * @param {T3} arg3 The third argument to apply. + * @returns {function(arg1: T1, arg2: T2): R} A new function that takes the first and second arguments and returns the result of the original function. + * + * @example + * const multiply = (x: number, y: number, z: number) => x * y * z; + * const multiplyWithPlaceholders = partial(multiply, partial.placeholder, partial.placeholder, 2); + * console.log(multiplyWithPlaceholders(3, 4)); // => 24 + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3) => R, arg1: Placeholder, arg2: Placeholder, arg3: T3): (arg1: T1, arg2: T2) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3): R} func The function to partially apply. + * @param {T1} arg1 The first argument to apply. + * @param {Placeholder} arg2 The placeholder for the second argument. + * @param {T3} arg3 The third argument to apply. + * @returns {function(arg2: T2): R} A new function that takes the second argument and returns the result of the original function. + * + * @example + * const greet = (greeting: string, name: string) => `${greeting}, ${name}!`; + * const greetWithPlaceholder = partial(greet, 'Hello', partial.placeholder); + * console.log(greetWithPlaceholder('John')); // => 'Hello, John!' + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3) => R, arg1: T1, arg2: Placeholder, arg3: T3): (arg2: T2) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3): R} func The function to partially apply. + * @param {Placeholder} arg1 The first argument to apply. + * @param {T2} arg2 The placeholder for the second argument. + * @param {T3} arg3 The third argument to apply. + * @returns {function(arg2: T2): R} A new function that takes the second argument and returns the result of the original function. + * + * @example + * const greet = (greeting: string, name: string) => `${greeting}, ${name}!`; + * const greetWithPlaceholder = partial(greet, 'Hello', partial.placeholder); + * console.log(greetWithPlaceholder('John')); // => 'Hello, John!' + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3) => R, plc1: Placeholder, arg2: T2, arg3: T3): (arg1: T1) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3): R} func The function to partially apply. + * @param {T1} arg1 The first argument to apply. + * @param {T2} arg2 The second argument to apply. + * @param {T3} arg3 The third argument to apply. + * @returns {function(): R} A new function that takes no arguments and returns the result of the original function. + * + * @example + * const sum = (a: number, b: number, c: number) => a + b + c; + * const sumAll = partial(sum, 1, 2, 3); + * console.log(sumAll()); // => 6 + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3) => R, arg1: T1, arg2: T2, arg3: T3): () => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3, arg4: T4): R} func The function to partially apply. + * @param {T1} arg1 The first argument to apply. + * @returns {function(arg2: T2): R} A new function that takes the second argument and returns the result of the original function. + * + * @example + * const multiply = (x: number, y: number, z: number, w: number) => x * y * z * w; + * const double = partial(multiply, 2); + * console.log(double(5, 4, 3)); // => 120 + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: T1): (arg2: T2, arg3: T3, arg4: T4) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3, arg4: T4): R} func The function to partially apply. + * @param {Placeholder} arg1 The placeholder for the first argument. + * @param {Placeholder} arg2 The placeholder for the second argument. + * @param {T3} arg3 The third argument to apply. + * @param {T4} arg4 The fourth argument to apply. + * @returns {function(arg1: T1, arg2: T2): R} A new function that takes the first and second arguments and returns the result of the original function. + * + * @example + * const multiply = (x: number, y: number, z: number, w: number) => x * y * z * w; + * const multiplyWithPlaceholders = partial(multiply, partial.placeholder, partial.placeholder, 2, 3); + * console.log(multiplyWithPlaceholders(4, 5)); // => 120 + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: Placeholder, arg2: Placeholder, arg3: T3, arg4: T4): (arg1: T1, arg2: T2) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3, arg4: T4): R} func The function to partially apply. + * @param {T1} arg1 The first argument to apply. + * @param {T2} arg2 The second argument to apply. + * @returns {function(arg3: T3, arg4: T4): R} A new function that takes the third and fourth arguments and returns the result of the original function. + * + * @example + * const sumFour = (a: number, b: number, c: number, d: number) => a + b + c + d; + * const addOneAndTwo = partial(sumFour, 1, 2); + * console.log(addOneAndTwo(3, 4)); // => 10 + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: T1, arg2: T2): (arg3: T3, arg4: T4) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3, arg4: T4): R} func The function to partially apply. + * @param {T1} arg1 The first argument to apply. + * @param {Placeholder} arg2 The placeholder for the second argument. + * @param {T3} arg3 The third argument to apply. + * @param {T4} arg4 The fourth argument to apply. + * @returns {function(arg2: T2, arg4: T4): R} A new function that takes the second and fourth arguments and returns the result of the original function. + * + * @example + * const greet = (greeting: string, name: string, punctuation: string) => `${greeting}, ${name}${punctuation}`; + * const greetWithPlaceholder = partial(greet, 'Hello', partial.placeholder, '!'); + * console.log(greetWithPlaceholder('John')); // => 'Hello, John!' + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: T1, arg2: Placeholder, arg3: T3): (arg2: T2, arg4: T4) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3, arg4: T4): R} func The function to partially apply. + * @param {Placeholder} arg1 The placeholder for the first argument. + * @param {T2} arg2 The second argument to apply. + * @param {T3} arg3 The third argument to apply. + * @param {T4} arg4 The fourth argument to apply. + * @returns {function(arg1: T1, arg3: T3): R} A new function that takes the first and third arguments and returns the result of the original function. + * + * @example + * const multiply = (x: number, y: number, z: number, w: number) => x * y * z * w; + * const multiplyWithPlaceholder = partial(multiply, partial.placeholder, 2, 3); + * console.log(multiplyWithPlaceholder(4)); // => 24 + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: Placeholder, arg2: T2, arg3: T3): (arg1: T1, arg4: T4) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3, arg4: T4): R} func The function to partially apply. + * @param {Placeholder} arg1 The placeholder for the first argument. + * @param {T2} arg2 The second argument to apply. + * @param {Placeholder} arg3 The placeholder for the third argument. + * @param {T4} arg4 The fourth argument to apply. + * @returns {function(arg1: T1, arg3: T3): R} A new function that takes the first and third arguments and returns the result of the original function. + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: Placeholder, arg2: T2, arg3: Placeholder, arg4: T4): (arg1: T1, arg3: T3) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3, arg4: T4): R} func The function to partially apply. + * @param {Placeholder} arg1 The placeholder for the first argument. + * @param {Placeholder} arg2 The placeholder for the second argument. + * @param {T3} arg3 The third argument to apply. + * @param {T4} arg4 The fourth argument to apply. + * @returns {function(arg1: T1, arg2: T2): R} A new function that takes the first and second arguments and returns the result of the original function. + * + * @example + * const multiply = (x: number, y: number, z: number, w: number) => x * y * z * w; + * const multiplyWithPlaceholders = partial(multiply, partial.placeholder, partial.placeholder, 2, 3); + * console.log(multiplyWithPlaceholders(4, 5)); // => 120 + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: Placeholder, arg2: Placeholder, arg3: T3, arg4: T4): (arg1: T1, arg2: T2) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3, arg4: T4): R} func The function to partially apply. + * @param {T1} arg1 The first argument to apply. + * @param {T2} arg2 The second argument to apply. + * @param {T3} arg3 The third argument to apply. + * @returns {function(arg4: T4): R} A new function that takes the fourth argument and returns the result of the original function. + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: T1, arg2: T2, arg3: T3): (arg4: T4) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3, arg4: T4): R} func The function to partially apply. + * @param {T1} arg1 The first argument to apply. + * @param {T2} arg2 The second argument to apply. + * @param {Placeholder} arg3 The placeholder for the third argument. + * @param {T4} arg4 The fourth argument to apply. + * @returns {function(arg3: T3): R} A new function that takes the third argument and returns the result of the original function. + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: T1, arg2: T2, arg3: Placeholder, arg4: T4): (arg3: T3) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3, arg4: T4): R} func The function to partially apply. + * @param {T1} arg1 The first argument to apply. + * @param {Placeholder} arg2 The placeholder for the second argument. + * @param {T3} arg3 The third argument to apply. + * @param {T4} arg4 The fourth argument to apply. + * @returns {function(arg2: T2): R} A new function that takes the second argument and returns the result of the original function. + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: T1, arg2: Placeholder, arg3: T3, arg4: T4): (arg2: T2) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3, arg4: T4): R} func The function to partially apply. + * @param {Placeholder} arg1 The placeholder for the first argument. + * @param {T2} arg2 The second argument to apply. + * @param {T3} arg3 The third argument to apply. + * @param {T4} arg4 The fourth argument to apply. + * @returns {function(arg1: T1): R} A new function that takes the first argument and returns the result of the original function. + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: Placeholder, arg2: T2, arg3: T3, arg4: T4): (arg1: T1) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, arg3: T3, arg4: T4): R} func The function to partially apply. + * @param {T1} arg1 The first argument to apply. + * @param {T2} arg2 The second argument to apply. + * @param {T3} arg3 The third argument to apply. + * @param {T4} arg4 The fourth argument to apply. + * @returns {function(): R} A new function that takes no arguments and returns the result of the original function. + * + * @example + * const sumFour = (a: number, b: number, c: number, d: number) => a + b + c + d; + * const sumAll = partial(sumFour, 1, 2, 3, 4); + * console.log(sumAll()); // => 10 + */ +declare function partial(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: T1, arg2: T2, arg3: T3, arg4: T4): () => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template TS The types of the arguments. + * @template R The return type of the function. + * @param {function(...args: TS): R} func The function to partially apply. + * @returns {function(...args: TS): R} A new function that takes the same arguments as the original function. + * + * @example + * const add = (...numbers: number[]) => numbers.reduce((sum, n) => sum + n, 0); + * const addFive = partial(add, 5); + * console.log(addFive(1, 2, 3)); // => 11 + */ +declare function partial(func: (...args: TS) => R): (...args: TS) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template TS The types of the arguments. + * @template T1 The type of the first argument. + * @template R The return type of the function. + * @param {function(arg1: T1, ...args: TS): R} func The function to partially apply. + * @param {T1} arg1 The first argument to apply. + * @returns {function(...args: TS): R} A new function that takes the remaining arguments and returns the result of the original function. + * + * @example + * const greet = (greeting: string, ...names: string[]) => `${greeting}, ${names.join(', ')}!`; + * const greetHello = partial(greet, 'Hello'); + * console.log(greetHello('Alice', 'Bob')); // => 'Hello, Alice, Bob!' + */ +declare function partial(func: (arg1: T1, ...args: TS) => R, arg1: T1): (...args: TS) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template TS The types of the arguments. + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template R The return type of the function. + * @param {function(arg1: T1, arg2: T2, ...args: TS): R} func The function to partially apply. + * @param {T1} arg1 The first argument to apply. + * @param {T2} arg2 The second argument to apply. + * @returns {function(...args: TS): R} A new function that takes the remaining arguments and returns the result of the original function. + * + * @example + * const greet = (greeting: string, name: string, punctuation: string) => `${greeting}, ${name}${punctuation}`; + * const greetWithHello = partial(greet, 'Hello', '!'); + * console.log(greetWithHello('John')); // => 'Hello, John!' + */ +declare function partial(func: (arg1: T1, arg2: T2, ...args: TS) => R, t1: T1, arg2: T2): (...args: TS) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template TS The types of the arguments. + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template R The return type of the function. + * @param {function(t1: T1, arg2: T2, arg3: T3, ...args: TS): R} func The function to partially apply. + * @param {T1} t1 The first argument to apply. + * @param {T2} arg2 The second argument to apply. + * @param {T3} arg3 The third argument to apply. + * @returns {function(...args: TS): R} A new function that takes the remaining arguments and returns the result of the original function. + * + * @example + * const greet = (greeting: string, name: string, punctuation: string) => `${greeting}, ${name}${punctuation}`; + * const greetWithHello = partial(greet, 'Hello', 'John', '!'); + * console.log(greetWithHello()); // => 'Hello, John!' + */ +declare function partial(func: (t1: T1, arg2: T2, arg3: T3, ...args: TS) => R, t1: T1, arg2: T2, arg3: T3): (...args: TS) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template TS The types of the arguments. + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {function(t1: T1, arg2: T2, arg3: T3, arg4: T4, ...args: TS): R} func The function to partially apply. + * @param {T1} t1 The first argument to apply. + * @param {T2} arg2 The second argument to apply. + * @param {T3} arg3 The third argument to apply. + * @param {T4} arg4 The fourth argument to apply. + * @returns {function(...args: TS): R} A new function that takes the remaining arguments and returns the result of the original function. + * + * @example + * const greet = (greeting: string, name: string, punctuation: string) => `${greeting}, ${name}${punctuation}`; + * const greetWithHello = partial(greet, 'Hello', 'John', '!'); + * console.log(greetWithHello()); // => 'Hello, John!' + */ +declare function partial(func: (t1: T1, arg2: T2, arg3: T3, arg4: T4, ...args: TS) => R, t1: T1, arg2: T2, arg3: T3, arg4: T4): (...args: TS) => R; +/** + * Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. + * + * The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template F The type of the function to partially apply. + * @param {F} func The function to partially apply. + * @param {...any[]} partialArgs The arguments to be partially applied. + * @returns {function(...args: any[]): ReturnType} A new function that takes the remaining arguments and returns the result of the original function. + * + * @example + * const add = (...numbers: number[]) => numbers.reduce((sum, n) => sum + n, 0); + * const addFive = partial(add, 5); + * console.log(addFive(1, 2, 3)); // => 11 + */ +declare function partial any>(func: F, ...partialArgs: any[]): (...args: any[]) => ReturnType; +declare namespace partial { + var placeholder: typeof placeholderSymbol; +} +declare function partialImpl any, P>(func: F, placeholder: P, ...partialArgs: any[]): (...args: any[]) => ReturnType; +declare const placeholderSymbol: unique symbol; +type Placeholder = typeof placeholderSymbol; +//#endregion +export { partial }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/partial.js b/tools/ui/node_modules/es-toolkit/dist/function/partial.js new file mode 100644 index 0000000000000000000000000000000000000000..5598761026f06706d93498c2823aefe6afc676be --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/partial.js @@ -0,0 +1,45 @@ +//#region src/function/partial.ts +/** +* Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. +* +* The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. +* +* Note: This method doesn't set the `length` property of partially applied functions. +* +* @template F The type of the function to partially apply. +* @param {F} func The function to partially apply arguments to. +* @param {any[]} partialArgs The arguments to be partially applied. +* @returns {(...args: any[]) => ReturnType} Returns the new partially applied function. +* +* @example +* function greet(greeting, name) { +* return greeting + ' ' + name; +* } +* +* const sayHelloTo = partial(greet, 'hello'); +* sayHelloTo('fred'); +* // => 'hello fred' +* +* // Partially applied with placeholders. +* const greetFred = partial(greet, partial.placeholder, 'fred'); +* greetFred('hi'); +* // => 'hi fred' +*/ +function partial(func, ...partialArgs) { + return partialImpl(func, placeholderSymbol, ...partialArgs); +} +function partialImpl(func, placeholder, ...partialArgs) { + const partialed = function(...providedArgs) { + let providedArgsIndex = 0; + const substitutedArgs = partialArgs.slice().map((arg) => arg === placeholder ? providedArgs[providedArgsIndex++] : arg); + const remainingArgs = providedArgs.slice(providedArgsIndex); + return func.apply(this, substitutedArgs.concat(remainingArgs)); + }; + if (func.prototype) partialed.prototype = Object.create(func.prototype); + return partialed; +} +const placeholderSymbol = Symbol("partial.placeholder"); +partial.placeholder = placeholderSymbol; +//#endregion +exports.partial = partial; +exports.partialImpl = partialImpl; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/partial.mjs b/tools/ui/node_modules/es-toolkit/dist/function/partial.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f416414f17e0fe83d706b6e9a660325133c02cd2 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/partial.mjs @@ -0,0 +1,44 @@ +//#region src/function/partial.ts +/** +* Creates a function that invokes `func` with `partialArgs` prepended to the arguments it receives. This method is like `bind` except it does not alter the `this` binding. +* +* The partial.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. +* +* Note: This method doesn't set the `length` property of partially applied functions. +* +* @template F The type of the function to partially apply. +* @param {F} func The function to partially apply arguments to. +* @param {any[]} partialArgs The arguments to be partially applied. +* @returns {(...args: any[]) => ReturnType} Returns the new partially applied function. +* +* @example +* function greet(greeting, name) { +* return greeting + ' ' + name; +* } +* +* const sayHelloTo = partial(greet, 'hello'); +* sayHelloTo('fred'); +* // => 'hello fred' +* +* // Partially applied with placeholders. +* const greetFred = partial(greet, partial.placeholder, 'fred'); +* greetFred('hi'); +* // => 'hi fred' +*/ +function partial(func, ...partialArgs) { + return partialImpl(func, placeholderSymbol, ...partialArgs); +} +function partialImpl(func, placeholder, ...partialArgs) { + const partialed = function(...providedArgs) { + let providedArgsIndex = 0; + const substitutedArgs = partialArgs.slice().map((arg) => arg === placeholder ? providedArgs[providedArgsIndex++] : arg); + const remainingArgs = providedArgs.slice(providedArgsIndex); + return func.apply(this, substitutedArgs.concat(remainingArgs)); + }; + if (func.prototype) partialed.prototype = Object.create(func.prototype); + return partialed; +} +const placeholderSymbol = Symbol("partial.placeholder"); +partial.placeholder = placeholderSymbol; +//#endregion +export { partial, partialImpl }; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/partialRight.d.mts b/tools/ui/node_modules/es-toolkit/dist/function/partialRight.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..e4b407e9bdf9c86d43ebdf17ba9b1590a2a5da58 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/partialRight.d.mts @@ -0,0 +1,630 @@ +//#region src/function/partialRight.d.ts +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template R The return type of the function. + * @param {() => R} func The function to invoke. + * @returns {() => R} Returns the new function. + * @example + * const getValue = () => 42; + * const getValueFunc = partialRight(getValue); + * console.log(getValueFunc()); // => 42 + */ +declare function partialRight(func: () => R): () => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template R The return type of the function. + * @param {(arg1: T1) => R} func The function to partially apply arguments to. + * @param {T1} arg1 The first argument to be partially applied. + * @returns {() => R} Returns the new partially applied function. + * @example + * const addOne = (num: number) => num + 1; + * const addOneFunc = partialRight(addOne, 1); + * console.log(addOneFunc()); // => 2 + */ +declare function partialRight(func: (arg1: T1) => R, arg1: T1): () => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template R The return type of the function. + * @param {(arg1: T1) => R} func The function to partially apply arguments to. + * @returns {(arg1: T1) => R} Returns the new partially applied function. + * @example + * const multiplyBy = (factor: number) => (num: number) => num * factor; + * const double = partialRight(multiplyBy(2)); + * console.log(double(5)); // => 10 + */ +declare function partialRight(func: (arg1: T1) => R): (arg1: T1) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template R The return type of the function. + * @param {(arg1: T1) => R} func The function to partially apply arguments to. + * @param {T1} arg1 The first argument to be partially applied. + * @returns {() => R} Returns the new partially applied function. + * @example + * const greet = (name: string) => `Hello, ${name}!`; + * const greetJohn = partialRight(greet, 'John'); + * console.log(greetJohn()); // => 'Hello, John!' + */ +declare function partialRight(func: (arg1: T1) => R, arg1: T1): () => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2) => R} func The function to partially apply arguments to. + * @returns {(arg1: T1, arg2: T2) => R} Returns the new partially applied function. + * @example + * const subtract = (a: number, b: number) => a - b; + * const subtractFive = partialRight(subtract); + * console.log(subtractFive(10, 5)); // => 5 + */ +declare function partialRight(func: (arg1: T1, arg2: T2) => R): (arg1: T1, arg2: T2) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2) => R} func The function to partially apply arguments to. + * @param {T1} arg1 The first argument to be partially applied. + * @param {Placeholder} arg2 The placeholder for the second argument. + * @returns {(arg2: T2) => R} Returns the new partially applied function. + * @example + * const concat = (a: string, b: string) => a + b; + * const concatWithHello = partialRight(concat, 'Hello', partialRight.placeholder); + * console.log(concatWithHello(' World!')); // => 'Hello World!' + */ +declare function partialRight(func: (arg1: T1, arg2: T2) => R, arg1: T1, arg2: Placeholder): (arg2: T2) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2) => R} func The function to partially apply arguments to. + * @param {T2} arg2 The second argument to be partially applied. + * @returns {(arg1: T1) => R} Returns the new partially applied function. + * @example + * const divide = (a: number, b: number) => a / b; + * const divideByTwo = partialRight(divide, 2); + * console.log(divideByTwo(10)); // => 5 + */ +declare function partialRight(func: (arg1: T1, arg2: T2) => R, arg2: T2): (arg1: T1) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2) => R} func The function to partially apply arguments to. + * @param {T1} arg1 The first argument to be partially applied. + * @param {T2} arg2 The second argument to be partially applied. + * @returns {() => R} Returns the new partially applied function. + * @example + * const multiply = (a: number, b: number) => a * b; + * const multiplyByThreeAndFour = partialRight(multiply, 3, 4); + * console.log(multiplyByThreeAndFour()); // => 12 + */ +declare function partialRight(func: (arg1: T1, arg2: T2) => R, arg1: T1, arg2: T2): () => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3) => R} func The function to partially apply arguments to. + * @returns {(arg1: T1, arg2: T2, arg3: T3) => R} Returns the new partially applied function. + * @example + * const sumThree = (a: number, b: number, c: number) => a + b + c; + * const sumWithFive = partialRight(sumThree); + * console.log(sumWithFive(1, 2, 5)); // => 8 + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3) => R): (arg1: T1, arg2: T2, arg3: T3) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3) => R} func The function to partially apply arguments to. + * @param {T1} arg1 The first argument to be partially applied. + * @param {Placeholder} arg2 The placeholder for the second argument. + * @param {Placeholder} arg3 The placeholder for the third argument. + * @returns {(arg2: T2, arg3: T3) => R} Returns the new partially applied function. + * @example + * const formatDate = (day: number, month: number, year: number) => `${day}/${month}/${year}`; + * const formatDateWithDay = partialRight(formatDate, 1, partialRight.placeholder, partialRight.placeholder); + * console.log(formatDateWithDay(12, 2023)); // => '1/12/2023' + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3) => R, arg1: T1, arg2: Placeholder, arg3: Placeholder): (arg2: T2, arg3: T3) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3) => R} func The function to partially apply arguments to. + * @param {T2} arg2 The second argument to be partially applied. + * @param {Placeholder} arg3 The placeholder for the third argument. + * @returns {(arg1: T1, arg3: T3) => R} Returns the new partially applied function. + * @example + * const createUser = (name: string, age: number, country: string) => `${name}, ${age} years old from ${country}`; + * const createUserFromUSA = partialRight(createUser, 'USA', partialRight.placeholder); + * console.log(createUserFromUSA('John', 30)); // => 'John, 30 years old from USA' + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3) => R, arg2: T2, arg3: Placeholder): (arg1: T1, arg3: T3) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3) => R} func The function to partially apply arguments to. + * @param {T1} arg1 The first argument to be partially applied. + * @param {T2} arg2 The second argument to be partially applied. + * @param {Placeholder} arg3 The placeholder for the third argument. + * @returns {(arg3: T3) => R} Returns the new partially applied function. + * @example + * const logMessage = (level: string, message: string, timestamp: string) => `[${level}] ${message} at ${timestamp}`; + * const logError = partialRight(logMessage, 'ERROR', '2023-10-01'); + * console.log(logError('Something went wrong!')); // => '[ERROR] Something went wrong! at 2023-10-01' + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3) => R, arg1: T1, arg2: T2, arg3: Placeholder): (arg3: T3) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3) => R} func The function to partially apply arguments to. + * @param {T3} arg3 The third argument to be partially applied. + * @returns {(arg1: T1, arg2: T2) => R} Returns the new partially applied function. + * @example + * const calculateArea = (length: number, width: number) => length * width; + * const calculateAreaWithWidth = partialRight(calculateArea, 5); + * console.log(calculateAreaWithWidth(10)); // => 50 + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3) => R, arg3: T3): (arg1: T1, arg2: T2) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3) => R} func The function to partially apply arguments to. + * @param {T1} arg1 The first argument to be partially applied. + * @param {Placeholder} arg2 The placeholder for the second argument. + * @param {T3} arg3 The third argument to be partially applied. + * @returns {(arg2: T2) => R} Returns the new partially applied function. + * @example + * const formatCurrency = (amount: number, currency: string) => `${amount} ${currency}`; + * const formatUSD = partialRight(formatCurrency, 100, partialRight.placeholder); + * console.log(formatUSD('USD')); // => '100 USD' + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3) => R, arg1: T1, arg2: Placeholder, arg3: T3): (arg2: T2) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3) => R} func The function to partially apply arguments to. + * @param {T2} arg2 The second argument to be partially applied. + * @param {T3} arg3 The third argument to be partially applied. + * @returns {(arg1: T1) => R} Returns the new partially applied function. + * @example + * const createProfile = (name: string, age: number, country: string) => `${name}, ${age} from ${country}`; + * const createProfileFromCanada = partialRight(createProfile, 'Canada', 'John'); + * console.log(createProfileFromCanada(30)); // => 'John, 30 from Canada' + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3) => R, arg2: T2, arg3: T3): (arg1: T1) => R; +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3) => R, arg1: T1, arg2: T2, arg3: T3): () => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R} func The function to partially apply arguments to. + * @returns {(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R} Returns a new function that takes four arguments. + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R} func The function to partially apply arguments to. + * @param {T1} arg1 The first argument to be partially applied. + * @param {Placeholder} arg2 The placeholder for the second argument. + * @param {Placeholder} arg3 The placeholder for the third argument. + * @param {Placeholder} arg4 The placeholder for the fourth argument. + * @returns {(arg2: T2, arg3: T3, arg4: T4) => R} Returns a new function that takes the second, third, and fourth arguments. + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: T1, arg2: Placeholder, arg3: Placeholder, arg4: Placeholder): (arg2: T2, arg3: T3, arg4: T4) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R} func The function to partially apply arguments to. + * @param {T2} arg2 The second argument to be partially applied. + * @param {Placeholder} arg3 The placeholder for the third argument. + * @param {Placeholder} arg4 The placeholder for the fourth argument. + * @returns {(arg1: T1, arg3: T3, arg4: T4) => R} Returns a new function that takes the first, third, and fourth arguments. + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg2: T2, arg3: Placeholder, arg4: Placeholder): (arg1: T1, arg3: T3, arg4: T4) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R} func The function to partially apply arguments to. + * @param {T1} arg1 The first argument to be partially applied. + * @param {T2} arg2 The second argument to be partially applied. + * @param {Placeholder} arg3 The placeholder for the third argument. + * @param {Placeholder} arg4 The placeholder for the fourth argument. + * @returns {(arg3: T3, arg4: T4) => R} Returns a new function that takes the third and fourth arguments. + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: T1, arg2: T2, arg3: Placeholder, arg4: Placeholder): (arg3: T3, arg4: T4) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R} func The function to partially apply arguments to. + * @param {T3} arg3 The third argument to be partially applied. + * @param {Placeholder} arg4 The placeholder for the fourth argument. + * @returns {(arg1: T1, arg2: T2, arg4: T4) => R} Returns a new function that takes the first, second, and fourth arguments. + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg3: T3, arg4: Placeholder): (arg1: T1, arg2: T2, arg4: T4) => R; +/** + * Creates a function that invokes `func` with the first argument, a placeholder for the second argument, + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R} func The function to partially apply arguments to. + * @param {T1} arg1 The first argument to be partially applied. + * @param {Placeholder} arg2 The placeholder for the second argument. + * @param {T3} arg3 The third argument to be partially applied. + * @param {Placeholder} arg4 The placeholder for the fourth argument. + * @returns {(arg2: T2, arg4: T4) => R} Returns a new function that takes the second and fourth arguments. + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: T1, arg2: Placeholder, arg3: T3, arg4: Placeholder): (arg2: T2, arg4: T4) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R} func The function to partially apply arguments to. + * @param {T2} arg2 The second argument to be partially applied. + * @param {T3} arg3 The third argument to be partially applied. + * @param {Placeholder} arg4 The placeholder for the fourth argument. + * @returns {(arg1: T1, arg4: T4) => R} Returns a new function that takes the first and fourth arguments. + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg2: T2, arg3: T3, arg4: Placeholder): (arg1: T1, arg4: T4) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R} func The function to partially apply arguments to. + * @param {T1} arg1 The first argument to be partially applied. + * @param {T2} arg2 The second argument to be partially applied. + * @param {T3} arg3 The third argument to be partially applied. + * @param {Placeholder} arg4 The placeholder for the fourth argument. + * @returns {(arg4: T4) => R} Returns a new function that takes the fourth argument. + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: T1, arg2: T2, arg3: T3, arg4: Placeholder): (arg4: T4) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R} func The function to partially apply arguments to. + * @param {T4} arg4 The fourth argument to be partially applied. + * @returns {(arg1: T1, arg2: T2, arg3: T3) => R} Returns a new function that takes the first, second, and third arguments. + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg4: T4): (arg1: T1, arg2: T2, arg3: T3) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R} func The function to partially apply arguments to. + * @param {T1} arg1 The first argument to be partially applied. + * @param {Placeholder} arg2 The placeholder for the second argument. + * @param {Placeholder} arg3 The placeholder for the third argument. + * @param {T4} arg4 The fourth argument to be partially applied. + * @returns {(arg2: T2, arg3: T3) => R} Returns a new function that takes the second and third arguments. + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: T1, arg2: Placeholder, arg3: Placeholder, arg4: T4): (arg2: T2, arg3: T3) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R} func The function to partially apply arguments to. + * @param {T2} arg2 The second argument to be partially applied. + * @param {Placeholder} arg3 The placeholder for the third argument. + * @param {T4} arg4 The fourth argument to be partially applied. + * @returns {(arg1: T1, arg3: T3) => R} Returns a new function that takes the first and third arguments. + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg2: T2, arg3: Placeholder, arg4: T4): (arg1: T1, arg3: T3) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R} func The function to partially apply arguments to. + * @param {T1} arg1 The first argument to be partially applied. + * @param {T2} arg2 The second argument to be partially applied. + * @param {Placeholder} arg3 The placeholder for the third argument. + * @param {T4} arg4 The fourth argument to be partially applied. + * @returns {(arg3: T3) => R} Returns a new function that takes the third argument. + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: T1, arg2: T2, arg3: Placeholder, arg4: T4): (arg3: T3) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R} func The function to partially apply arguments to. + * @param {T3} arg3 The third argument to be partially applied. + * @param {T4} arg4 The fourth argument to be partially applied. + * @returns {(arg1: T1, arg2: T2) => R} Returns a new function that takes the first and second arguments. + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg3: T3, arg4: T4): (arg1: T1, arg2: T2) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R} func The function to partially apply arguments to. + * @param {T1} arg1 The first argument to be partially applied. + * @param {Placeholder} arg2 The placeholder for the second argument. + * @param {T3} arg3 The third argument to be partially applied. + * @param {T4} arg4 The fourth argument to be partially applied. + * @returns {(arg2: T2) => R} Returns a new function that takes the second argument. + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: T1, arg2: Placeholder, arg3: T3, arg4: T4): (arg2: T2) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R} func The function to partially apply arguments to. + * @param {T2} arg2 The second argument to be partially applied. + * @param {T3} arg3 The third argument to be partially applied. + * @param {T4} arg4 The fourth argument to be partially applied. + * @returns {(arg1: T1) => R} Returns a new function that takes the first argument. + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg2: T2, arg3: T3, arg4: T4): (arg1: T1) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R} func The function to partially apply arguments to. + * @param {T1} arg1 The first argument to be partially applied. + * @param {T2} arg2 The second argument to be partially applied. + * @param {T3} arg3 The third argument to be partially applied. + * @param {T4} arg4 The fourth argument to be partially applied. + * @returns {() => R} Returns the new partially applied function. + * @example + * const concatenate = (a: string, b: string, c: string, d: string) => a + b + c + d; + * const concatenateHelloWorld = partialRight(concatenate, 'Hello', ' ', 'World', '!'); + * console.log(concatenateHelloWorld()); // => 'Hello World!' + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: T1, arg2: T2, arg3: T3, arg4: T4): () => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template F The type of the function to partially apply. + * @param {F} func The function to partially apply arguments to. + * @param {...any[]} args The arguments to be partially applied. + * @returns {function(...args: any[]): ReturnType} Returns the new partially applied function. + * @example + * const log = (...messages: string[]) => console.log(...messages); + * const logError = partialRight(log, 'Error:'); + * logError('Something went wrong!'); // => 'Error: Something went wrong!' + */ +declare function partialRight(func: (...args: any[]) => any, ...args: any[]): (...args: any[]) => any; +declare namespace partialRight { + var placeholder: typeof placeholderSymbol; +} +declare function partialRightImpl any, P>(func: F, placeholder: P, ...partialArgs: any[]): (...args: any[]) => ReturnType; +declare const placeholderSymbol: unique symbol; +type Placeholder = typeof placeholderSymbol; +//#endregion +export { partialRight }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/partialRight.d.ts b/tools/ui/node_modules/es-toolkit/dist/function/partialRight.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e4b407e9bdf9c86d43ebdf17ba9b1590a2a5da58 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/partialRight.d.ts @@ -0,0 +1,630 @@ +//#region src/function/partialRight.d.ts +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template R The return type of the function. + * @param {() => R} func The function to invoke. + * @returns {() => R} Returns the new function. + * @example + * const getValue = () => 42; + * const getValueFunc = partialRight(getValue); + * console.log(getValueFunc()); // => 42 + */ +declare function partialRight(func: () => R): () => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template R The return type of the function. + * @param {(arg1: T1) => R} func The function to partially apply arguments to. + * @param {T1} arg1 The first argument to be partially applied. + * @returns {() => R} Returns the new partially applied function. + * @example + * const addOne = (num: number) => num + 1; + * const addOneFunc = partialRight(addOne, 1); + * console.log(addOneFunc()); // => 2 + */ +declare function partialRight(func: (arg1: T1) => R, arg1: T1): () => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template R The return type of the function. + * @param {(arg1: T1) => R} func The function to partially apply arguments to. + * @returns {(arg1: T1) => R} Returns the new partially applied function. + * @example + * const multiplyBy = (factor: number) => (num: number) => num * factor; + * const double = partialRight(multiplyBy(2)); + * console.log(double(5)); // => 10 + */ +declare function partialRight(func: (arg1: T1) => R): (arg1: T1) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template R The return type of the function. + * @param {(arg1: T1) => R} func The function to partially apply arguments to. + * @param {T1} arg1 The first argument to be partially applied. + * @returns {() => R} Returns the new partially applied function. + * @example + * const greet = (name: string) => `Hello, ${name}!`; + * const greetJohn = partialRight(greet, 'John'); + * console.log(greetJohn()); // => 'Hello, John!' + */ +declare function partialRight(func: (arg1: T1) => R, arg1: T1): () => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2) => R} func The function to partially apply arguments to. + * @returns {(arg1: T1, arg2: T2) => R} Returns the new partially applied function. + * @example + * const subtract = (a: number, b: number) => a - b; + * const subtractFive = partialRight(subtract); + * console.log(subtractFive(10, 5)); // => 5 + */ +declare function partialRight(func: (arg1: T1, arg2: T2) => R): (arg1: T1, arg2: T2) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2) => R} func The function to partially apply arguments to. + * @param {T1} arg1 The first argument to be partially applied. + * @param {Placeholder} arg2 The placeholder for the second argument. + * @returns {(arg2: T2) => R} Returns the new partially applied function. + * @example + * const concat = (a: string, b: string) => a + b; + * const concatWithHello = partialRight(concat, 'Hello', partialRight.placeholder); + * console.log(concatWithHello(' World!')); // => 'Hello World!' + */ +declare function partialRight(func: (arg1: T1, arg2: T2) => R, arg1: T1, arg2: Placeholder): (arg2: T2) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2) => R} func The function to partially apply arguments to. + * @param {T2} arg2 The second argument to be partially applied. + * @returns {(arg1: T1) => R} Returns the new partially applied function. + * @example + * const divide = (a: number, b: number) => a / b; + * const divideByTwo = partialRight(divide, 2); + * console.log(divideByTwo(10)); // => 5 + */ +declare function partialRight(func: (arg1: T1, arg2: T2) => R, arg2: T2): (arg1: T1) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2) => R} func The function to partially apply arguments to. + * @param {T1} arg1 The first argument to be partially applied. + * @param {T2} arg2 The second argument to be partially applied. + * @returns {() => R} Returns the new partially applied function. + * @example + * const multiply = (a: number, b: number) => a * b; + * const multiplyByThreeAndFour = partialRight(multiply, 3, 4); + * console.log(multiplyByThreeAndFour()); // => 12 + */ +declare function partialRight(func: (arg1: T1, arg2: T2) => R, arg1: T1, arg2: T2): () => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3) => R} func The function to partially apply arguments to. + * @returns {(arg1: T1, arg2: T2, arg3: T3) => R} Returns the new partially applied function. + * @example + * const sumThree = (a: number, b: number, c: number) => a + b + c; + * const sumWithFive = partialRight(sumThree); + * console.log(sumWithFive(1, 2, 5)); // => 8 + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3) => R): (arg1: T1, arg2: T2, arg3: T3) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3) => R} func The function to partially apply arguments to. + * @param {T1} arg1 The first argument to be partially applied. + * @param {Placeholder} arg2 The placeholder for the second argument. + * @param {Placeholder} arg3 The placeholder for the third argument. + * @returns {(arg2: T2, arg3: T3) => R} Returns the new partially applied function. + * @example + * const formatDate = (day: number, month: number, year: number) => `${day}/${month}/${year}`; + * const formatDateWithDay = partialRight(formatDate, 1, partialRight.placeholder, partialRight.placeholder); + * console.log(formatDateWithDay(12, 2023)); // => '1/12/2023' + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3) => R, arg1: T1, arg2: Placeholder, arg3: Placeholder): (arg2: T2, arg3: T3) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3) => R} func The function to partially apply arguments to. + * @param {T2} arg2 The second argument to be partially applied. + * @param {Placeholder} arg3 The placeholder for the third argument. + * @returns {(arg1: T1, arg3: T3) => R} Returns the new partially applied function. + * @example + * const createUser = (name: string, age: number, country: string) => `${name}, ${age} years old from ${country}`; + * const createUserFromUSA = partialRight(createUser, 'USA', partialRight.placeholder); + * console.log(createUserFromUSA('John', 30)); // => 'John, 30 years old from USA' + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3) => R, arg2: T2, arg3: Placeholder): (arg1: T1, arg3: T3) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3) => R} func The function to partially apply arguments to. + * @param {T1} arg1 The first argument to be partially applied. + * @param {T2} arg2 The second argument to be partially applied. + * @param {Placeholder} arg3 The placeholder for the third argument. + * @returns {(arg3: T3) => R} Returns the new partially applied function. + * @example + * const logMessage = (level: string, message: string, timestamp: string) => `[${level}] ${message} at ${timestamp}`; + * const logError = partialRight(logMessage, 'ERROR', '2023-10-01'); + * console.log(logError('Something went wrong!')); // => '[ERROR] Something went wrong! at 2023-10-01' + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3) => R, arg1: T1, arg2: T2, arg3: Placeholder): (arg3: T3) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3) => R} func The function to partially apply arguments to. + * @param {T3} arg3 The third argument to be partially applied. + * @returns {(arg1: T1, arg2: T2) => R} Returns the new partially applied function. + * @example + * const calculateArea = (length: number, width: number) => length * width; + * const calculateAreaWithWidth = partialRight(calculateArea, 5); + * console.log(calculateAreaWithWidth(10)); // => 50 + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3) => R, arg3: T3): (arg1: T1, arg2: T2) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3) => R} func The function to partially apply arguments to. + * @param {T1} arg1 The first argument to be partially applied. + * @param {Placeholder} arg2 The placeholder for the second argument. + * @param {T3} arg3 The third argument to be partially applied. + * @returns {(arg2: T2) => R} Returns the new partially applied function. + * @example + * const formatCurrency = (amount: number, currency: string) => `${amount} ${currency}`; + * const formatUSD = partialRight(formatCurrency, 100, partialRight.placeholder); + * console.log(formatUSD('USD')); // => '100 USD' + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3) => R, arg1: T1, arg2: Placeholder, arg3: T3): (arg2: T2) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3) => R} func The function to partially apply arguments to. + * @param {T2} arg2 The second argument to be partially applied. + * @param {T3} arg3 The third argument to be partially applied. + * @returns {(arg1: T1) => R} Returns the new partially applied function. + * @example + * const createProfile = (name: string, age: number, country: string) => `${name}, ${age} from ${country}`; + * const createProfileFromCanada = partialRight(createProfile, 'Canada', 'John'); + * console.log(createProfileFromCanada(30)); // => 'John, 30 from Canada' + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3) => R, arg2: T2, arg3: T3): (arg1: T1) => R; +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3) => R, arg1: T1, arg2: T2, arg3: T3): () => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R} func The function to partially apply arguments to. + * @returns {(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R} Returns a new function that takes four arguments. + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R} func The function to partially apply arguments to. + * @param {T1} arg1 The first argument to be partially applied. + * @param {Placeholder} arg2 The placeholder for the second argument. + * @param {Placeholder} arg3 The placeholder for the third argument. + * @param {Placeholder} arg4 The placeholder for the fourth argument. + * @returns {(arg2: T2, arg3: T3, arg4: T4) => R} Returns a new function that takes the second, third, and fourth arguments. + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: T1, arg2: Placeholder, arg3: Placeholder, arg4: Placeholder): (arg2: T2, arg3: T3, arg4: T4) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R} func The function to partially apply arguments to. + * @param {T2} arg2 The second argument to be partially applied. + * @param {Placeholder} arg3 The placeholder for the third argument. + * @param {Placeholder} arg4 The placeholder for the fourth argument. + * @returns {(arg1: T1, arg3: T3, arg4: T4) => R} Returns a new function that takes the first, third, and fourth arguments. + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg2: T2, arg3: Placeholder, arg4: Placeholder): (arg1: T1, arg3: T3, arg4: T4) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R} func The function to partially apply arguments to. + * @param {T1} arg1 The first argument to be partially applied. + * @param {T2} arg2 The second argument to be partially applied. + * @param {Placeholder} arg3 The placeholder for the third argument. + * @param {Placeholder} arg4 The placeholder for the fourth argument. + * @returns {(arg3: T3, arg4: T4) => R} Returns a new function that takes the third and fourth arguments. + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: T1, arg2: T2, arg3: Placeholder, arg4: Placeholder): (arg3: T3, arg4: T4) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R} func The function to partially apply arguments to. + * @param {T3} arg3 The third argument to be partially applied. + * @param {Placeholder} arg4 The placeholder for the fourth argument. + * @returns {(arg1: T1, arg2: T2, arg4: T4) => R} Returns a new function that takes the first, second, and fourth arguments. + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg3: T3, arg4: Placeholder): (arg1: T1, arg2: T2, arg4: T4) => R; +/** + * Creates a function that invokes `func` with the first argument, a placeholder for the second argument, + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R} func The function to partially apply arguments to. + * @param {T1} arg1 The first argument to be partially applied. + * @param {Placeholder} arg2 The placeholder for the second argument. + * @param {T3} arg3 The third argument to be partially applied. + * @param {Placeholder} arg4 The placeholder for the fourth argument. + * @returns {(arg2: T2, arg4: T4) => R} Returns a new function that takes the second and fourth arguments. + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: T1, arg2: Placeholder, arg3: T3, arg4: Placeholder): (arg2: T2, arg4: T4) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R} func The function to partially apply arguments to. + * @param {T2} arg2 The second argument to be partially applied. + * @param {T3} arg3 The third argument to be partially applied. + * @param {Placeholder} arg4 The placeholder for the fourth argument. + * @returns {(arg1: T1, arg4: T4) => R} Returns a new function that takes the first and fourth arguments. + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg2: T2, arg3: T3, arg4: Placeholder): (arg1: T1, arg4: T4) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R} func The function to partially apply arguments to. + * @param {T1} arg1 The first argument to be partially applied. + * @param {T2} arg2 The second argument to be partially applied. + * @param {T3} arg3 The third argument to be partially applied. + * @param {Placeholder} arg4 The placeholder for the fourth argument. + * @returns {(arg4: T4) => R} Returns a new function that takes the fourth argument. + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: T1, arg2: T2, arg3: T3, arg4: Placeholder): (arg4: T4) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R} func The function to partially apply arguments to. + * @param {T4} arg4 The fourth argument to be partially applied. + * @returns {(arg1: T1, arg2: T2, arg3: T3) => R} Returns a new function that takes the first, second, and third arguments. + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg4: T4): (arg1: T1, arg2: T2, arg3: T3) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R} func The function to partially apply arguments to. + * @param {T1} arg1 The first argument to be partially applied. + * @param {Placeholder} arg2 The placeholder for the second argument. + * @param {Placeholder} arg3 The placeholder for the third argument. + * @param {T4} arg4 The fourth argument to be partially applied. + * @returns {(arg2: T2, arg3: T3) => R} Returns a new function that takes the second and third arguments. + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: T1, arg2: Placeholder, arg3: Placeholder, arg4: T4): (arg2: T2, arg3: T3) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R} func The function to partially apply arguments to. + * @param {T2} arg2 The second argument to be partially applied. + * @param {Placeholder} arg3 The placeholder for the third argument. + * @param {T4} arg4 The fourth argument to be partially applied. + * @returns {(arg1: T1, arg3: T3) => R} Returns a new function that takes the first and third arguments. + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg2: T2, arg3: Placeholder, arg4: T4): (arg1: T1, arg3: T3) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R} func The function to partially apply arguments to. + * @param {T1} arg1 The first argument to be partially applied. + * @param {T2} arg2 The second argument to be partially applied. + * @param {Placeholder} arg3 The placeholder for the third argument. + * @param {T4} arg4 The fourth argument to be partially applied. + * @returns {(arg3: T3) => R} Returns a new function that takes the third argument. + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: T1, arg2: T2, arg3: Placeholder, arg4: T4): (arg3: T3) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R} func The function to partially apply arguments to. + * @param {T3} arg3 The third argument to be partially applied. + * @param {T4} arg4 The fourth argument to be partially applied. + * @returns {(arg1: T1, arg2: T2) => R} Returns a new function that takes the first and second arguments. + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg3: T3, arg4: T4): (arg1: T1, arg2: T2) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R} func The function to partially apply arguments to. + * @param {T1} arg1 The first argument to be partially applied. + * @param {Placeholder} arg2 The placeholder for the second argument. + * @param {T3} arg3 The third argument to be partially applied. + * @param {T4} arg4 The fourth argument to be partially applied. + * @returns {(arg2: T2) => R} Returns a new function that takes the second argument. + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: T1, arg2: Placeholder, arg3: T3, arg4: T4): (arg2: T2) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R} func The function to partially apply arguments to. + * @param {T2} arg2 The second argument to be partially applied. + * @param {T3} arg3 The third argument to be partially applied. + * @param {T4} arg4 The fourth argument to be partially applied. + * @returns {(arg1: T1) => R} Returns a new function that takes the first argument. + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg2: T2, arg3: T3, arg4: T4): (arg1: T1) => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template T1 The type of the first argument. + * @template T2 The type of the second argument. + * @template T3 The type of the third argument. + * @template T4 The type of the fourth argument. + * @template R The return type of the function. + * @param {(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R} func The function to partially apply arguments to. + * @param {T1} arg1 The first argument to be partially applied. + * @param {T2} arg2 The second argument to be partially applied. + * @param {T3} arg3 The third argument to be partially applied. + * @param {T4} arg4 The fourth argument to be partially applied. + * @returns {() => R} Returns the new partially applied function. + * @example + * const concatenate = (a: string, b: string, c: string, d: string) => a + b + c + d; + * const concatenateHelloWorld = partialRight(concatenate, 'Hello', ' ', 'World', '!'); + * console.log(concatenateHelloWorld()); // => 'Hello World!' + */ +declare function partialRight(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => R, arg1: T1, arg2: T2, arg3: T3, arg4: T4): () => R; +/** + * This method is like `partial` except that partially applied arguments are appended to the arguments it receives. + * + * The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. + * + * Note: This method doesn't set the `length` property of partially applied functions. + * + * @template F The type of the function to partially apply. + * @param {F} func The function to partially apply arguments to. + * @param {...any[]} args The arguments to be partially applied. + * @returns {function(...args: any[]): ReturnType} Returns the new partially applied function. + * @example + * const log = (...messages: string[]) => console.log(...messages); + * const logError = partialRight(log, 'Error:'); + * logError('Something went wrong!'); // => 'Error: Something went wrong!' + */ +declare function partialRight(func: (...args: any[]) => any, ...args: any[]): (...args: any[]) => any; +declare namespace partialRight { + var placeholder: typeof placeholderSymbol; +} +declare function partialRightImpl any, P>(func: F, placeholder: P, ...partialArgs: any[]): (...args: any[]) => ReturnType; +declare const placeholderSymbol: unique symbol; +type Placeholder = typeof placeholderSymbol; +//#endregion +export { partialRight }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/partialRight.js b/tools/ui/node_modules/es-toolkit/dist/function/partialRight.js new file mode 100644 index 0000000000000000000000000000000000000000..a8f937f7bc6321bf2417d03e25bbcf94c249487a --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/partialRight.js @@ -0,0 +1,47 @@ +//#region src/function/partialRight.ts +/** +* This method is like `partial` except that partially applied arguments are appended to the arguments it receives. +* +* The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. +* +* Note: This method doesn't set the `length` property of partially applied functions. +* +* @template F The type of the function to partially apply. +* @param {F} func The function to partially apply arguments to. +* @param {any[]} partialArgs The arguments to be partially applied. +* @returns {(...args: any[]) => ReturnType} Returns the new partially applied function. +* +* @example +* function greet(greeting, name) { +* return greeting + ' ' + name; +* } +* +* const greetFred = partialRight(greet, 'fred'); +* greetFred('hi'); +* // => 'hi fred' +* +* // Partially applied with placeholders. +* const sayHelloTo = partialRight(greet, 'hello', partialRight.placeholder); +* sayHelloTo('fred'); +* // => 'hello fred' +*/ +function partialRight(func, ...partialArgs) { + return partialRightImpl(func, placeholderSymbol, ...partialArgs); +} +function partialRightImpl(func, placeholder, ...partialArgs) { + const partialedRight = function(...providedArgs) { + const placeholderLength = partialArgs.filter((arg) => arg === placeholder).length; + const rangeLength = Math.max(providedArgs.length - placeholderLength, 0); + const remainingArgs = providedArgs.slice(0, rangeLength); + let providedArgsIndex = rangeLength; + const substitutedArgs = partialArgs.slice().map((arg) => arg === placeholder ? providedArgs[providedArgsIndex++] : arg); + return func.apply(this, remainingArgs.concat(substitutedArgs)); + }; + if (func.prototype) partialedRight.prototype = Object.create(func.prototype); + return partialedRight; +} +const placeholderSymbol = Symbol("partialRight.placeholder"); +partialRight.placeholder = placeholderSymbol; +//#endregion +exports.partialRight = partialRight; +exports.partialRightImpl = partialRightImpl; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/partialRight.mjs b/tools/ui/node_modules/es-toolkit/dist/function/partialRight.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5903aff5b7abd29cc689e2504414e4b635dcefb0 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/partialRight.mjs @@ -0,0 +1,46 @@ +//#region src/function/partialRight.ts +/** +* This method is like `partial` except that partially applied arguments are appended to the arguments it receives. +* +* The partialRight.placeholder value, which defaults to a `symbol`, may be used as a placeholder for partially applied arguments. +* +* Note: This method doesn't set the `length` property of partially applied functions. +* +* @template F The type of the function to partially apply. +* @param {F} func The function to partially apply arguments to. +* @param {any[]} partialArgs The arguments to be partially applied. +* @returns {(...args: any[]) => ReturnType} Returns the new partially applied function. +* +* @example +* function greet(greeting, name) { +* return greeting + ' ' + name; +* } +* +* const greetFred = partialRight(greet, 'fred'); +* greetFred('hi'); +* // => 'hi fred' +* +* // Partially applied with placeholders. +* const sayHelloTo = partialRight(greet, 'hello', partialRight.placeholder); +* sayHelloTo('fred'); +* // => 'hello fred' +*/ +function partialRight(func, ...partialArgs) { + return partialRightImpl(func, placeholderSymbol, ...partialArgs); +} +function partialRightImpl(func, placeholder, ...partialArgs) { + const partialedRight = function(...providedArgs) { + const placeholderLength = partialArgs.filter((arg) => arg === placeholder).length; + const rangeLength = Math.max(providedArgs.length - placeholderLength, 0); + const remainingArgs = providedArgs.slice(0, rangeLength); + let providedArgsIndex = rangeLength; + const substitutedArgs = partialArgs.slice().map((arg) => arg === placeholder ? providedArgs[providedArgsIndex++] : arg); + return func.apply(this, remainingArgs.concat(substitutedArgs)); + }; + if (func.prototype) partialedRight.prototype = Object.create(func.prototype); + return partialedRight; +} +const placeholderSymbol = Symbol("partialRight.placeholder"); +partialRight.placeholder = placeholderSymbol; +//#endregion +export { partialRight, partialRightImpl }; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/rest.d.mts b/tools/ui/node_modules/es-toolkit/dist/function/rest.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..1ee720cd26e933593fd23788cc023e4eef14c1f6 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/rest.d.mts @@ -0,0 +1,34 @@ +//#region src/function/rest.d.ts +/** + * Creates a function that transforms the arguments of the provided function `func`. + * The transformed arguments are passed to `func` such that the arguments starting from a specified index + * are grouped into an array, while the previous arguments are passed as individual elements. + * + * @template F - The type of the function being transformed. + * @param {F} func - The function whose arguments are to be transformed. + * @param {number} [startIndex=func.length - 1] - The index from which to start grouping the remaining arguments into an array. + * Defaults to `func.length - 1`, grouping all arguments after the last parameter. + * @returns {(...args: any[]) => ReturnType} A new function that, when called, returns the result of calling `func` with the transformed arguments. + * + * The transformed arguments are: + * - The first `start` arguments as individual elements. + * - The remaining arguments from index `start` onward grouped into an array. + * @example + * function fn(a, b, c) { + * return [a, b, c]; + * } + * + * // Using default start index (func.length - 1, which is 2 in this case) + * const transformedFn = rest(fn); + * console.log(transformedFn(1, 2, 3, 4)); // [1, 2, [3, 4]] + * + * // Using start index 1 + * const transformedFnWithStart = rest(fn, 1); + * console.log(transformedFnWithStart(1, 2, 3, 4)); // [1, [2, 3, 4]] + * + * // With fewer arguments than the start index + * console.log(transformedFn(1)); // [1, undefined, []] + */ +declare function rest any>(func: F, startIndex?: number): (...args: any[]) => ReturnType; +//#endregion +export { rest }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/rest.d.ts b/tools/ui/node_modules/es-toolkit/dist/function/rest.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1ee720cd26e933593fd23788cc023e4eef14c1f6 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/rest.d.ts @@ -0,0 +1,34 @@ +//#region src/function/rest.d.ts +/** + * Creates a function that transforms the arguments of the provided function `func`. + * The transformed arguments are passed to `func` such that the arguments starting from a specified index + * are grouped into an array, while the previous arguments are passed as individual elements. + * + * @template F - The type of the function being transformed. + * @param {F} func - The function whose arguments are to be transformed. + * @param {number} [startIndex=func.length - 1] - The index from which to start grouping the remaining arguments into an array. + * Defaults to `func.length - 1`, grouping all arguments after the last parameter. + * @returns {(...args: any[]) => ReturnType} A new function that, when called, returns the result of calling `func` with the transformed arguments. + * + * The transformed arguments are: + * - The first `start` arguments as individual elements. + * - The remaining arguments from index `start` onward grouped into an array. + * @example + * function fn(a, b, c) { + * return [a, b, c]; + * } + * + * // Using default start index (func.length - 1, which is 2 in this case) + * const transformedFn = rest(fn); + * console.log(transformedFn(1, 2, 3, 4)); // [1, 2, [3, 4]] + * + * // Using start index 1 + * const transformedFnWithStart = rest(fn, 1); + * console.log(transformedFnWithStart(1, 2, 3, 4)); // [1, [2, 3, 4]] + * + * // With fewer arguments than the start index + * console.log(transformedFn(1)); // [1, undefined, []] + */ +declare function rest any>(func: F, startIndex?: number): (...args: any[]) => ReturnType; +//#endregion +export { rest }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/rest.js b/tools/ui/node_modules/es-toolkit/dist/function/rest.js new file mode 100644 index 0000000000000000000000000000000000000000..3afc88cbebc12365d2e43917b835ecd96f38ab08 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/rest.js @@ -0,0 +1,41 @@ +//#region src/function/rest.ts +/** +* Creates a function that transforms the arguments of the provided function `func`. +* The transformed arguments are passed to `func` such that the arguments starting from a specified index +* are grouped into an array, while the previous arguments are passed as individual elements. +* +* @template F - The type of the function being transformed. +* @param {F} func - The function whose arguments are to be transformed. +* @param {number} [startIndex=func.length - 1] - The index from which to start grouping the remaining arguments into an array. +* Defaults to `func.length - 1`, grouping all arguments after the last parameter. +* @returns {(...args: any[]) => ReturnType} A new function that, when called, returns the result of calling `func` with the transformed arguments. +* +* The transformed arguments are: +* - The first `start` arguments as individual elements. +* - The remaining arguments from index `start` onward grouped into an array. +* @example +* function fn(a, b, c) { +* return [a, b, c]; +* } +* +* // Using default start index (func.length - 1, which is 2 in this case) +* const transformedFn = rest(fn); +* console.log(transformedFn(1, 2, 3, 4)); // [1, 2, [3, 4]] +* +* // Using start index 1 +* const transformedFnWithStart = rest(fn, 1); +* console.log(transformedFnWithStart(1, 2, 3, 4)); // [1, [2, 3, 4]] +* +* // With fewer arguments than the start index +* console.log(transformedFn(1)); // [1, undefined, []] +*/ +function rest(func, startIndex = func.length - 1) { + return function(...args) { + const rest = args.slice(startIndex); + const params = args.slice(0, startIndex); + while (params.length < startIndex) params.push(void 0); + return func.apply(this, [...params, rest]); + }; +} +//#endregion +exports.rest = rest; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/rest.mjs b/tools/ui/node_modules/es-toolkit/dist/function/rest.mjs new file mode 100644 index 0000000000000000000000000000000000000000..9cf8fd32094394aab29110771023e241cd576356 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/rest.mjs @@ -0,0 +1,41 @@ +//#region src/function/rest.ts +/** +* Creates a function that transforms the arguments of the provided function `func`. +* The transformed arguments are passed to `func` such that the arguments starting from a specified index +* are grouped into an array, while the previous arguments are passed as individual elements. +* +* @template F - The type of the function being transformed. +* @param {F} func - The function whose arguments are to be transformed. +* @param {number} [startIndex=func.length - 1] - The index from which to start grouping the remaining arguments into an array. +* Defaults to `func.length - 1`, grouping all arguments after the last parameter. +* @returns {(...args: any[]) => ReturnType} A new function that, when called, returns the result of calling `func` with the transformed arguments. +* +* The transformed arguments are: +* - The first `start` arguments as individual elements. +* - The remaining arguments from index `start` onward grouped into an array. +* @example +* function fn(a, b, c) { +* return [a, b, c]; +* } +* +* // Using default start index (func.length - 1, which is 2 in this case) +* const transformedFn = rest(fn); +* console.log(transformedFn(1, 2, 3, 4)); // [1, 2, [3, 4]] +* +* // Using start index 1 +* const transformedFnWithStart = rest(fn, 1); +* console.log(transformedFnWithStart(1, 2, 3, 4)); // [1, [2, 3, 4]] +* +* // With fewer arguments than the start index +* console.log(transformedFn(1)); // [1, undefined, []] +*/ +function rest(func, startIndex = func.length - 1) { + return function(...args) { + const rest = args.slice(startIndex); + const params = args.slice(0, startIndex); + while (params.length < startIndex) params.push(void 0); + return func.apply(this, [...params, rest]); + }; +} +//#endregion +export { rest }; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/retry.d.mts b/tools/ui/node_modules/es-toolkit/dist/function/retry.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..c0838a9db42713441927e8f3286de0c4914b47bf --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/retry.d.mts @@ -0,0 +1,91 @@ +//#region src/function/retry.d.ts +interface RetryOptions { + /** + * Delay between retries. Can be a static number (milliseconds) or a function + * that computes delay dynamically based on the current attempt. + * + * @default 0 + * @example + * delay: (attempts) => attempt * 50 + */ + delay?: number | ((attempts: number) => number); + /** + * The number of retries to attempt. + * @default Number.POSITIVE_INFINITY + */ + retries?: number; + /** + * An AbortSignal to cancel the retry operation. + */ + signal?: AbortSignal; + /** + * A function that determines whether to retry based on the error and attempt number. + * If not provided, all errors will trigger a retry. + * + * @param {unknown} error - The error that occurred. + * @param {number} attempt - The current attempt number (0-indexed). + * @returns {boolean} Whether to retry. + * + * @example + * shouldRetry: (error, attempt) => error.status >= 500 + */ + shouldRetry?: (error: unknown, attempt: number) => boolean; +} +/** + * Retries a function that returns a promise until it resolves successfully. + * + * @template T + * @param {() => Promise} func - The function to retry. + * @returns {Promise} A promise that resolves with the value of the successful function call. + * + * @example + * // Basic usage with default retry options + * retry(() => fetchData()).then(data => console.log(data)); + */ +declare function retry(func: () => Promise): Promise; +/** + * Retries a function that returns a promise a specified number of times. + * + * @template T + * @param {() => Promise} func - The function to retry. It should return a promise. + * @param {number} retries - The number of retries to attempt. Default is Infinity. + * @returns {Promise} A promise that resolves with the value of the successful function call. + * + * @example + * // Retry a function up to 3 times + * retry(() => fetchData(), 3).then(data => console.log(data)); + */ +declare function retry(func: () => Promise, retries: number): Promise; +/** + * Retries a function that returns a promise with specified options. + * + * @template T + * @param {() => Promise} func - The function to retry. It should return a promise. + * @param {RetryOptions} options - Options to configure the retry behavior. + * @param {number | ((attempts: number) => number)} [options.delay=0] - Delay(milliseconds) between retries. + * @param {number} [options.retries=Infinity] - The number of retries to attempt. + * @param {AbortSignal} [options.signal] - An AbortSignal to cancel the retry operation. + * @param {(error: unknown, attempt: number) => boolean} [options.shouldRetry] - A function that determines whether to retry. + * @returns {Promise} A promise that resolves with the value of the successful function call. + * + * @example + * // Retry a function with a delay of 1000ms between attempts + * retry(() => fetchData(), { delay: 1000, times: 5 }).then(data => console.log(data)); + * + * @example + * // Retry a function with a fixed delay + * retry(() => fetchData(), { delay: 1000, retries: 5 }); + * + * // Retry a function with a delay increasing linearly by 50ms per attempt + * retry(() => fetchData(), { delay: (attempts) => attempt * 50, retries: 5 }); + * + * @example + * // Retry a function with exponential backoff + jitter (max delay 10 seconds) + * retry(() => fetchData(), { + * delay: (attempts) => Math.min(Math.random() * 100 * 2 ** attempts, 10000), + * retries: 5 + * }); + */ +declare function retry(func: () => Promise, options: RetryOptions): Promise; +//#endregion +export { retry }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/retry.d.ts b/tools/ui/node_modules/es-toolkit/dist/function/retry.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c0838a9db42713441927e8f3286de0c4914b47bf --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/retry.d.ts @@ -0,0 +1,91 @@ +//#region src/function/retry.d.ts +interface RetryOptions { + /** + * Delay between retries. Can be a static number (milliseconds) or a function + * that computes delay dynamically based on the current attempt. + * + * @default 0 + * @example + * delay: (attempts) => attempt * 50 + */ + delay?: number | ((attempts: number) => number); + /** + * The number of retries to attempt. + * @default Number.POSITIVE_INFINITY + */ + retries?: number; + /** + * An AbortSignal to cancel the retry operation. + */ + signal?: AbortSignal; + /** + * A function that determines whether to retry based on the error and attempt number. + * If not provided, all errors will trigger a retry. + * + * @param {unknown} error - The error that occurred. + * @param {number} attempt - The current attempt number (0-indexed). + * @returns {boolean} Whether to retry. + * + * @example + * shouldRetry: (error, attempt) => error.status >= 500 + */ + shouldRetry?: (error: unknown, attempt: number) => boolean; +} +/** + * Retries a function that returns a promise until it resolves successfully. + * + * @template T + * @param {() => Promise} func - The function to retry. + * @returns {Promise} A promise that resolves with the value of the successful function call. + * + * @example + * // Basic usage with default retry options + * retry(() => fetchData()).then(data => console.log(data)); + */ +declare function retry(func: () => Promise): Promise; +/** + * Retries a function that returns a promise a specified number of times. + * + * @template T + * @param {() => Promise} func - The function to retry. It should return a promise. + * @param {number} retries - The number of retries to attempt. Default is Infinity. + * @returns {Promise} A promise that resolves with the value of the successful function call. + * + * @example + * // Retry a function up to 3 times + * retry(() => fetchData(), 3).then(data => console.log(data)); + */ +declare function retry(func: () => Promise, retries: number): Promise; +/** + * Retries a function that returns a promise with specified options. + * + * @template T + * @param {() => Promise} func - The function to retry. It should return a promise. + * @param {RetryOptions} options - Options to configure the retry behavior. + * @param {number | ((attempts: number) => number)} [options.delay=0] - Delay(milliseconds) between retries. + * @param {number} [options.retries=Infinity] - The number of retries to attempt. + * @param {AbortSignal} [options.signal] - An AbortSignal to cancel the retry operation. + * @param {(error: unknown, attempt: number) => boolean} [options.shouldRetry] - A function that determines whether to retry. + * @returns {Promise} A promise that resolves with the value of the successful function call. + * + * @example + * // Retry a function with a delay of 1000ms between attempts + * retry(() => fetchData(), { delay: 1000, times: 5 }).then(data => console.log(data)); + * + * @example + * // Retry a function with a fixed delay + * retry(() => fetchData(), { delay: 1000, retries: 5 }); + * + * // Retry a function with a delay increasing linearly by 50ms per attempt + * retry(() => fetchData(), { delay: (attempts) => attempt * 50, retries: 5 }); + * + * @example + * // Retry a function with exponential backoff + jitter (max delay 10 seconds) + * retry(() => fetchData(), { + * delay: (attempts) => Math.min(Math.random() * 100 * 2 ** attempts, 10000), + * retries: 5 + * }); + */ +declare function retry(func: () => Promise, options: RetryOptions): Promise; +//#endregion +export { retry }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/retry.js b/tools/ui/node_modules/es-toolkit/dist/function/retry.js new file mode 100644 index 0000000000000000000000000000000000000000..76dee7735fac9dcfdfb838ad229a3648579c70de --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/retry.js @@ -0,0 +1,45 @@ +const require_delay = require("../promise/delay.js"); +//#region src/function/retry.ts +const DEFAULT_DELAY = 0; +const DEFAULT_RETRIES = Number.POSITIVE_INFINITY; +const DEFAULT_SHOULD_RETRY = () => true; +/** +* Retries a function that returns a promise with specified options. +* +* @template T +* @param {() => Promise} func - The function to retry. It should return a promise. +* @param {number | RetryOptions} [_options] - Either the number of retries or an options object. +* @returns {Promise} A promise that resolves with the value of the successful function call. +*/ +async function retry(func, _options) { + let delay$1; + let retries; + let signal; + let shouldRetry; + if (typeof _options === "number") { + delay$1 = DEFAULT_DELAY; + retries = _options; + signal = void 0; + shouldRetry = DEFAULT_SHOULD_RETRY; + } else { + delay$1 = _options?.delay ?? DEFAULT_DELAY; + retries = _options?.retries ?? DEFAULT_RETRIES; + signal = _options?.signal; + shouldRetry = _options?.shouldRetry ?? DEFAULT_SHOULD_RETRY; + } + let error; + for (let attempts = 0; attempts <= retries; attempts++) { + if (signal?.aborted) throw error ?? /* @__PURE__ */ new Error(`The retry operation was aborted due to an abort signal.`); + try { + return await func(); + } catch (err) { + error = err; + if (!shouldRetry(err, attempts)) throw err; + const currentDelay = typeof delay$1 === "function" ? delay$1(attempts) : delay$1; + await require_delay.delay(currentDelay); + } + } + throw error; +} +//#endregion +exports.retry = retry; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/retry.mjs b/tools/ui/node_modules/es-toolkit/dist/function/retry.mjs new file mode 100644 index 0000000000000000000000000000000000000000..678d29cc9d9c1fadae4d60af8c93490e61bcbf3b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/retry.mjs @@ -0,0 +1,44 @@ +import { delay } from "../promise/delay.mjs"; +//#region src/function/retry.ts +const DEFAULT_DELAY = 0; +const DEFAULT_RETRIES = Number.POSITIVE_INFINITY; +const DEFAULT_SHOULD_RETRY = () => true; +/** +* Retries a function that returns a promise with specified options. +* +* @template T +* @param {() => Promise} func - The function to retry. It should return a promise. +* @param {number | RetryOptions} [_options] - Either the number of retries or an options object. +* @returns {Promise} A promise that resolves with the value of the successful function call. +*/ +async function retry(func, _options) { + let delay$1; + let retries; + let signal; + let shouldRetry; + if (typeof _options === "number") { + delay$1 = DEFAULT_DELAY; + retries = _options; + signal = void 0; + shouldRetry = DEFAULT_SHOULD_RETRY; + } else { + delay$1 = _options?.delay ?? DEFAULT_DELAY; + retries = _options?.retries ?? DEFAULT_RETRIES; + signal = _options?.signal; + shouldRetry = _options?.shouldRetry ?? DEFAULT_SHOULD_RETRY; + } + let error; + for (let attempts = 0; attempts <= retries; attempts++) { + if (signal?.aborted) throw error ?? /* @__PURE__ */ new Error(`The retry operation was aborted due to an abort signal.`); + try { + return await func(); + } catch (err) { + error = err; + if (!shouldRetry(err, attempts)) throw err; + await delay(typeof delay$1 === "function" ? delay$1(attempts) : delay$1); + } + } + throw error; +} +//#endregion +export { retry }; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/spread.d.mts b/tools/ui/node_modules/es-toolkit/dist/function/spread.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..76bf10c692c3675320d8cef7591b1bcc5014984b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/spread.d.mts @@ -0,0 +1,20 @@ +//#region src/function/spread.d.ts +/** + * Creates a new function that spreads elements of an array argument into individual arguments + * for the original function. + * + * @template F - A function type with any number of parameters and any return type. + * @param {F} func - The function to be transformed. It can be any function with any number of arguments. + * @returns {(argsArr: Parameters) => ReturnType} - A new function that takes an array of arguments and returns the result of calling the original function with those arguments. + * + * @example + * function add(a, b) { + * return a + b; + * } + * + * const spreadAdd = spread(add); + * console.log(spreadAdd([1, 2])); // Output: 3 + */ +declare function spread any>(func: F): (argsArr: Parameters) => ReturnType; +//#endregion +export { spread }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/spread.d.ts b/tools/ui/node_modules/es-toolkit/dist/function/spread.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..76bf10c692c3675320d8cef7591b1bcc5014984b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/spread.d.ts @@ -0,0 +1,20 @@ +//#region src/function/spread.d.ts +/** + * Creates a new function that spreads elements of an array argument into individual arguments + * for the original function. + * + * @template F - A function type with any number of parameters and any return type. + * @param {F} func - The function to be transformed. It can be any function with any number of arguments. + * @returns {(argsArr: Parameters) => ReturnType} - A new function that takes an array of arguments and returns the result of calling the original function with those arguments. + * + * @example + * function add(a, b) { + * return a + b; + * } + * + * const spreadAdd = spread(add); + * console.log(spreadAdd([1, 2])); // Output: 3 + */ +declare function spread any>(func: F): (argsArr: Parameters) => ReturnType; +//#endregion +export { spread }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/spread.js b/tools/ui/node_modules/es-toolkit/dist/function/spread.js new file mode 100644 index 0000000000000000000000000000000000000000..23b05e19e026f3dc91b114c01a84390a38f7a71d --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/spread.js @@ -0,0 +1,24 @@ +//#region src/function/spread.ts +/** +* Creates a new function that spreads elements of an array argument into individual arguments +* for the original function. +* +* @template F - A function type with any number of parameters and any return type. +* @param {F} func - The function to be transformed. It can be any function with any number of arguments. +* @returns {(argsArr: Parameters) => ReturnType} - A new function that takes an array of arguments and returns the result of calling the original function with those arguments. +* +* @example +* function add(a, b) { +* return a + b; +* } +* +* const spreadAdd = spread(add); +* console.log(spreadAdd([1, 2])); // Output: 3 +*/ +function spread(func) { + return function(argsArr) { + return func.apply(this, argsArr); + }; +} +//#endregion +exports.spread = spread; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/spread.mjs b/tools/ui/node_modules/es-toolkit/dist/function/spread.mjs new file mode 100644 index 0000000000000000000000000000000000000000..06bd64102f06e24bfeab408cac3ae68375695d2f --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/spread.mjs @@ -0,0 +1,24 @@ +//#region src/function/spread.ts +/** +* Creates a new function that spreads elements of an array argument into individual arguments +* for the original function. +* +* @template F - A function type with any number of parameters and any return type. +* @param {F} func - The function to be transformed. It can be any function with any number of arguments. +* @returns {(argsArr: Parameters) => ReturnType} - A new function that takes an array of arguments and returns the result of calling the original function with those arguments. +* +* @example +* function add(a, b) { +* return a + b; +* } +* +* const spreadAdd = spread(add); +* console.log(spreadAdd([1, 2])); // Output: 3 +*/ +function spread(func) { + return function(argsArr) { + return func.apply(this, argsArr); + }; +} +//#endregion +export { spread }; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/throttle.d.mts b/tools/ui/node_modules/es-toolkit/dist/function/throttle.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..063a737ccdb76448fee396b51f9e52e1a779797c --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/throttle.d.mts @@ -0,0 +1,52 @@ +//#region src/function/throttle.d.ts +interface ThrottleOptions { + /** + * An optional AbortSignal to cancel the throttled function. + */ + signal?: AbortSignal; + /** + * An optional array specifying whether the function should be invoked on the leading edge, trailing edge, or both. + * If `edges` includes "leading", the function will be invoked at the start of the delay period. + * If `edges` includes "trailing", the function will be invoked at the end of the delay period. + * If both "leading" and "trailing" are included, the function will be invoked at both the start and end of the delay period. + * @default ["leading", "trailing"] + */ + edges?: Array<'leading' | 'trailing'>; +} +interface ThrottledFunction void> { + (...args: Parameters): void; + cancel: () => void; + flush: () => void; +} +/** + * Creates a throttled function that only invokes the provided function at most once + * per every `throttleMs` milliseconds. Subsequent calls to the throttled function + * within the wait time will not trigger the execution of the original function. + * + * @template F - The type of function. + * @param {F} func - The function to throttle. + * @param {number} throttleMs - The number of milliseconds to throttle executions to. + * @returns {(...args: Parameters) => void} A new throttled function that accepts the same parameters as the original function. + * + * @example + * const throttledFunction = throttle(() => { + * console.log('Function executed'); + * }, 1000); + * + * // Will log 'Function executed' immediately + * throttledFunction(); + * + * // Will not log anything as it is within the throttle time + * throttledFunction(); + * + * // After 1 second + * setTimeout(() => { + * throttledFunction(); // Will log 'Function executed' + * }, 1000); + */ +declare function throttle void>(func: F, throttleMs: number, { + signal, + edges +}?: ThrottleOptions): ThrottledFunction; +//#endregion +export { ThrottleOptions, ThrottledFunction, throttle }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/throttle.d.ts b/tools/ui/node_modules/es-toolkit/dist/function/throttle.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..063a737ccdb76448fee396b51f9e52e1a779797c --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/throttle.d.ts @@ -0,0 +1,52 @@ +//#region src/function/throttle.d.ts +interface ThrottleOptions { + /** + * An optional AbortSignal to cancel the throttled function. + */ + signal?: AbortSignal; + /** + * An optional array specifying whether the function should be invoked on the leading edge, trailing edge, or both. + * If `edges` includes "leading", the function will be invoked at the start of the delay period. + * If `edges` includes "trailing", the function will be invoked at the end of the delay period. + * If both "leading" and "trailing" are included, the function will be invoked at both the start and end of the delay period. + * @default ["leading", "trailing"] + */ + edges?: Array<'leading' | 'trailing'>; +} +interface ThrottledFunction void> { + (...args: Parameters): void; + cancel: () => void; + flush: () => void; +} +/** + * Creates a throttled function that only invokes the provided function at most once + * per every `throttleMs` milliseconds. Subsequent calls to the throttled function + * within the wait time will not trigger the execution of the original function. + * + * @template F - The type of function. + * @param {F} func - The function to throttle. + * @param {number} throttleMs - The number of milliseconds to throttle executions to. + * @returns {(...args: Parameters) => void} A new throttled function that accepts the same parameters as the original function. + * + * @example + * const throttledFunction = throttle(() => { + * console.log('Function executed'); + * }, 1000); + * + * // Will log 'Function executed' immediately + * throttledFunction(); + * + * // Will not log anything as it is within the throttle time + * throttledFunction(); + * + * // After 1 second + * setTimeout(() => { + * throttledFunction(); // Will log 'Function executed' + * }, 1000); + */ +declare function throttle void>(func: F, throttleMs: number, { + signal, + edges +}?: ThrottleOptions): ThrottledFunction; +//#endregion +export { ThrottleOptions, ThrottledFunction, throttle }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/throttle.js b/tools/ui/node_modules/es-toolkit/dist/function/throttle.js new file mode 100644 index 0000000000000000000000000000000000000000..b4e3ac64d1f229fa36d5f1f95602df0f42763590 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/throttle.js @@ -0,0 +1,54 @@ +const require_debounce = require("./debounce.js"); +//#region src/function/throttle.ts +/** +* Creates a throttled function that only invokes the provided function at most once +* per every `throttleMs` milliseconds. Subsequent calls to the throttled function +* within the wait time will not trigger the execution of the original function. +* +* @template F - The type of function. +* @param {F} func - The function to throttle. +* @param {number} throttleMs - The number of milliseconds to throttle executions to. +* @returns {(...args: Parameters) => void} A new throttled function that accepts the same parameters as the original function. +* +* @example +* const throttledFunction = throttle(() => { +* console.log('Function executed'); +* }, 1000); +* +* // Will log 'Function executed' immediately +* throttledFunction(); +* +* // Will not log anything as it is within the throttle time +* throttledFunction(); +* +* // After 1 second +* setTimeout(() => { +* throttledFunction(); // Will log 'Function executed' +* }, 1000); +*/ +function throttle(func, throttleMs, { signal, edges = ["leading", "trailing"] } = {}) { + let pendingAt = null; + const debounced = require_debounce.debounce(function(...args) { + pendingAt = Date.now(); + func.apply(this, args); + }, throttleMs, { + signal, + edges + }); + const throttled = function(...args) { + if (pendingAt == null) pendingAt = Date.now(); + if (Date.now() - pendingAt >= throttleMs) { + pendingAt = Date.now(); + func.apply(this, args); + debounced.cancel(); + debounced.schedule(); + return; + } + debounced.apply(this, args); + }; + throttled.cancel = debounced.cancel; + throttled.flush = debounced.flush; + return throttled; +} +//#endregion +exports.throttle = throttle; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/throttle.mjs b/tools/ui/node_modules/es-toolkit/dist/function/throttle.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f8b4b4f070c29055388a1bfb0616b16d1c63840a --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/throttle.mjs @@ -0,0 +1,54 @@ +import { debounce } from "./debounce.mjs"; +//#region src/function/throttle.ts +/** +* Creates a throttled function that only invokes the provided function at most once +* per every `throttleMs` milliseconds. Subsequent calls to the throttled function +* within the wait time will not trigger the execution of the original function. +* +* @template F - The type of function. +* @param {F} func - The function to throttle. +* @param {number} throttleMs - The number of milliseconds to throttle executions to. +* @returns {(...args: Parameters) => void} A new throttled function that accepts the same parameters as the original function. +* +* @example +* const throttledFunction = throttle(() => { +* console.log('Function executed'); +* }, 1000); +* +* // Will log 'Function executed' immediately +* throttledFunction(); +* +* // Will not log anything as it is within the throttle time +* throttledFunction(); +* +* // After 1 second +* setTimeout(() => { +* throttledFunction(); // Will log 'Function executed' +* }, 1000); +*/ +function throttle(func, throttleMs, { signal, edges = ["leading", "trailing"] } = {}) { + let pendingAt = null; + const debounced = debounce(function(...args) { + pendingAt = Date.now(); + func.apply(this, args); + }, throttleMs, { + signal, + edges + }); + const throttled = function(...args) { + if (pendingAt == null) pendingAt = Date.now(); + if (Date.now() - pendingAt >= throttleMs) { + pendingAt = Date.now(); + func.apply(this, args); + debounced.cancel(); + debounced.schedule(); + return; + } + debounced.apply(this, args); + }; + throttled.cancel = debounced.cancel; + throttled.flush = debounced.flush; + return throttled; +} +//#endregion +export { throttle }; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/unary.d.mts b/tools/ui/node_modules/es-toolkit/dist/function/unary.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..dd3c875c2cb469e09502bd6cfeb3b4e7eea0ada8 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/unary.d.mts @@ -0,0 +1,18 @@ +//#region src/function/unary.d.ts +/** + * Creates a function that accepts up to one argument, ignoring any additional arguments. + * + * @template F - The type of the function. + * @param {F} func - The function to cap arguments for. + * @returns {(...args: any[]) => ReturnType} Returns the new capped function. + * + * @example + * function fn(a, b, c) { + * console.log(arguments); + * } + * + * unary(fn)(1, 2, 3); // [Arguments] { '0': 1 } + */ +declare function unary any>(func: F): (...args: any[]) => ReturnType; +//#endregion +export { unary }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/unary.d.ts b/tools/ui/node_modules/es-toolkit/dist/function/unary.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dd3c875c2cb469e09502bd6cfeb3b4e7eea0ada8 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/unary.d.ts @@ -0,0 +1,18 @@ +//#region src/function/unary.d.ts +/** + * Creates a function that accepts up to one argument, ignoring any additional arguments. + * + * @template F - The type of the function. + * @param {F} func - The function to cap arguments for. + * @returns {(...args: any[]) => ReturnType} Returns the new capped function. + * + * @example + * function fn(a, b, c) { + * console.log(arguments); + * } + * + * unary(fn)(1, 2, 3); // [Arguments] { '0': 1 } + */ +declare function unary any>(func: F): (...args: any[]) => ReturnType; +//#endregion +export { unary }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/function/unary.js b/tools/ui/node_modules/es-toolkit/dist/function/unary.js new file mode 100644 index 0000000000000000000000000000000000000000..d27177d33b469cc6f59f37a5b37d20fb0135a9ab --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/unary.js @@ -0,0 +1,21 @@ +const require_ary = require("./ary.js"); +//#region src/function/unary.ts +/** +* Creates a function that accepts up to one argument, ignoring any additional arguments. +* +* @template F - The type of the function. +* @param {F} func - The function to cap arguments for. +* @returns {(...args: any[]) => ReturnType} Returns the new capped function. +* +* @example +* function fn(a, b, c) { +* console.log(arguments); +* } +* +* unary(fn)(1, 2, 3); // [Arguments] { '0': 1 } +*/ +function unary(func) { + return require_ary.ary(func, 1); +} +//#endregion +exports.unary = unary; diff --git a/tools/ui/node_modules/es-toolkit/dist/function/unary.mjs b/tools/ui/node_modules/es-toolkit/dist/function/unary.mjs new file mode 100644 index 0000000000000000000000000000000000000000..62aadd9a639724be05c3438b55d3cf9ee5186af6 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/function/unary.mjs @@ -0,0 +1,21 @@ +import { ary } from "./ary.mjs"; +//#region src/function/unary.ts +/** +* Creates a function that accepts up to one argument, ignoring any additional arguments. +* +* @template F - The type of the function. +* @param {F} func - The function to cap arguments for. +* @returns {(...args: any[]) => ReturnType} Returns the new capped function. +* +* @example +* function fn(a, b, c) { +* console.log(arguments); +* } +* +* unary(fn)(1, 2, 3); // [Arguments] { '0': 1 } +*/ +function unary(func) { + return ary(func, 1); +} +//#endregion +export { unary }; diff --git a/tools/ui/node_modules/es-toolkit/dist/index.d.mts b/tools/ui/node_modules/es-toolkit/dist/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..f994dcba4679e3890e221fb6fee0d55117ea2f0d --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/index.d.mts @@ -0,0 +1,186 @@ +import { at } from "./array/at.mjs"; +import { cartesianProduct } from "./array/cartesianProduct.mjs"; +import { chunk } from "./array/chunk.mjs"; +import { combinations } from "./array/combinations.mjs"; +import { compact } from "./array/compact.mjs"; +import { countBy } from "./array/countBy.mjs"; +import { difference } from "./array/difference.mjs"; +import { differenceBy } from "./array/differenceBy.mjs"; +import { differenceWith } from "./array/differenceWith.mjs"; +import { drop } from "./array/drop.mjs"; +import { dropRight } from "./array/dropRight.mjs"; +import { dropRightWhile } from "./array/dropRightWhile.mjs"; +import { dropWhile } from "./array/dropWhile.mjs"; +import { fill } from "./array/fill.mjs"; +import { filterAsync } from "./array/filterAsync.mjs"; +import { flatMap } from "./array/flatMap.mjs"; +import { flatMapAsync } from "./array/flatMapAsync.mjs"; +import { flattenDeep } from "./array/flattenDeep.mjs"; +import { flatMapDeep } from "./array/flatMapDeep.mjs"; +import { flatten } from "./array/flatten.mjs"; +import { forEachAsync } from "./array/forEachAsync.mjs"; +import { forEachRight } from "./array/forEachRight.mjs"; +import { groupBy } from "./array/groupBy.mjs"; +import { head } from "./array/head.mjs"; +import { initial } from "./array/initial.mjs"; +import { intersection } from "./array/intersection.mjs"; +import { intersectionBy } from "./array/intersectionBy.mjs"; +import { intersectionWith } from "./array/intersectionWith.mjs"; +import { isSubset } from "./array/isSubset.mjs"; +import { isSubsetWith } from "./array/isSubsetWith.mjs"; +import { keyBy } from "./array/keyBy.mjs"; +import { last } from "./array/last.mjs"; +import { limitAsync } from "./array/limitAsync.mjs"; +import { mapAsync } from "./array/mapAsync.mjs"; +import { maxBy } from "./array/maxBy.mjs"; +import { minBy } from "./array/minBy.mjs"; +import { orderBy } from "./array/orderBy.mjs"; +import { partition } from "./array/partition.mjs"; +import { pull } from "./array/pull.mjs"; +import { pullAt } from "./array/pullAt.mjs"; +import { reduceAsync } from "./array/reduceAsync.mjs"; +import { remove } from "./array/remove.mjs"; +import { sample } from "./array/sample.mjs"; +import { sampleSize } from "./array/sampleSize.mjs"; +import { shuffle } from "./array/shuffle.mjs"; +import { sortBy } from "./array/sortBy.mjs"; +import { tail } from "./array/tail.mjs"; +import { take } from "./array/take.mjs"; +import { takeRight } from "./array/takeRight.mjs"; +import { takeRightWhile } from "./array/takeRightWhile.mjs"; +import { takeWhile } from "./array/takeWhile.mjs"; +import { toFilled } from "./array/toFilled.mjs"; +import { union } from "./array/union.mjs"; +import { unionBy } from "./array/unionBy.mjs"; +import { unionWith } from "./array/unionWith.mjs"; +import { uniq } from "./array/uniq.mjs"; +import { uniqBy } from "./array/uniqBy.mjs"; +import { uniqWith } from "./array/uniqWith.mjs"; +import { unzip } from "./array/unzip.mjs"; +import { unzipWith } from "./array/unzipWith.mjs"; +import { windowed } from "./array/windowed.mjs"; +import { without } from "./array/without.mjs"; +import { xor } from "./array/xor.mjs"; +import { xorBy } from "./array/xorBy.mjs"; +import { xorWith } from "./array/xorWith.mjs"; +import { zip } from "./array/zip.mjs"; +import { zipObject } from "./array/zipObject.mjs"; +import { zipWith } from "./array/zipWith.mjs"; +import { isEqual } from "./predicate/isEqual.mjs"; +import { AbortError } from "./error/AbortError.mjs"; +import { TimeoutError } from "./error/TimeoutError.mjs"; +import { after } from "./function/after.mjs"; +import { ary } from "./function/ary.mjs"; +import { asyncNoop } from "./function/asyncNoop.mjs"; +import { before } from "./function/before.mjs"; +import { curry } from "./function/curry.mjs"; +import { curryRight } from "./function/curryRight.mjs"; +import { DebounceOptions, DebouncedFunction, debounce } from "./function/debounce.mjs"; +import { flow } from "./function/flow.mjs"; +import { flowRight } from "./function/flowRight.mjs"; +import { identity } from "./function/identity.mjs"; +import { MemoizeCache, memoize } from "./function/memoize.mjs"; +import { negate } from "./function/negate.mjs"; +import { noop } from "./function/noop.mjs"; +import { once } from "./function/once.mjs"; +import { partial } from "./function/partial.mjs"; +import { partialRight } from "./function/partialRight.mjs"; +import { rest } from "./function/rest.mjs"; +import { retry } from "./function/retry.mjs"; +import { spread } from "./function/spread.mjs"; +import { ThrottleOptions, ThrottledFunction, throttle } from "./function/throttle.mjs"; +import { unary } from "./function/unary.mjs"; +import { clamp } from "./math/clamp.mjs"; +import { inRange } from "./math/inRange.mjs"; +import { mean } from "./math/mean.mjs"; +import { meanBy } from "./math/meanBy.mjs"; +import { median } from "./math/median.mjs"; +import { medianBy } from "./math/medianBy.mjs"; +import { percentile } from "./math/percentile.mjs"; +import { random } from "./math/random.mjs"; +import { randomInt } from "./math/randomInt.mjs"; +import { range } from "./math/range.mjs"; +import { rangeRight } from "./math/rangeRight.mjs"; +import { round } from "./math/round.mjs"; +import { sum } from "./math/sum.mjs"; +import { sumBy } from "./math/sumBy.mjs"; +import { clone } from "./object/clone.mjs"; +import { cloneDeep } from "./object/cloneDeep.mjs"; +import { cloneDeepWith } from "./object/cloneDeepWith.mjs"; +import { findKey } from "./object/findKey.mjs"; +import { flattenObject } from "./object/flattenObject.mjs"; +import { invert } from "./object/invert.mjs"; +import { mapKeys } from "./object/mapKeys.mjs"; +import { mapValues } from "./object/mapValues.mjs"; +import { merge } from "./object/merge.mjs"; +import { mergeWith } from "./object/mergeWith.mjs"; +import { omit } from "./object/omit.mjs"; +import { omitBy } from "./object/omitBy.mjs"; +import { pick } from "./object/pick.mjs"; +import { pickBy } from "./object/pickBy.mjs"; +import { sortKeys } from "./object/sortKeys.mjs"; +import { toCamelCaseKeys } from "./object/toCamelCaseKeys.mjs"; +import { toMerged } from "./object/toMerged.mjs"; +import { toSnakeCaseKeys } from "./object/toSnakeCaseKeys.mjs"; +import { isArrayBuffer } from "./predicate/isArrayBuffer.mjs"; +import { isBlob } from "./predicate/isBlob.mjs"; +import { isBoolean } from "./predicate/isBoolean.mjs"; +import { isBrowser } from "./predicate/isBrowser.mjs"; +import { isBuffer } from "./predicate/isBuffer.mjs"; +import { isDate } from "./predicate/isDate.mjs"; +import { isEmptyObject } from "./predicate/isEmptyObject.mjs"; +import { isEqualWith } from "./predicate/isEqualWith.mjs"; +import { isError } from "./predicate/isError.mjs"; +import { isFile } from "./predicate/isFile.mjs"; +import { isFunction } from "./predicate/isFunction.mjs"; +import { isJSON } from "./predicate/isJSON.mjs"; +import { isJSONArray, isJSONObject, isJSONValue } from "./predicate/isJSONValue.mjs"; +import { isLength } from "./predicate/isLength.mjs"; +import { isMap } from "./predicate/isMap.mjs"; +import { isNil } from "./predicate/isNil.mjs"; +import { isNode } from "./predicate/isNode.mjs"; +import { isNotNil } from "./predicate/isNotNil.mjs"; +import { isNull } from "./predicate/isNull.mjs"; +import { isNumber } from "./predicate/isNumber.mjs"; +import { isPlainObject } from "./predicate/isPlainObject.mjs"; +import { isPrimitive } from "./predicate/isPrimitive.mjs"; +import { isPromise } from "./predicate/isPromise.mjs"; +import { isRegExp } from "./predicate/isRegExp.mjs"; +import { isSet } from "./predicate/isSet.mjs"; +import { isString } from "./predicate/isString.mjs"; +import { isSymbol } from "./predicate/isSymbol.mjs"; +import { isTypedArray } from "./predicate/isTypedArray.mjs"; +import { isUndefined } from "./predicate/isUndefined.mjs"; +import { isWeakMap } from "./predicate/isWeakMap.mjs"; +import { isWeakSet } from "./predicate/isWeakSet.mjs"; +import { allKeyed } from "./promise/allKeyed.mjs"; +import { delay } from "./promise/delay.mjs"; +import { Mutex } from "./promise/mutex.mjs"; +import { Semaphore } from "./promise/semaphore.mjs"; +import { timeout } from "./promise/timeout.mjs"; +import { withTimeout } from "./promise/withTimeout.mjs"; +import { camelCase } from "./string/camelCase.mjs"; +import { capitalize } from "./string/capitalize.mjs"; +import { constantCase } from "./string/constantCase.mjs"; +import { deburr } from "./string/deburr.mjs"; +import { escape } from "./string/escape.mjs"; +import { escapeRegExp } from "./string/escapeRegExp.mjs"; +import { kebabCase } from "./string/kebabCase.mjs"; +import { lowerCase } from "./string/lowerCase.mjs"; +import { lowerFirst } from "./string/lowerFirst.mjs"; +import { pad } from "./string/pad.mjs"; +import { pascalCase } from "./string/pascalCase.mjs"; +import { reverseString } from "./string/reverseString.mjs"; +import { snakeCase } from "./string/snakeCase.mjs"; +import { startCase } from "./string/startCase.mjs"; +import { trim } from "./string/trim.mjs"; +import { trimEnd } from "./string/trimEnd.mjs"; +import { trimStart } from "./string/trimStart.mjs"; +import { unescape } from "./string/unescape.mjs"; +import { upperCase } from "./string/upperCase.mjs"; +import { upperFirst } from "./string/upperFirst.mjs"; +import { words } from "./string/words.mjs"; +import { attempt } from "./util/attempt.mjs"; +import { attemptAsync } from "./util/attemptAsync.mjs"; +import { invariant } from "./util/invariant.mjs"; +export { AbortError, DebounceOptions, DebouncedFunction, MemoizeCache, Mutex, Semaphore, ThrottleOptions, ThrottledFunction, TimeoutError, after, allKeyed, ary, invariant as assert, asyncNoop, at, attempt, attemptAsync, before, camelCase, capitalize, cartesianProduct, chunk, clamp, clone, cloneDeep, cloneDeepWith, combinations, compact, constantCase, countBy, curry, curryRight, debounce, deburr, delay, difference, differenceBy, differenceWith, drop, dropRight, dropRightWhile, dropWhile, escape, escapeRegExp, fill, filterAsync, findKey, flatMap, flatMapAsync, flatMapDeep, flatten, flattenDeep, flattenObject, flow, flowRight, forEachAsync, forEachRight, groupBy, head, identity, inRange, initial, intersection, intersectionBy, intersectionWith, invariant, invert, isArrayBuffer, isBlob, isBoolean, isBrowser, isBuffer, isDate, isEmptyObject, isEqual, isEqualWith, isError, isFile, isFunction, isJSON, isJSONArray, isJSONObject, isJSONValue, isLength, isMap, isNil, isNode, isNotNil, isNull, isNumber, isPlainObject, isPrimitive, isPromise, isRegExp, isSet, isString, isSubset, isSubsetWith, isSymbol, isTypedArray, isUndefined, isWeakMap, isWeakSet, kebabCase, keyBy, last, limitAsync, lowerCase, lowerFirst, mapAsync, mapKeys, mapValues, maxBy, mean, meanBy, median, medianBy, memoize, merge, mergeWith, minBy, negate, noop, omit, omitBy, once, orderBy, pad, partial, partialRight, partition, pascalCase, percentile, pick, pickBy, pull, pullAt, random, randomInt, range, rangeRight, reduceAsync, remove, rest, retry, reverseString, round, sample, sampleSize, shuffle, snakeCase, sortBy, sortKeys, spread, startCase, sum, sumBy, tail, take, takeRight, takeRightWhile, takeWhile, throttle, timeout, toCamelCaseKeys, toFilled, toMerged, toSnakeCaseKeys, trim, trimEnd, trimStart, unary, unescape, union, unionBy, unionWith, uniq, uniqBy, uniqWith, unzip, unzipWith, upperCase, upperFirst, windowed, withTimeout, without, words, xor, xorBy, xorWith, zip, zipObject, zipWith }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/index.d.ts b/tools/ui/node_modules/es-toolkit/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b0c00d385d093817f2c27529936e7ea6bd129392 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/index.d.ts @@ -0,0 +1,186 @@ +import { at } from "./array/at.js"; +import { cartesianProduct } from "./array/cartesianProduct.js"; +import { chunk } from "./array/chunk.js"; +import { combinations } from "./array/combinations.js"; +import { compact } from "./array/compact.js"; +import { countBy } from "./array/countBy.js"; +import { difference } from "./array/difference.js"; +import { differenceBy } from "./array/differenceBy.js"; +import { differenceWith } from "./array/differenceWith.js"; +import { drop } from "./array/drop.js"; +import { dropRight } from "./array/dropRight.js"; +import { dropRightWhile } from "./array/dropRightWhile.js"; +import { dropWhile } from "./array/dropWhile.js"; +import { fill } from "./array/fill.js"; +import { filterAsync } from "./array/filterAsync.js"; +import { flatMap } from "./array/flatMap.js"; +import { flatMapAsync } from "./array/flatMapAsync.js"; +import { flattenDeep } from "./array/flattenDeep.js"; +import { flatMapDeep } from "./array/flatMapDeep.js"; +import { flatten } from "./array/flatten.js"; +import { forEachAsync } from "./array/forEachAsync.js"; +import { forEachRight } from "./array/forEachRight.js"; +import { groupBy } from "./array/groupBy.js"; +import { head } from "./array/head.js"; +import { initial } from "./array/initial.js"; +import { intersection } from "./array/intersection.js"; +import { intersectionBy } from "./array/intersectionBy.js"; +import { intersectionWith } from "./array/intersectionWith.js"; +import { isSubset } from "./array/isSubset.js"; +import { isSubsetWith } from "./array/isSubsetWith.js"; +import { keyBy } from "./array/keyBy.js"; +import { last } from "./array/last.js"; +import { limitAsync } from "./array/limitAsync.js"; +import { mapAsync } from "./array/mapAsync.js"; +import { maxBy } from "./array/maxBy.js"; +import { minBy } from "./array/minBy.js"; +import { orderBy } from "./array/orderBy.js"; +import { partition } from "./array/partition.js"; +import { pull } from "./array/pull.js"; +import { pullAt } from "./array/pullAt.js"; +import { reduceAsync } from "./array/reduceAsync.js"; +import { remove } from "./array/remove.js"; +import { sample } from "./array/sample.js"; +import { sampleSize } from "./array/sampleSize.js"; +import { shuffle } from "./array/shuffle.js"; +import { sortBy } from "./array/sortBy.js"; +import { tail } from "./array/tail.js"; +import { take } from "./array/take.js"; +import { takeRight } from "./array/takeRight.js"; +import { takeRightWhile } from "./array/takeRightWhile.js"; +import { takeWhile } from "./array/takeWhile.js"; +import { toFilled } from "./array/toFilled.js"; +import { union } from "./array/union.js"; +import { unionBy } from "./array/unionBy.js"; +import { unionWith } from "./array/unionWith.js"; +import { uniq } from "./array/uniq.js"; +import { uniqBy } from "./array/uniqBy.js"; +import { uniqWith } from "./array/uniqWith.js"; +import { unzip } from "./array/unzip.js"; +import { unzipWith } from "./array/unzipWith.js"; +import { windowed } from "./array/windowed.js"; +import { without } from "./array/without.js"; +import { xor } from "./array/xor.js"; +import { xorBy } from "./array/xorBy.js"; +import { xorWith } from "./array/xorWith.js"; +import { zip } from "./array/zip.js"; +import { zipObject } from "./array/zipObject.js"; +import { zipWith } from "./array/zipWith.js"; +import { isEqual } from "./predicate/isEqual.js"; +import { AbortError } from "./error/AbortError.js"; +import { TimeoutError } from "./error/TimeoutError.js"; +import { after } from "./function/after.js"; +import { ary } from "./function/ary.js"; +import { asyncNoop } from "./function/asyncNoop.js"; +import { before } from "./function/before.js"; +import { curry } from "./function/curry.js"; +import { curryRight } from "./function/curryRight.js"; +import { DebounceOptions, DebouncedFunction, debounce } from "./function/debounce.js"; +import { flow } from "./function/flow.js"; +import { flowRight } from "./function/flowRight.js"; +import { identity } from "./function/identity.js"; +import { MemoizeCache, memoize } from "./function/memoize.js"; +import { negate } from "./function/negate.js"; +import { noop } from "./function/noop.js"; +import { once } from "./function/once.js"; +import { partial } from "./function/partial.js"; +import { partialRight } from "./function/partialRight.js"; +import { rest } from "./function/rest.js"; +import { retry } from "./function/retry.js"; +import { spread } from "./function/spread.js"; +import { ThrottleOptions, ThrottledFunction, throttle } from "./function/throttle.js"; +import { unary } from "./function/unary.js"; +import { clamp } from "./math/clamp.js"; +import { inRange } from "./math/inRange.js"; +import { mean } from "./math/mean.js"; +import { meanBy } from "./math/meanBy.js"; +import { median } from "./math/median.js"; +import { medianBy } from "./math/medianBy.js"; +import { percentile } from "./math/percentile.js"; +import { random } from "./math/random.js"; +import { randomInt } from "./math/randomInt.js"; +import { range } from "./math/range.js"; +import { rangeRight } from "./math/rangeRight.js"; +import { round } from "./math/round.js"; +import { sum } from "./math/sum.js"; +import { sumBy } from "./math/sumBy.js"; +import { clone } from "./object/clone.js"; +import { cloneDeep } from "./object/cloneDeep.js"; +import { cloneDeepWith } from "./object/cloneDeepWith.js"; +import { findKey } from "./object/findKey.js"; +import { flattenObject } from "./object/flattenObject.js"; +import { invert } from "./object/invert.js"; +import { mapKeys } from "./object/mapKeys.js"; +import { mapValues } from "./object/mapValues.js"; +import { merge } from "./object/merge.js"; +import { mergeWith } from "./object/mergeWith.js"; +import { omit } from "./object/omit.js"; +import { omitBy } from "./object/omitBy.js"; +import { pick } from "./object/pick.js"; +import { pickBy } from "./object/pickBy.js"; +import { sortKeys } from "./object/sortKeys.js"; +import { toCamelCaseKeys } from "./object/toCamelCaseKeys.js"; +import { toMerged } from "./object/toMerged.js"; +import { toSnakeCaseKeys } from "./object/toSnakeCaseKeys.js"; +import { isArrayBuffer } from "./predicate/isArrayBuffer.js"; +import { isBlob } from "./predicate/isBlob.js"; +import { isBoolean } from "./predicate/isBoolean.js"; +import { isBrowser } from "./predicate/isBrowser.js"; +import { isBuffer } from "./predicate/isBuffer.js"; +import { isDate } from "./predicate/isDate.js"; +import { isEmptyObject } from "./predicate/isEmptyObject.js"; +import { isEqualWith } from "./predicate/isEqualWith.js"; +import { isError } from "./predicate/isError.js"; +import { isFile } from "./predicate/isFile.js"; +import { isFunction } from "./predicate/isFunction.js"; +import { isJSON } from "./predicate/isJSON.js"; +import { isJSONArray, isJSONObject, isJSONValue } from "./predicate/isJSONValue.js"; +import { isLength } from "./predicate/isLength.js"; +import { isMap } from "./predicate/isMap.js"; +import { isNil } from "./predicate/isNil.js"; +import { isNode } from "./predicate/isNode.js"; +import { isNotNil } from "./predicate/isNotNil.js"; +import { isNull } from "./predicate/isNull.js"; +import { isNumber } from "./predicate/isNumber.js"; +import { isPlainObject } from "./predicate/isPlainObject.js"; +import { isPrimitive } from "./predicate/isPrimitive.js"; +import { isPromise } from "./predicate/isPromise.js"; +import { isRegExp } from "./predicate/isRegExp.js"; +import { isSet } from "./predicate/isSet.js"; +import { isString } from "./predicate/isString.js"; +import { isSymbol } from "./predicate/isSymbol.js"; +import { isTypedArray } from "./predicate/isTypedArray.js"; +import { isUndefined } from "./predicate/isUndefined.js"; +import { isWeakMap } from "./predicate/isWeakMap.js"; +import { isWeakSet } from "./predicate/isWeakSet.js"; +import { allKeyed } from "./promise/allKeyed.js"; +import { delay } from "./promise/delay.js"; +import { Mutex } from "./promise/mutex.js"; +import { Semaphore } from "./promise/semaphore.js"; +import { timeout } from "./promise/timeout.js"; +import { withTimeout } from "./promise/withTimeout.js"; +import { camelCase } from "./string/camelCase.js"; +import { capitalize } from "./string/capitalize.js"; +import { constantCase } from "./string/constantCase.js"; +import { deburr } from "./string/deburr.js"; +import { escape } from "./string/escape.js"; +import { escapeRegExp } from "./string/escapeRegExp.js"; +import { kebabCase } from "./string/kebabCase.js"; +import { lowerCase } from "./string/lowerCase.js"; +import { lowerFirst } from "./string/lowerFirst.js"; +import { pad } from "./string/pad.js"; +import { pascalCase } from "./string/pascalCase.js"; +import { reverseString } from "./string/reverseString.js"; +import { snakeCase } from "./string/snakeCase.js"; +import { startCase } from "./string/startCase.js"; +import { trim } from "./string/trim.js"; +import { trimEnd } from "./string/trimEnd.js"; +import { trimStart } from "./string/trimStart.js"; +import { unescape } from "./string/unescape.js"; +import { upperCase } from "./string/upperCase.js"; +import { upperFirst } from "./string/upperFirst.js"; +import { words } from "./string/words.js"; +import { attempt } from "./util/attempt.js"; +import { attemptAsync } from "./util/attemptAsync.js"; +import { invariant } from "./util/invariant.js"; +export { AbortError, DebounceOptions, DebouncedFunction, MemoizeCache, Mutex, Semaphore, ThrottleOptions, ThrottledFunction, TimeoutError, after, allKeyed, ary, invariant as assert, asyncNoop, at, attempt, attemptAsync, before, camelCase, capitalize, cartesianProduct, chunk, clamp, clone, cloneDeep, cloneDeepWith, combinations, compact, constantCase, countBy, curry, curryRight, debounce, deburr, delay, difference, differenceBy, differenceWith, drop, dropRight, dropRightWhile, dropWhile, escape, escapeRegExp, fill, filterAsync, findKey, flatMap, flatMapAsync, flatMapDeep, flatten, flattenDeep, flattenObject, flow, flowRight, forEachAsync, forEachRight, groupBy, head, identity, inRange, initial, intersection, intersectionBy, intersectionWith, invariant, invert, isArrayBuffer, isBlob, isBoolean, isBrowser, isBuffer, isDate, isEmptyObject, isEqual, isEqualWith, isError, isFile, isFunction, isJSON, isJSONArray, isJSONObject, isJSONValue, isLength, isMap, isNil, isNode, isNotNil, isNull, isNumber, isPlainObject, isPrimitive, isPromise, isRegExp, isSet, isString, isSubset, isSubsetWith, isSymbol, isTypedArray, isUndefined, isWeakMap, isWeakSet, kebabCase, keyBy, last, limitAsync, lowerCase, lowerFirst, mapAsync, mapKeys, mapValues, maxBy, mean, meanBy, median, medianBy, memoize, merge, mergeWith, minBy, negate, noop, omit, omitBy, once, orderBy, pad, partial, partialRight, partition, pascalCase, percentile, pick, pickBy, pull, pullAt, random, randomInt, range, rangeRight, reduceAsync, remove, rest, retry, reverseString, round, sample, sampleSize, shuffle, snakeCase, sortBy, sortKeys, spread, startCase, sum, sumBy, tail, take, takeRight, takeRightWhile, takeWhile, throttle, timeout, toCamelCaseKeys, toFilled, toMerged, toSnakeCaseKeys, trim, trimEnd, trimStart, unary, unescape, union, unionBy, unionWith, uniq, uniqBy, uniqWith, unzip, unzipWith, upperCase, upperFirst, windowed, withTimeout, without, words, xor, xorBy, xorWith, zip, zipObject, zipWith }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/index.js b/tools/ui/node_modules/es-toolkit/dist/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e6645d870f4b01266afd8200c4c7b5933600cf29 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/index.js @@ -0,0 +1,383 @@ +Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); +const require_at = require("./array/at.js"); +const require_cartesianProduct = require("./array/cartesianProduct.js"); +const require_chunk = require("./array/chunk.js"); +const require_combinations = require("./array/combinations.js"); +const require_compact = require("./array/compact.js"); +const require_countBy = require("./array/countBy.js"); +const require_difference = require("./array/difference.js"); +const require_differenceBy = require("./array/differenceBy.js"); +const require_differenceWith = require("./array/differenceWith.js"); +const require_drop = require("./array/drop.js"); +const require_dropRight = require("./array/dropRight.js"); +const require_dropRightWhile = require("./array/dropRightWhile.js"); +const require_dropWhile = require("./array/dropWhile.js"); +const require_fill = require("./array/fill.js"); +const require_semaphore = require("./promise/semaphore.js"); +const require_limitAsync = require("./array/limitAsync.js"); +const require_filterAsync = require("./array/filterAsync.js"); +const require_flatten = require("./array/flatten.js"); +const require_flatMap = require("./array/flatMap.js"); +const require_flatMapAsync = require("./array/flatMapAsync.js"); +const require_flattenDeep = require("./array/flattenDeep.js"); +const require_flatMapDeep = require("./array/flatMapDeep.js"); +const require_forEachAsync = require("./array/forEachAsync.js"); +const require_forEachRight = require("./array/forEachRight.js"); +const require_groupBy = require("./array/groupBy.js"); +const require_head = require("./array/head.js"); +const require_initial = require("./array/initial.js"); +const require_intersection = require("./array/intersection.js"); +const require_intersectionBy = require("./array/intersectionBy.js"); +const require_intersectionWith = require("./array/intersectionWith.js"); +const require_isSubset = require("./array/isSubset.js"); +const require_isSubsetWith = require("./array/isSubsetWith.js"); +const require_keyBy = require("./array/keyBy.js"); +const require_last = require("./array/last.js"); +const require_mapAsync = require("./array/mapAsync.js"); +const require_maxBy = require("./array/maxBy.js"); +const require_minBy = require("./array/minBy.js"); +const require_orderBy = require("./array/orderBy.js"); +const require_partition = require("./array/partition.js"); +const require_pull = require("./array/pull.js"); +const require_pullAt = require("./array/pullAt.js"); +const require_reduceAsync = require("./array/reduceAsync.js"); +const require_remove = require("./array/remove.js"); +const require_sample = require("./array/sample.js"); +const require_random = require("./math/random.js"); +const require_randomInt = require("./math/randomInt.js"); +const require_sampleSize = require("./array/sampleSize.js"); +const require_shuffle = require("./array/shuffle.js"); +const require_sortBy = require("./array/sortBy.js"); +const require_tail = require("./array/tail.js"); +const require_take = require("./array/take.js"); +const require_takeRight = require("./array/takeRight.js"); +const require_takeRightWhile = require("./array/takeRightWhile.js"); +const require_takeWhile = require("./array/takeWhile.js"); +const require_toFilled = require("./array/toFilled.js"); +const require_uniq = require("./array/uniq.js"); +const require_union = require("./array/union.js"); +const require_uniqBy = require("./array/uniqBy.js"); +const require_unionBy = require("./array/unionBy.js"); +const require_uniqWith = require("./array/uniqWith.js"); +const require_unionWith = require("./array/unionWith.js"); +const require_unzip = require("./array/unzip.js"); +const require_unzipWith = require("./array/unzipWith.js"); +const require_windowed = require("./array/windowed.js"); +const require_without = require("./array/without.js"); +const require_xor = require("./array/xor.js"); +const require_xorBy = require("./array/xorBy.js"); +const require_xorWith = require("./array/xorWith.js"); +const require_zip = require("./array/zip.js"); +const require_zipObject = require("./array/zipObject.js"); +const require_zipWith = require("./array/zipWith.js"); +require("./array/index.js"); +const require_AbortError = require("./error/AbortError.js"); +const require_TimeoutError = require("./error/TimeoutError.js"); +require("./error/index.js"); +const require_after = require("./function/after.js"); +const require_ary = require("./function/ary.js"); +const require_asyncNoop = require("./function/asyncNoop.js"); +const require_before = require("./function/before.js"); +const require_curry = require("./function/curry.js"); +const require_curryRight = require("./function/curryRight.js"); +const require_debounce = require("./function/debounce.js"); +const require_flow = require("./function/flow.js"); +const require_flowRight = require("./function/flowRight.js"); +const require_identity = require("./function/identity.js"); +const require_memoize = require("./function/memoize.js"); +const require_negate = require("./function/negate.js"); +const require_noop = require("./function/noop.js"); +const require_once = require("./function/once.js"); +const require_partial = require("./function/partial.js"); +const require_partialRight = require("./function/partialRight.js"); +const require_rest = require("./function/rest.js"); +const require_delay = require("./promise/delay.js"); +const require_retry = require("./function/retry.js"); +const require_spread = require("./function/spread.js"); +const require_throttle = require("./function/throttle.js"); +const require_unary = require("./function/unary.js"); +require("./function/index.js"); +const require_clamp = require("./math/clamp.js"); +const require_inRange = require("./math/inRange.js"); +const require_sum = require("./math/sum.js"); +const require_mean = require("./math/mean.js"); +const require_sumBy = require("./math/sumBy.js"); +const require_meanBy = require("./math/meanBy.js"); +const require_median = require("./math/median.js"); +const require_medianBy = require("./math/medianBy.js"); +const require_percentile = require("./math/percentile.js"); +const require_range = require("./math/range.js"); +const require_rangeRight = require("./math/rangeRight.js"); +const require_round = require("./math/round.js"); +require("./math/index.js"); +const require_isPrimitive = require("./predicate/isPrimitive.js"); +const require_isTypedArray = require("./predicate/isTypedArray.js"); +const require_clone = require("./object/clone.js"); +const require_isBuffer = require("./predicate/isBuffer.js"); +const require_cloneDeepWith = require("./object/cloneDeepWith.js"); +const require_cloneDeep = require("./object/cloneDeep.js"); +const require_findKey = require("./object/findKey.js"); +const require_isPlainObject = require("./predicate/isPlainObject.js"); +const require_flattenObject = require("./object/flattenObject.js"); +const require_invert = require("./object/invert.js"); +const require_mapKeys = require("./object/mapKeys.js"); +const require_mapValues = require("./object/mapValues.js"); +const require_merge = require("./object/merge.js"); +const require_mergeWith = require("./object/mergeWith.js"); +const require_omit = require("./object/omit.js"); +const require_omitBy = require("./object/omitBy.js"); +const require_pick = require("./object/pick.js"); +const require_pickBy = require("./object/pickBy.js"); +const require_sortKeys = require("./object/sortKeys.js"); +const require_capitalize = require("./string/capitalize.js"); +const require_words = require("./string/words.js"); +const require_camelCase = require("./string/camelCase.js"); +const require_toCamelCaseKeys = require("./object/toCamelCaseKeys.js"); +const require_toMerged = require("./object/toMerged.js"); +const require_snakeCase = require("./string/snakeCase.js"); +const require_toSnakeCaseKeys = require("./object/toSnakeCaseKeys.js"); +require("./object/index.js"); +const require_isArrayBuffer = require("./predicate/isArrayBuffer.js"); +const require_isBlob = require("./predicate/isBlob.js"); +const require_isBoolean = require("./predicate/isBoolean.js"); +const require_isBrowser = require("./predicate/isBrowser.js"); +const require_isDate = require("./predicate/isDate.js"); +const require_isEmptyObject = require("./predicate/isEmptyObject.js"); +const require_isEqualWith = require("./predicate/isEqualWith.js"); +const require_isEqual = require("./predicate/isEqual.js"); +const require_isError = require("./predicate/isError.js"); +const require_isFile = require("./predicate/isFile.js"); +const require_isFunction = require("./predicate/isFunction.js"); +const require_isJSON = require("./predicate/isJSON.js"); +const require_isJSONValue = require("./predicate/isJSONValue.js"); +const require_isLength = require("./predicate/isLength.js"); +const require_isMap = require("./predicate/isMap.js"); +const require_isNil = require("./predicate/isNil.js"); +const require_isNode = require("./predicate/isNode.js"); +const require_isNotNil = require("./predicate/isNotNil.js"); +const require_isNull = require("./predicate/isNull.js"); +const require_isNumber = require("./predicate/isNumber.js"); +const require_isPromise = require("./predicate/isPromise.js"); +const require_isRegExp = require("./predicate/isRegExp.js"); +const require_isSet = require("./predicate/isSet.js"); +const require_isString = require("./predicate/isString.js"); +const require_isSymbol = require("./predicate/isSymbol.js"); +const require_isUndefined = require("./predicate/isUndefined.js"); +const require_isWeakMap = require("./predicate/isWeakMap.js"); +const require_isWeakSet = require("./predicate/isWeakSet.js"); +require("./predicate/index.js"); +const require_allKeyed = require("./promise/allKeyed.js"); +const require_mutex = require("./promise/mutex.js"); +const require_timeout = require("./promise/timeout.js"); +const require_withTimeout = require("./promise/withTimeout.js"); +require("./promise/index.js"); +const require_constantCase = require("./string/constantCase.js"); +const require_deburr = require("./string/deburr.js"); +const require_escape = require("./string/escape.js"); +const require_escapeRegExp = require("./string/escapeRegExp.js"); +const require_kebabCase = require("./string/kebabCase.js"); +const require_lowerCase = require("./string/lowerCase.js"); +const require_lowerFirst = require("./string/lowerFirst.js"); +const require_pad = require("./string/pad.js"); +const require_pascalCase = require("./string/pascalCase.js"); +const require_reverseString = require("./string/reverseString.js"); +const require_startCase = require("./string/startCase.js"); +const require_trimEnd = require("./string/trimEnd.js"); +const require_trimStart = require("./string/trimStart.js"); +const require_trim = require("./string/trim.js"); +const require_unescape = require("./string/unescape.js"); +const require_upperCase = require("./string/upperCase.js"); +const require_upperFirst = require("./string/upperFirst.js"); +require("./string/index.js"); +const require_attempt = require("./util/attempt.js"); +const require_attemptAsync = require("./util/attemptAsync.js"); +const require_invariant = require("./util/invariant.js"); +require("./util/index.js"); +exports.AbortError = require_AbortError.AbortError; +exports.Mutex = require_mutex.Mutex; +exports.Semaphore = require_semaphore.Semaphore; +exports.TimeoutError = require_TimeoutError.TimeoutError; +exports.after = require_after.after; +exports.allKeyed = require_allKeyed.allKeyed; +exports.ary = require_ary.ary; +exports.assert = require_invariant.invariant; +exports.asyncNoop = require_asyncNoop.asyncNoop; +exports.at = require_at.at; +exports.attempt = require_attempt.attempt; +exports.attemptAsync = require_attemptAsync.attemptAsync; +exports.before = require_before.before; +exports.camelCase = require_camelCase.camelCase; +exports.capitalize = require_capitalize.capitalize; +exports.cartesianProduct = require_cartesianProduct.cartesianProduct; +exports.chunk = require_chunk.chunk; +exports.clamp = require_clamp.clamp; +exports.clone = require_clone.clone; +exports.cloneDeep = require_cloneDeep.cloneDeep; +exports.cloneDeepWith = require_cloneDeepWith.cloneDeepWith; +exports.combinations = require_combinations.combinations; +exports.compact = require_compact.compact; +exports.constantCase = require_constantCase.constantCase; +exports.countBy = require_countBy.countBy; +exports.curry = require_curry.curry; +exports.curryRight = require_curryRight.curryRight; +exports.debounce = require_debounce.debounce; +exports.deburr = require_deburr.deburr; +exports.delay = require_delay.delay; +exports.difference = require_difference.difference; +exports.differenceBy = require_differenceBy.differenceBy; +exports.differenceWith = require_differenceWith.differenceWith; +exports.drop = require_drop.drop; +exports.dropRight = require_dropRight.dropRight; +exports.dropRightWhile = require_dropRightWhile.dropRightWhile; +exports.dropWhile = require_dropWhile.dropWhile; +exports.escape = require_escape.escape; +exports.escapeRegExp = require_escapeRegExp.escapeRegExp; +exports.fill = require_fill.fill; +exports.filterAsync = require_filterAsync.filterAsync; +exports.findKey = require_findKey.findKey; +exports.flatMap = require_flatMap.flatMap; +exports.flatMapAsync = require_flatMapAsync.flatMapAsync; +exports.flatMapDeep = require_flatMapDeep.flatMapDeep; +exports.flatten = require_flatten.flatten; +exports.flattenDeep = require_flattenDeep.flattenDeep; +exports.flattenObject = require_flattenObject.flattenObject; +exports.flow = require_flow.flow; +exports.flowRight = require_flowRight.flowRight; +exports.forEachAsync = require_forEachAsync.forEachAsync; +exports.forEachRight = require_forEachRight.forEachRight; +exports.groupBy = require_groupBy.groupBy; +exports.head = require_head.head; +exports.identity = require_identity.identity; +exports.inRange = require_inRange.inRange; +exports.initial = require_initial.initial; +exports.intersection = require_intersection.intersection; +exports.intersectionBy = require_intersectionBy.intersectionBy; +exports.intersectionWith = require_intersectionWith.intersectionWith; +exports.invariant = require_invariant.invariant; +exports.invert = require_invert.invert; +exports.isArrayBuffer = require_isArrayBuffer.isArrayBuffer; +exports.isBlob = require_isBlob.isBlob; +exports.isBoolean = require_isBoolean.isBoolean; +exports.isBrowser = require_isBrowser.isBrowser; +exports.isBuffer = require_isBuffer.isBuffer; +exports.isDate = require_isDate.isDate; +exports.isEmptyObject = require_isEmptyObject.isEmptyObject; +exports.isEqual = require_isEqual.isEqual; +exports.isEqualWith = require_isEqualWith.isEqualWith; +exports.isError = require_isError.isError; +exports.isFile = require_isFile.isFile; +exports.isFunction = require_isFunction.isFunction; +exports.isJSON = require_isJSON.isJSON; +exports.isJSONArray = require_isJSONValue.isJSONArray; +exports.isJSONObject = require_isJSONValue.isJSONObject; +exports.isJSONValue = require_isJSONValue.isJSONValue; +exports.isLength = require_isLength.isLength; +exports.isMap = require_isMap.isMap; +exports.isNil = require_isNil.isNil; +exports.isNode = require_isNode.isNode; +exports.isNotNil = require_isNotNil.isNotNil; +exports.isNull = require_isNull.isNull; +exports.isNumber = require_isNumber.isNumber; +exports.isPlainObject = require_isPlainObject.isPlainObject; +exports.isPrimitive = require_isPrimitive.isPrimitive; +exports.isPromise = require_isPromise.isPromise; +exports.isRegExp = require_isRegExp.isRegExp; +exports.isSet = require_isSet.isSet; +exports.isString = require_isString.isString; +exports.isSubset = require_isSubset.isSubset; +exports.isSubsetWith = require_isSubsetWith.isSubsetWith; +exports.isSymbol = require_isSymbol.isSymbol; +exports.isTypedArray = require_isTypedArray.isTypedArray; +exports.isUndefined = require_isUndefined.isUndefined; +exports.isWeakMap = require_isWeakMap.isWeakMap; +exports.isWeakSet = require_isWeakSet.isWeakSet; +exports.kebabCase = require_kebabCase.kebabCase; +exports.keyBy = require_keyBy.keyBy; +exports.last = require_last.last; +exports.limitAsync = require_limitAsync.limitAsync; +exports.lowerCase = require_lowerCase.lowerCase; +exports.lowerFirst = require_lowerFirst.lowerFirst; +exports.mapAsync = require_mapAsync.mapAsync; +exports.mapKeys = require_mapKeys.mapKeys; +exports.mapValues = require_mapValues.mapValues; +exports.maxBy = require_maxBy.maxBy; +exports.mean = require_mean.mean; +exports.meanBy = require_meanBy.meanBy; +exports.median = require_median.median; +exports.medianBy = require_medianBy.medianBy; +exports.memoize = require_memoize.memoize; +exports.merge = require_merge.merge; +exports.mergeWith = require_mergeWith.mergeWith; +exports.minBy = require_minBy.minBy; +exports.negate = require_negate.negate; +exports.noop = require_noop.noop; +exports.omit = require_omit.omit; +exports.omitBy = require_omitBy.omitBy; +exports.once = require_once.once; +exports.orderBy = require_orderBy.orderBy; +exports.pad = require_pad.pad; +exports.partial = require_partial.partial; +exports.partialRight = require_partialRight.partialRight; +exports.partition = require_partition.partition; +exports.pascalCase = require_pascalCase.pascalCase; +exports.percentile = require_percentile.percentile; +exports.pick = require_pick.pick; +exports.pickBy = require_pickBy.pickBy; +exports.pull = require_pull.pull; +exports.pullAt = require_pullAt.pullAt; +exports.random = require_random.random; +exports.randomInt = require_randomInt.randomInt; +exports.range = require_range.range; +exports.rangeRight = require_rangeRight.rangeRight; +exports.reduceAsync = require_reduceAsync.reduceAsync; +exports.remove = require_remove.remove; +exports.rest = require_rest.rest; +exports.retry = require_retry.retry; +exports.reverseString = require_reverseString.reverseString; +exports.round = require_round.round; +exports.sample = require_sample.sample; +exports.sampleSize = require_sampleSize.sampleSize; +exports.shuffle = require_shuffle.shuffle; +exports.snakeCase = require_snakeCase.snakeCase; +exports.sortBy = require_sortBy.sortBy; +exports.sortKeys = require_sortKeys.sortKeys; +exports.spread = require_spread.spread; +exports.startCase = require_startCase.startCase; +exports.sum = require_sum.sum; +exports.sumBy = require_sumBy.sumBy; +exports.tail = require_tail.tail; +exports.take = require_take.take; +exports.takeRight = require_takeRight.takeRight; +exports.takeRightWhile = require_takeRightWhile.takeRightWhile; +exports.takeWhile = require_takeWhile.takeWhile; +exports.throttle = require_throttle.throttle; +exports.timeout = require_timeout.timeout; +exports.toCamelCaseKeys = require_toCamelCaseKeys.toCamelCaseKeys; +exports.toFilled = require_toFilled.toFilled; +exports.toMerged = require_toMerged.toMerged; +exports.toSnakeCaseKeys = require_toSnakeCaseKeys.toSnakeCaseKeys; +exports.trim = require_trim.trim; +exports.trimEnd = require_trimEnd.trimEnd; +exports.trimStart = require_trimStart.trimStart; +exports.unary = require_unary.unary; +exports.unescape = require_unescape.unescape; +exports.union = require_union.union; +exports.unionBy = require_unionBy.unionBy; +exports.unionWith = require_unionWith.unionWith; +exports.uniq = require_uniq.uniq; +exports.uniqBy = require_uniqBy.uniqBy; +exports.uniqWith = require_uniqWith.uniqWith; +exports.unzip = require_unzip.unzip; +exports.unzipWith = require_unzipWith.unzipWith; +exports.upperCase = require_upperCase.upperCase; +exports.upperFirst = require_upperFirst.upperFirst; +exports.windowed = require_windowed.windowed; +exports.withTimeout = require_withTimeout.withTimeout; +exports.without = require_without.without; +exports.words = require_words.words; +exports.xor = require_xor.xor; +exports.xorBy = require_xorBy.xorBy; +exports.xorWith = require_xorWith.xorWith; +exports.zip = require_zip.zip; +exports.zipObject = require_zipObject.zipObject; +exports.zipWith = require_zipWith.zipWith; diff --git a/tools/ui/node_modules/es-toolkit/dist/index.mjs b/tools/ui/node_modules/es-toolkit/dist/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e1be0c0e0856c6878b0880c68e391a1b19317727 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/index.mjs @@ -0,0 +1,195 @@ +import { at } from "./array/at.mjs"; +import { cartesianProduct } from "./array/cartesianProduct.mjs"; +import { chunk } from "./array/chunk.mjs"; +import { combinations } from "./array/combinations.mjs"; +import { compact } from "./array/compact.mjs"; +import { countBy } from "./array/countBy.mjs"; +import { difference } from "./array/difference.mjs"; +import { differenceBy } from "./array/differenceBy.mjs"; +import { differenceWith } from "./array/differenceWith.mjs"; +import { drop } from "./array/drop.mjs"; +import { dropRight } from "./array/dropRight.mjs"; +import { dropRightWhile } from "./array/dropRightWhile.mjs"; +import { dropWhile } from "./array/dropWhile.mjs"; +import { fill } from "./array/fill.mjs"; +import { Semaphore } from "./promise/semaphore.mjs"; +import { limitAsync } from "./array/limitAsync.mjs"; +import { filterAsync } from "./array/filterAsync.mjs"; +import { flatten } from "./array/flatten.mjs"; +import { flatMap } from "./array/flatMap.mjs"; +import { flatMapAsync } from "./array/flatMapAsync.mjs"; +import { flattenDeep } from "./array/flattenDeep.mjs"; +import { flatMapDeep } from "./array/flatMapDeep.mjs"; +import { forEachAsync } from "./array/forEachAsync.mjs"; +import { forEachRight } from "./array/forEachRight.mjs"; +import { groupBy } from "./array/groupBy.mjs"; +import { head } from "./array/head.mjs"; +import { initial } from "./array/initial.mjs"; +import { intersection } from "./array/intersection.mjs"; +import { intersectionBy } from "./array/intersectionBy.mjs"; +import { intersectionWith } from "./array/intersectionWith.mjs"; +import { isSubset } from "./array/isSubset.mjs"; +import { isSubsetWith } from "./array/isSubsetWith.mjs"; +import { keyBy } from "./array/keyBy.mjs"; +import { last } from "./array/last.mjs"; +import { mapAsync } from "./array/mapAsync.mjs"; +import { maxBy } from "./array/maxBy.mjs"; +import { minBy } from "./array/minBy.mjs"; +import { orderBy } from "./array/orderBy.mjs"; +import { partition } from "./array/partition.mjs"; +import { pull } from "./array/pull.mjs"; +import { pullAt } from "./array/pullAt.mjs"; +import { reduceAsync } from "./array/reduceAsync.mjs"; +import { remove } from "./array/remove.mjs"; +import { sample } from "./array/sample.mjs"; +import { random } from "./math/random.mjs"; +import { randomInt } from "./math/randomInt.mjs"; +import { sampleSize } from "./array/sampleSize.mjs"; +import { shuffle } from "./array/shuffle.mjs"; +import { sortBy } from "./array/sortBy.mjs"; +import { tail } from "./array/tail.mjs"; +import { take } from "./array/take.mjs"; +import { takeRight } from "./array/takeRight.mjs"; +import { takeRightWhile } from "./array/takeRightWhile.mjs"; +import { takeWhile } from "./array/takeWhile.mjs"; +import { toFilled } from "./array/toFilled.mjs"; +import { uniq } from "./array/uniq.mjs"; +import { union } from "./array/union.mjs"; +import { uniqBy } from "./array/uniqBy.mjs"; +import { unionBy } from "./array/unionBy.mjs"; +import { uniqWith } from "./array/uniqWith.mjs"; +import { unionWith } from "./array/unionWith.mjs"; +import { unzip } from "./array/unzip.mjs"; +import { unzipWith } from "./array/unzipWith.mjs"; +import { windowed } from "./array/windowed.mjs"; +import { without } from "./array/without.mjs"; +import { xor } from "./array/xor.mjs"; +import { xorBy } from "./array/xorBy.mjs"; +import { xorWith } from "./array/xorWith.mjs"; +import { zip } from "./array/zip.mjs"; +import { zipObject } from "./array/zipObject.mjs"; +import { zipWith } from "./array/zipWith.mjs"; +import "./array/index.mjs"; +import { AbortError } from "./error/AbortError.mjs"; +import { TimeoutError } from "./error/TimeoutError.mjs"; +import "./error/index.mjs"; +import { after } from "./function/after.mjs"; +import { ary } from "./function/ary.mjs"; +import { asyncNoop } from "./function/asyncNoop.mjs"; +import { before } from "./function/before.mjs"; +import { curry } from "./function/curry.mjs"; +import { curryRight } from "./function/curryRight.mjs"; +import { debounce } from "./function/debounce.mjs"; +import { flow } from "./function/flow.mjs"; +import { flowRight } from "./function/flowRight.mjs"; +import { identity } from "./function/identity.mjs"; +import { memoize } from "./function/memoize.mjs"; +import { negate } from "./function/negate.mjs"; +import { noop } from "./function/noop.mjs"; +import { once } from "./function/once.mjs"; +import { partial } from "./function/partial.mjs"; +import { partialRight } from "./function/partialRight.mjs"; +import { rest } from "./function/rest.mjs"; +import { delay } from "./promise/delay.mjs"; +import { retry } from "./function/retry.mjs"; +import { spread } from "./function/spread.mjs"; +import { throttle } from "./function/throttle.mjs"; +import { unary } from "./function/unary.mjs"; +import "./function/index.mjs"; +import { clamp } from "./math/clamp.mjs"; +import { inRange } from "./math/inRange.mjs"; +import { sum } from "./math/sum.mjs"; +import { mean } from "./math/mean.mjs"; +import { sumBy } from "./math/sumBy.mjs"; +import { meanBy } from "./math/meanBy.mjs"; +import { median } from "./math/median.mjs"; +import { medianBy } from "./math/medianBy.mjs"; +import { percentile } from "./math/percentile.mjs"; +import { range } from "./math/range.mjs"; +import { rangeRight } from "./math/rangeRight.mjs"; +import { round } from "./math/round.mjs"; +import "./math/index.mjs"; +import { isPrimitive } from "./predicate/isPrimitive.mjs"; +import { isTypedArray } from "./predicate/isTypedArray.mjs"; +import { clone } from "./object/clone.mjs"; +import { isBuffer } from "./predicate/isBuffer.mjs"; +import { cloneDeepWith } from "./object/cloneDeepWith.mjs"; +import { cloneDeep } from "./object/cloneDeep.mjs"; +import { findKey } from "./object/findKey.mjs"; +import { isPlainObject } from "./predicate/isPlainObject.mjs"; +import { flattenObject } from "./object/flattenObject.mjs"; +import { invert } from "./object/invert.mjs"; +import { mapKeys } from "./object/mapKeys.mjs"; +import { mapValues } from "./object/mapValues.mjs"; +import { merge } from "./object/merge.mjs"; +import { mergeWith } from "./object/mergeWith.mjs"; +import { omit } from "./object/omit.mjs"; +import { omitBy } from "./object/omitBy.mjs"; +import { pick } from "./object/pick.mjs"; +import { pickBy } from "./object/pickBy.mjs"; +import { sortKeys } from "./object/sortKeys.mjs"; +import { capitalize } from "./string/capitalize.mjs"; +import { words } from "./string/words.mjs"; +import { camelCase } from "./string/camelCase.mjs"; +import { toCamelCaseKeys } from "./object/toCamelCaseKeys.mjs"; +import { toMerged } from "./object/toMerged.mjs"; +import { snakeCase } from "./string/snakeCase.mjs"; +import { toSnakeCaseKeys } from "./object/toSnakeCaseKeys.mjs"; +import "./object/index.mjs"; +import { isArrayBuffer } from "./predicate/isArrayBuffer.mjs"; +import { isBlob } from "./predicate/isBlob.mjs"; +import { isBoolean } from "./predicate/isBoolean.mjs"; +import { isBrowser } from "./predicate/isBrowser.mjs"; +import { isDate } from "./predicate/isDate.mjs"; +import { isEmptyObject } from "./predicate/isEmptyObject.mjs"; +import { isEqualWith } from "./predicate/isEqualWith.mjs"; +import { isEqual } from "./predicate/isEqual.mjs"; +import { isError } from "./predicate/isError.mjs"; +import { isFile } from "./predicate/isFile.mjs"; +import { isFunction } from "./predicate/isFunction.mjs"; +import { isJSON } from "./predicate/isJSON.mjs"; +import { isJSONArray, isJSONObject, isJSONValue } from "./predicate/isJSONValue.mjs"; +import { isLength } from "./predicate/isLength.mjs"; +import { isMap } from "./predicate/isMap.mjs"; +import { isNil } from "./predicate/isNil.mjs"; +import { isNode } from "./predicate/isNode.mjs"; +import { isNotNil } from "./predicate/isNotNil.mjs"; +import { isNull } from "./predicate/isNull.mjs"; +import { isNumber } from "./predicate/isNumber.mjs"; +import { isPromise } from "./predicate/isPromise.mjs"; +import { isRegExp } from "./predicate/isRegExp.mjs"; +import { isSet } from "./predicate/isSet.mjs"; +import { isString } from "./predicate/isString.mjs"; +import { isSymbol } from "./predicate/isSymbol.mjs"; +import { isUndefined } from "./predicate/isUndefined.mjs"; +import { isWeakMap } from "./predicate/isWeakMap.mjs"; +import { isWeakSet } from "./predicate/isWeakSet.mjs"; +import "./predicate/index.mjs"; +import { allKeyed } from "./promise/allKeyed.mjs"; +import { Mutex } from "./promise/mutex.mjs"; +import { timeout } from "./promise/timeout.mjs"; +import { withTimeout } from "./promise/withTimeout.mjs"; +import "./promise/index.mjs"; +import { constantCase } from "./string/constantCase.mjs"; +import { deburr } from "./string/deburr.mjs"; +import { escape } from "./string/escape.mjs"; +import { escapeRegExp } from "./string/escapeRegExp.mjs"; +import { kebabCase } from "./string/kebabCase.mjs"; +import { lowerCase } from "./string/lowerCase.mjs"; +import { lowerFirst } from "./string/lowerFirst.mjs"; +import { pad } from "./string/pad.mjs"; +import { pascalCase } from "./string/pascalCase.mjs"; +import { reverseString } from "./string/reverseString.mjs"; +import { startCase } from "./string/startCase.mjs"; +import { trimEnd } from "./string/trimEnd.mjs"; +import { trimStart } from "./string/trimStart.mjs"; +import { trim } from "./string/trim.mjs"; +import { unescape } from "./string/unescape.mjs"; +import { upperCase } from "./string/upperCase.mjs"; +import { upperFirst } from "./string/upperFirst.mjs"; +import "./string/index.mjs"; +import { attempt } from "./util/attempt.mjs"; +import { attemptAsync } from "./util/attemptAsync.mjs"; +import { invariant } from "./util/invariant.mjs"; +import "./util/index.mjs"; +export { AbortError, Mutex, Semaphore, TimeoutError, after, allKeyed, ary, invariant as assert, asyncNoop, at, attempt, attemptAsync, before, camelCase, capitalize, cartesianProduct, chunk, clamp, clone, cloneDeep, cloneDeepWith, combinations, compact, constantCase, countBy, curry, curryRight, debounce, deburr, delay, difference, differenceBy, differenceWith, drop, dropRight, dropRightWhile, dropWhile, escape, escapeRegExp, fill, filterAsync, findKey, flatMap, flatMapAsync, flatMapDeep, flatten, flattenDeep, flattenObject, flow, flowRight, forEachAsync, forEachRight, groupBy, head, identity, inRange, initial, intersection, intersectionBy, intersectionWith, invariant, invert, isArrayBuffer, isBlob, isBoolean, isBrowser, isBuffer, isDate, isEmptyObject, isEqual, isEqualWith, isError, isFile, isFunction, isJSON, isJSONArray, isJSONObject, isJSONValue, isLength, isMap, isNil, isNode, isNotNil, isNull, isNumber, isPlainObject, isPrimitive, isPromise, isRegExp, isSet, isString, isSubset, isSubsetWith, isSymbol, isTypedArray, isUndefined, isWeakMap, isWeakSet, kebabCase, keyBy, last, limitAsync, lowerCase, lowerFirst, mapAsync, mapKeys, mapValues, maxBy, mean, meanBy, median, medianBy, memoize, merge, mergeWith, minBy, negate, noop, omit, omitBy, once, orderBy, pad, partial, partialRight, partition, pascalCase, percentile, pick, pickBy, pull, pullAt, random, randomInt, range, rangeRight, reduceAsync, remove, rest, retry, reverseString, round, sample, sampleSize, shuffle, snakeCase, sortBy, sortKeys, spread, startCase, sum, sumBy, tail, take, takeRight, takeRightWhile, takeWhile, throttle, timeout, toCamelCaseKeys, toFilled, toMerged, toSnakeCaseKeys, trim, trimEnd, trimStart, unary, unescape, union, unionBy, unionWith, uniq, uniqBy, uniqWith, unzip, unzipWith, upperCase, upperFirst, windowed, withTimeout, without, words, xor, xorBy, xorWith, zip, zipObject, zipWith }; diff --git a/tools/ui/node_modules/es-toolkit/dist/map/countBy.d.mts b/tools/ui/node_modules/es-toolkit/dist/map/countBy.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..22b466355701cda09cbfa923f6eaf4415dd0a4ee --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/countBy.d.mts @@ -0,0 +1,36 @@ +//#region src/map/countBy.d.ts +/** + * Counts the occurrences of items in a Map based on a transformation function. + * + * This function takes a Map and a function that generates a key from each value-key pair. + * It returns an object with the generated keys as properties and their counts as values. + * The count is incremented for each entry for which the transformation produces the same key. + * + * @template K - The type of the Map's keys. + * @template V - The type of the Map's values. + * @template K2 - The type of keys produced by the transformation function. + * @param {Map} map - The Map to count occurrences from. + * @param {(value: V, key: K, object: Map) => K2} mapper - The function to produce a key for counting. + * @returns {Record} An object containing the mapped keys and their counts. + * + * @example + * const map = new Map([ + * ['a', 1], + * ['b', 2], + * ['c', 1] + * ]); + * const result = countBy(map, (value) => value); + * // result will be { 1: 2, 2: 1 } + * + * @example + * const map = new Map([ + * ['alice', 20], + * ['bob', 30], + * ['carol', 20] + * ]); + * const result = countBy(map, (value, key) => key[0]); + * // result will be { a: 1, b: 1, c: 1 } + */ +declare function countBy(map: Map, mapper: (value: V, key: K, object: Map) => K2): Map; +//#endregion +export { countBy }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/map/countBy.d.ts b/tools/ui/node_modules/es-toolkit/dist/map/countBy.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..22b466355701cda09cbfa923f6eaf4415dd0a4ee --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/countBy.d.ts @@ -0,0 +1,36 @@ +//#region src/map/countBy.d.ts +/** + * Counts the occurrences of items in a Map based on a transformation function. + * + * This function takes a Map and a function that generates a key from each value-key pair. + * It returns an object with the generated keys as properties and their counts as values. + * The count is incremented for each entry for which the transformation produces the same key. + * + * @template K - The type of the Map's keys. + * @template V - The type of the Map's values. + * @template K2 - The type of keys produced by the transformation function. + * @param {Map} map - The Map to count occurrences from. + * @param {(value: V, key: K, object: Map) => K2} mapper - The function to produce a key for counting. + * @returns {Record} An object containing the mapped keys and their counts. + * + * @example + * const map = new Map([ + * ['a', 1], + * ['b', 2], + * ['c', 1] + * ]); + * const result = countBy(map, (value) => value); + * // result will be { 1: 2, 2: 1 } + * + * @example + * const map = new Map([ + * ['alice', 20], + * ['bob', 30], + * ['carol', 20] + * ]); + * const result = countBy(map, (value, key) => key[0]); + * // result will be { a: 1, b: 1, c: 1 } + */ +declare function countBy(map: Map, mapper: (value: V, key: K, object: Map) => K2): Map; +//#endregion +export { countBy }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/map/countBy.js b/tools/ui/node_modules/es-toolkit/dist/map/countBy.js new file mode 100644 index 0000000000000000000000000000000000000000..1a86b150356e62992c7bb4aa328e6e8ff0b939ce --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/countBy.js @@ -0,0 +1,43 @@ +//#region src/map/countBy.ts +/** +* Counts the occurrences of items in a Map based on a transformation function. +* +* This function takes a Map and a function that generates a key from each value-key pair. +* It returns an object with the generated keys as properties and their counts as values. +* The count is incremented for each entry for which the transformation produces the same key. +* +* @template K - The type of the Map's keys. +* @template V - The type of the Map's values. +* @template K2 - The type of keys produced by the transformation function. +* @param {Map} map - The Map to count occurrences from. +* @param {(value: V, key: K, object: Map) => K2} mapper - The function to produce a key for counting. +* @returns {Record} An object containing the mapped keys and their counts. +* +* @example +* const map = new Map([ +* ['a', 1], +* ['b', 2], +* ['c', 1] +* ]); +* const result = countBy(map, (value) => value); +* // result will be { 1: 2, 2: 1 } +* +* @example +* const map = new Map([ +* ['alice', 20], +* ['bob', 30], +* ['carol', 20] +* ]); +* const result = countBy(map, (value, key) => key[0]); +* // result will be { a: 1, b: 1, c: 1 } +*/ +function countBy(map, mapper) { + const result = /* @__PURE__ */ new Map(); + for (const [key, value] of map) { + const mappedKey = mapper(value, key, map); + result.set(mappedKey, (result.get(mappedKey) ?? 0) + 1); + } + return result; +} +//#endregion +exports.countBy = countBy; diff --git a/tools/ui/node_modules/es-toolkit/dist/map/countBy.mjs b/tools/ui/node_modules/es-toolkit/dist/map/countBy.mjs new file mode 100644 index 0000000000000000000000000000000000000000..cd6133effd9befbb9fb7103c1a5c7337a3581c06 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/countBy.mjs @@ -0,0 +1,43 @@ +//#region src/map/countBy.ts +/** +* Counts the occurrences of items in a Map based on a transformation function. +* +* This function takes a Map and a function that generates a key from each value-key pair. +* It returns an object with the generated keys as properties and their counts as values. +* The count is incremented for each entry for which the transformation produces the same key. +* +* @template K - The type of the Map's keys. +* @template V - The type of the Map's values. +* @template K2 - The type of keys produced by the transformation function. +* @param {Map} map - The Map to count occurrences from. +* @param {(value: V, key: K, object: Map) => K2} mapper - The function to produce a key for counting. +* @returns {Record} An object containing the mapped keys and their counts. +* +* @example +* const map = new Map([ +* ['a', 1], +* ['b', 2], +* ['c', 1] +* ]); +* const result = countBy(map, (value) => value); +* // result will be { 1: 2, 2: 1 } +* +* @example +* const map = new Map([ +* ['alice', 20], +* ['bob', 30], +* ['carol', 20] +* ]); +* const result = countBy(map, (value, key) => key[0]); +* // result will be { a: 1, b: 1, c: 1 } +*/ +function countBy(map, mapper) { + const result = /* @__PURE__ */ new Map(); + for (const [key, value] of map) { + const mappedKey = mapper(value, key, map); + result.set(mappedKey, (result.get(mappedKey) ?? 0) + 1); + } + return result; +} +//#endregion +export { countBy }; diff --git a/tools/ui/node_modules/es-toolkit/dist/map/every.d.mts b/tools/ui/node_modules/es-toolkit/dist/map/every.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..0ec98f16acb2fbe32c1fa8ea842db98fbb9fc23a --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/every.d.mts @@ -0,0 +1,29 @@ +//#region src/map/every.d.ts +/** + * Tests whether all entries in a Map satisfy the provided predicate function. + * + * This function iterates through all entries of the Map and checks if the predicate function + * returns true for every entry. It returns true if the predicate is satisfied for all entries, + * and false otherwise. + * + * @template K - The type of keys in the Map. + * @template V - The type of values in the Map. + * @param {Map} map - The Map to test. + * @param {(value: V, key: K, map: Map) => boolean} doesMatch - A predicate function that tests each entry. + * @returns {boolean} true if all entries satisfy the predicate, false otherwise. + * + * @example + * const map = new Map([ + * ['a', 10], + * ['b', 20], + * ['c', 30] + * ]); + * const result = every(map, (value) => value > 5); + * // result will be: true + * + * const result2 = every(map, (value) => value > 15); + * // result2 will be: false + */ +declare function every(map: Map, doesMatch: (value: V, key: K, map: Map) => boolean): boolean; +//#endregion +export { every }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/map/every.d.ts b/tools/ui/node_modules/es-toolkit/dist/map/every.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0ec98f16acb2fbe32c1fa8ea842db98fbb9fc23a --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/every.d.ts @@ -0,0 +1,29 @@ +//#region src/map/every.d.ts +/** + * Tests whether all entries in a Map satisfy the provided predicate function. + * + * This function iterates through all entries of the Map and checks if the predicate function + * returns true for every entry. It returns true if the predicate is satisfied for all entries, + * and false otherwise. + * + * @template K - The type of keys in the Map. + * @template V - The type of values in the Map. + * @param {Map} map - The Map to test. + * @param {(value: V, key: K, map: Map) => boolean} doesMatch - A predicate function that tests each entry. + * @returns {boolean} true if all entries satisfy the predicate, false otherwise. + * + * @example + * const map = new Map([ + * ['a', 10], + * ['b', 20], + * ['c', 30] + * ]); + * const result = every(map, (value) => value > 5); + * // result will be: true + * + * const result2 = every(map, (value) => value > 15); + * // result2 will be: false + */ +declare function every(map: Map, doesMatch: (value: V, key: K, map: Map) => boolean): boolean; +//#endregion +export { every }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/map/every.js b/tools/ui/node_modules/es-toolkit/dist/map/every.js new file mode 100644 index 0000000000000000000000000000000000000000..66826adcdba1349eeb97aab5be4fc14e1e335cd4 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/every.js @@ -0,0 +1,32 @@ +//#region src/map/every.ts +/** +* Tests whether all entries in a Map satisfy the provided predicate function. +* +* This function iterates through all entries of the Map and checks if the predicate function +* returns true for every entry. It returns true if the predicate is satisfied for all entries, +* and false otherwise. +* +* @template K - The type of keys in the Map. +* @template V - The type of values in the Map. +* @param {Map} map - The Map to test. +* @param {(value: V, key: K, map: Map) => boolean} doesMatch - A predicate function that tests each entry. +* @returns {boolean} true if all entries satisfy the predicate, false otherwise. +* +* @example +* const map = new Map([ +* ['a', 10], +* ['b', 20], +* ['c', 30] +* ]); +* const result = every(map, (value) => value > 5); +* // result will be: true +* +* const result2 = every(map, (value) => value > 15); +* // result2 will be: false +*/ +function every(map, doesMatch) { + for (const [key, value] of map) if (!doesMatch(value, key, map)) return false; + return true; +} +//#endregion +exports.every = every; diff --git a/tools/ui/node_modules/es-toolkit/dist/map/every.mjs b/tools/ui/node_modules/es-toolkit/dist/map/every.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0381f97d4adc5afa84c07b041c905ed86ebad4a3 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/every.mjs @@ -0,0 +1,32 @@ +//#region src/map/every.ts +/** +* Tests whether all entries in a Map satisfy the provided predicate function. +* +* This function iterates through all entries of the Map and checks if the predicate function +* returns true for every entry. It returns true if the predicate is satisfied for all entries, +* and false otherwise. +* +* @template K - The type of keys in the Map. +* @template V - The type of values in the Map. +* @param {Map} map - The Map to test. +* @param {(value: V, key: K, map: Map) => boolean} doesMatch - A predicate function that tests each entry. +* @returns {boolean} true if all entries satisfy the predicate, false otherwise. +* +* @example +* const map = new Map([ +* ['a', 10], +* ['b', 20], +* ['c', 30] +* ]); +* const result = every(map, (value) => value > 5); +* // result will be: true +* +* const result2 = every(map, (value) => value > 15); +* // result2 will be: false +*/ +function every(map, doesMatch) { + for (const [key, value] of map) if (!doesMatch(value, key, map)) return false; + return true; +} +//#endregion +export { every }; diff --git a/tools/ui/node_modules/es-toolkit/dist/map/filter.d.mts b/tools/ui/node_modules/es-toolkit/dist/map/filter.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..fb955795ef3642a2ea404f1aff12b723dd13746e --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/filter.d.mts @@ -0,0 +1,30 @@ +//#region src/map/filter.d.ts +/** + * Filters a Map based on a predicate function. + * + * This function takes a Map and a predicate function, and returns a new Map containing + * only the entries for which the predicate function returns true. + * + * @template K - The type of keys in the Map. + * @template V - The type of values in the Map. + * @param {Map} map - The Map to filter. + * @param {(value: V, key: K, map: Map) => boolean} callback - A predicate function that tests each entry. + * @returns {Map} A new Map containing only the entries that satisfy the predicate. + * + * @example + * const map = new Map([ + * ['a', 1], + * ['b', 2], + * ['c', 3], + * ['d', 4] + * ]); + * const result = filter(map, (value) => value > 2); + * // result will be: + * // Map(2) { + * // 'c' => 3, + * // 'd' => 4 + * // } + */ +declare function filter(map: Map, callback: (value: V, key: K, map: Map) => boolean): Map; +//#endregion +export { filter }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/map/filter.d.ts b/tools/ui/node_modules/es-toolkit/dist/map/filter.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fb955795ef3642a2ea404f1aff12b723dd13746e --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/filter.d.ts @@ -0,0 +1,30 @@ +//#region src/map/filter.d.ts +/** + * Filters a Map based on a predicate function. + * + * This function takes a Map and a predicate function, and returns a new Map containing + * only the entries for which the predicate function returns true. + * + * @template K - The type of keys in the Map. + * @template V - The type of values in the Map. + * @param {Map} map - The Map to filter. + * @param {(value: V, key: K, map: Map) => boolean} callback - A predicate function that tests each entry. + * @returns {Map} A new Map containing only the entries that satisfy the predicate. + * + * @example + * const map = new Map([ + * ['a', 1], + * ['b', 2], + * ['c', 3], + * ['d', 4] + * ]); + * const result = filter(map, (value) => value > 2); + * // result will be: + * // Map(2) { + * // 'c' => 3, + * // 'd' => 4 + * // } + */ +declare function filter(map: Map, callback: (value: V, key: K, map: Map) => boolean): Map; +//#endregion +export { filter }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/map/filter.js b/tools/ui/node_modules/es-toolkit/dist/map/filter.js new file mode 100644 index 0000000000000000000000000000000000000000..fcead0337be83c7c9542147d2df9c4ba2c28433e --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/filter.js @@ -0,0 +1,34 @@ +//#region src/map/filter.ts +/** +* Filters a Map based on a predicate function. +* +* This function takes a Map and a predicate function, and returns a new Map containing +* only the entries for which the predicate function returns true. +* +* @template K - The type of keys in the Map. +* @template V - The type of values in the Map. +* @param {Map} map - The Map to filter. +* @param {(value: V, key: K, map: Map) => boolean} callback - A predicate function that tests each entry. +* @returns {Map} A new Map containing only the entries that satisfy the predicate. +* +* @example +* const map = new Map([ +* ['a', 1], +* ['b', 2], +* ['c', 3], +* ['d', 4] +* ]); +* const result = filter(map, (value) => value > 2); +* // result will be: +* // Map(2) { +* // 'c' => 3, +* // 'd' => 4 +* // } +*/ +function filter(map, callback) { + const result = /* @__PURE__ */ new Map(); + for (const [key, value] of map) if (callback(value, key, map)) result.set(key, value); + return result; +} +//#endregion +exports.filter = filter; diff --git a/tools/ui/node_modules/es-toolkit/dist/map/filter.mjs b/tools/ui/node_modules/es-toolkit/dist/map/filter.mjs new file mode 100644 index 0000000000000000000000000000000000000000..aac4d6664a7428fa33dc1b5a6d1668e03911d2a9 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/filter.mjs @@ -0,0 +1,34 @@ +//#region src/map/filter.ts +/** +* Filters a Map based on a predicate function. +* +* This function takes a Map and a predicate function, and returns a new Map containing +* only the entries for which the predicate function returns true. +* +* @template K - The type of keys in the Map. +* @template V - The type of values in the Map. +* @param {Map} map - The Map to filter. +* @param {(value: V, key: K, map: Map) => boolean} callback - A predicate function that tests each entry. +* @returns {Map} A new Map containing only the entries that satisfy the predicate. +* +* @example +* const map = new Map([ +* ['a', 1], +* ['b', 2], +* ['c', 3], +* ['d', 4] +* ]); +* const result = filter(map, (value) => value > 2); +* // result will be: +* // Map(2) { +* // 'c' => 3, +* // 'd' => 4 +* // } +*/ +function filter(map, callback) { + const result = /* @__PURE__ */ new Map(); + for (const [key, value] of map) if (callback(value, key, map)) result.set(key, value); + return result; +} +//#endregion +export { filter }; diff --git a/tools/ui/node_modules/es-toolkit/dist/map/findKey.d.mts b/tools/ui/node_modules/es-toolkit/dist/map/findKey.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..cca04dd68c73b3029b496167ca43bff6f1578881 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/findKey.d.mts @@ -0,0 +1,26 @@ +//#region src/map/findKey.d.ts +/** + * Finds the first key in a Map for which the predicate function returns true. + * + * This function iterates through the entries of the Map and returns the key of the first + * entry for which the predicate function returns true. If no entry satisfies the predicate, + * it returns undefined. + * + * @template K - The type of keys in the Map. + * @template V - The type of values in the Map. + * @param {Map} map - The Map to search. + * @param {(value: V, key: K, map: Map) => boolean} doesMatch - A predicate function that tests each entry. + * @returns {K | undefined} The key of the first entry that satisfies the predicate, or undefined if none found. + * + * @example + * const map = new Map([ + * ['apple', { color: 'red', quantity: 10 }], + * ['banana', { color: 'yellow', quantity: 5 }], + * ['grape', { color: 'purple', quantity: 15 }] + * ]); + * const result = findKey(map, (value) => value.quantity > 10); + * // result will be: 'grape' + */ +declare function findKey(map: Map, doesMatch: (value: V, key: K, map: Map) => boolean): K | undefined; +//#endregion +export { findKey }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/map/findKey.d.ts b/tools/ui/node_modules/es-toolkit/dist/map/findKey.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cca04dd68c73b3029b496167ca43bff6f1578881 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/findKey.d.ts @@ -0,0 +1,26 @@ +//#region src/map/findKey.d.ts +/** + * Finds the first key in a Map for which the predicate function returns true. + * + * This function iterates through the entries of the Map and returns the key of the first + * entry for which the predicate function returns true. If no entry satisfies the predicate, + * it returns undefined. + * + * @template K - The type of keys in the Map. + * @template V - The type of values in the Map. + * @param {Map} map - The Map to search. + * @param {(value: V, key: K, map: Map) => boolean} doesMatch - A predicate function that tests each entry. + * @returns {K | undefined} The key of the first entry that satisfies the predicate, or undefined if none found. + * + * @example + * const map = new Map([ + * ['apple', { color: 'red', quantity: 10 }], + * ['banana', { color: 'yellow', quantity: 5 }], + * ['grape', { color: 'purple', quantity: 15 }] + * ]); + * const result = findKey(map, (value) => value.quantity > 10); + * // result will be: 'grape' + */ +declare function findKey(map: Map, doesMatch: (value: V, key: K, map: Map) => boolean): K | undefined; +//#endregion +export { findKey }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/map/findKey.js b/tools/ui/node_modules/es-toolkit/dist/map/findKey.js new file mode 100644 index 0000000000000000000000000000000000000000..4ae79a33ebb0f1f27e9a1d1beade00cd07a874bd --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/findKey.js @@ -0,0 +1,33 @@ +//#region src/map/findKey.ts +/** +* Finds the first key in a Map for which the predicate function returns true. +* +* This function iterates through the entries of the Map and returns the key of the first +* entry for which the predicate function returns true. If no entry satisfies the predicate, +* it returns undefined. +* +* @template K - The type of keys in the Map. +* @template V - The type of values in the Map. +* @param {Map} map - The Map to search. +* @param {(value: V, key: K, map: Map) => boolean} doesMatch - A predicate function that tests each entry. +* @returns {K | undefined} The key of the first entry that satisfies the predicate, or undefined if none found. +* +* @example +* const map = new Map([ +* ['apple', { color: 'red', quantity: 10 }], +* ['banana', { color: 'yellow', quantity: 5 }], +* ['grape', { color: 'purple', quantity: 15 }] +* ]); +* const result = findKey(map, (value) => value.quantity > 10); +* // result will be: 'grape' +*/ +function findKey(map, doesMatch) { + let result = void 0; + for (const [key, value] of map) if (doesMatch(value, key, map)) { + result = key; + break; + } + return result; +} +//#endregion +exports.findKey = findKey; diff --git a/tools/ui/node_modules/es-toolkit/dist/map/findKey.mjs b/tools/ui/node_modules/es-toolkit/dist/map/findKey.mjs new file mode 100644 index 0000000000000000000000000000000000000000..55e9a2fd30627cdc303ca17c6b93f29ac69c20da --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/findKey.mjs @@ -0,0 +1,33 @@ +//#region src/map/findKey.ts +/** +* Finds the first key in a Map for which the predicate function returns true. +* +* This function iterates through the entries of the Map and returns the key of the first +* entry for which the predicate function returns true. If no entry satisfies the predicate, +* it returns undefined. +* +* @template K - The type of keys in the Map. +* @template V - The type of values in the Map. +* @param {Map} map - The Map to search. +* @param {(value: V, key: K, map: Map) => boolean} doesMatch - A predicate function that tests each entry. +* @returns {K | undefined} The key of the first entry that satisfies the predicate, or undefined if none found. +* +* @example +* const map = new Map([ +* ['apple', { color: 'red', quantity: 10 }], +* ['banana', { color: 'yellow', quantity: 5 }], +* ['grape', { color: 'purple', quantity: 15 }] +* ]); +* const result = findKey(map, (value) => value.quantity > 10); +* // result will be: 'grape' +*/ +function findKey(map, doesMatch) { + let result = void 0; + for (const [key, value] of map) if (doesMatch(value, key, map)) { + result = key; + break; + } + return result; +} +//#endregion +export { findKey }; diff --git a/tools/ui/node_modules/es-toolkit/dist/map/findValue.d.mts b/tools/ui/node_modules/es-toolkit/dist/map/findValue.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..877d65604ef1753e2239ccc18e993bfc3dda1192 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/findValue.d.mts @@ -0,0 +1,26 @@ +//#region src/map/findValue.d.ts +/** + * Finds the first value in a Map for which the predicate function returns true. + * + * This function iterates through the entries of the Map and returns the value of the first + * entry for which the predicate function returns true. If no entry satisfies the predicate, + * it returns undefined. + * + * @template K - The type of keys in the Map. + * @template V - The type of values in the Map. + * @param {Map} map - The Map to search. + * @param {(value: V, key: K, map: Map) => boolean} doesMatch - A predicate function that tests each entry. + * @returns {V | undefined} The value of the first entry that satisfies the predicate, or undefined if none found. + * + * @example + * const map = new Map([ + * ['apple', { color: 'red', quantity: 10 }], + * ['banana', { color: 'yellow', quantity: 5 }], + * ['grape', { color: 'purple', quantity: 15 }] + * ]); + * const result = findValue(map, (value) => value.quantity > 10); + * // result will be: { color: 'purple', quantity: 15 } + */ +declare function findValue(map: Map, doesMatch: (value: V, key: K, map: Map) => boolean): V | undefined; +//#endregion +export { findValue }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/map/findValue.d.ts b/tools/ui/node_modules/es-toolkit/dist/map/findValue.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..877d65604ef1753e2239ccc18e993bfc3dda1192 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/findValue.d.ts @@ -0,0 +1,26 @@ +//#region src/map/findValue.d.ts +/** + * Finds the first value in a Map for which the predicate function returns true. + * + * This function iterates through the entries of the Map and returns the value of the first + * entry for which the predicate function returns true. If no entry satisfies the predicate, + * it returns undefined. + * + * @template K - The type of keys in the Map. + * @template V - The type of values in the Map. + * @param {Map} map - The Map to search. + * @param {(value: V, key: K, map: Map) => boolean} doesMatch - A predicate function that tests each entry. + * @returns {V | undefined} The value of the first entry that satisfies the predicate, or undefined if none found. + * + * @example + * const map = new Map([ + * ['apple', { color: 'red', quantity: 10 }], + * ['banana', { color: 'yellow', quantity: 5 }], + * ['grape', { color: 'purple', quantity: 15 }] + * ]); + * const result = findValue(map, (value) => value.quantity > 10); + * // result will be: { color: 'purple', quantity: 15 } + */ +declare function findValue(map: Map, doesMatch: (value: V, key: K, map: Map) => boolean): V | undefined; +//#endregion +export { findValue }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/map/findValue.js b/tools/ui/node_modules/es-toolkit/dist/map/findValue.js new file mode 100644 index 0000000000000000000000000000000000000000..2148b41a20da2d142670393425826888d0ad2136 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/findValue.js @@ -0,0 +1,33 @@ +//#region src/map/findValue.ts +/** +* Finds the first value in a Map for which the predicate function returns true. +* +* This function iterates through the entries of the Map and returns the value of the first +* entry for which the predicate function returns true. If no entry satisfies the predicate, +* it returns undefined. +* +* @template K - The type of keys in the Map. +* @template V - The type of values in the Map. +* @param {Map} map - The Map to search. +* @param {(value: V, key: K, map: Map) => boolean} doesMatch - A predicate function that tests each entry. +* @returns {V | undefined} The value of the first entry that satisfies the predicate, or undefined if none found. +* +* @example +* const map = new Map([ +* ['apple', { color: 'red', quantity: 10 }], +* ['banana', { color: 'yellow', quantity: 5 }], +* ['grape', { color: 'purple', quantity: 15 }] +* ]); +* const result = findValue(map, (value) => value.quantity > 10); +* // result will be: { color: 'purple', quantity: 15 } +*/ +function findValue(map, doesMatch) { + let result = void 0; + for (const [key, value] of map) if (doesMatch(value, key, map)) { + result = value; + break; + } + return result; +} +//#endregion +exports.findValue = findValue; diff --git a/tools/ui/node_modules/es-toolkit/dist/map/findValue.mjs b/tools/ui/node_modules/es-toolkit/dist/map/findValue.mjs new file mode 100644 index 0000000000000000000000000000000000000000..621ff0ef4bd7b2a5688b419267fcb0a073c35094 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/findValue.mjs @@ -0,0 +1,33 @@ +//#region src/map/findValue.ts +/** +* Finds the first value in a Map for which the predicate function returns true. +* +* This function iterates through the entries of the Map and returns the value of the first +* entry for which the predicate function returns true. If no entry satisfies the predicate, +* it returns undefined. +* +* @template K - The type of keys in the Map. +* @template V - The type of values in the Map. +* @param {Map} map - The Map to search. +* @param {(value: V, key: K, map: Map) => boolean} doesMatch - A predicate function that tests each entry. +* @returns {V | undefined} The value of the first entry that satisfies the predicate, or undefined if none found. +* +* @example +* const map = new Map([ +* ['apple', { color: 'red', quantity: 10 }], +* ['banana', { color: 'yellow', quantity: 5 }], +* ['grape', { color: 'purple', quantity: 15 }] +* ]); +* const result = findValue(map, (value) => value.quantity > 10); +* // result will be: { color: 'purple', quantity: 15 } +*/ +function findValue(map, doesMatch) { + let result = void 0; + for (const [key, value] of map) if (doesMatch(value, key, map)) { + result = value; + break; + } + return result; +} +//#endregion +export { findValue }; diff --git a/tools/ui/node_modules/es-toolkit/dist/map/forEach.d.mts b/tools/ui/node_modules/es-toolkit/dist/map/forEach.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..8dd4f8547ce034917e21658ebaa6506766c32b60 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/forEach.d.mts @@ -0,0 +1,30 @@ +//#region src/map/forEach.d.ts +/** + * Executes a provided function once for each entry in a Map. + * + * This function iterates through all entries of the Map and executes the callback function + * for each entry. The callback receives the value, key, and the Map itself as arguments. + * + * @template K - The type of keys in the Map. + * @template V - The type of values in the Map. + * @param {Map} map - The Map to iterate over. + * @param {(value: V, key: K, map: Map) => void} callback - A function to execute for each entry. + * @returns {void} + * + * @example + * const map = new Map([ + * ['a', 1], + * ['b', 2], + * ['c', 3] + * ]); + * forEach(map, (value, key) => { + * console.log(`${key}: ${value}`); + * }); + * // Output: + * // a: 1 + * // b: 2 + * // c: 3 + */ +declare function forEach(map: Map, callback: (value: V, key: K, map: Map) => void): void; +//#endregion +export { forEach }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/map/forEach.d.ts b/tools/ui/node_modules/es-toolkit/dist/map/forEach.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8dd4f8547ce034917e21658ebaa6506766c32b60 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/forEach.d.ts @@ -0,0 +1,30 @@ +//#region src/map/forEach.d.ts +/** + * Executes a provided function once for each entry in a Map. + * + * This function iterates through all entries of the Map and executes the callback function + * for each entry. The callback receives the value, key, and the Map itself as arguments. + * + * @template K - The type of keys in the Map. + * @template V - The type of values in the Map. + * @param {Map} map - The Map to iterate over. + * @param {(value: V, key: K, map: Map) => void} callback - A function to execute for each entry. + * @returns {void} + * + * @example + * const map = new Map([ + * ['a', 1], + * ['b', 2], + * ['c', 3] + * ]); + * forEach(map, (value, key) => { + * console.log(`${key}: ${value}`); + * }); + * // Output: + * // a: 1 + * // b: 2 + * // c: 3 + */ +declare function forEach(map: Map, callback: (value: V, key: K, map: Map) => void): void; +//#endregion +export { forEach }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/map/forEach.js b/tools/ui/node_modules/es-toolkit/dist/map/forEach.js new file mode 100644 index 0000000000000000000000000000000000000000..db2c18b784e16463147376d5bf106c975eed9b15 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/forEach.js @@ -0,0 +1,32 @@ +//#region src/map/forEach.ts +/** +* Executes a provided function once for each entry in a Map. +* +* This function iterates through all entries of the Map and executes the callback function +* for each entry. The callback receives the value, key, and the Map itself as arguments. +* +* @template K - The type of keys in the Map. +* @template V - The type of values in the Map. +* @param {Map} map - The Map to iterate over. +* @param {(value: V, key: K, map: Map) => void} callback - A function to execute for each entry. +* @returns {void} +* +* @example +* const map = new Map([ +* ['a', 1], +* ['b', 2], +* ['c', 3] +* ]); +* forEach(map, (value, key) => { +* console.log(`${key}: ${value}`); +* }); +* // Output: +* // a: 1 +* // b: 2 +* // c: 3 +*/ +function forEach(map, callback) { + for (const [key, value] of map) callback(value, key, map); +} +//#endregion +exports.forEach = forEach; diff --git a/tools/ui/node_modules/es-toolkit/dist/map/forEach.mjs b/tools/ui/node_modules/es-toolkit/dist/map/forEach.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0f5d883ea21d2a0d5a83f4dd11421f7400b6bfb5 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/forEach.mjs @@ -0,0 +1,32 @@ +//#region src/map/forEach.ts +/** +* Executes a provided function once for each entry in a Map. +* +* This function iterates through all entries of the Map and executes the callback function +* for each entry. The callback receives the value, key, and the Map itself as arguments. +* +* @template K - The type of keys in the Map. +* @template V - The type of values in the Map. +* @param {Map} map - The Map to iterate over. +* @param {(value: V, key: K, map: Map) => void} callback - A function to execute for each entry. +* @returns {void} +* +* @example +* const map = new Map([ +* ['a', 1], +* ['b', 2], +* ['c', 3] +* ]); +* forEach(map, (value, key) => { +* console.log(`${key}: ${value}`); +* }); +* // Output: +* // a: 1 +* // b: 2 +* // c: 3 +*/ +function forEach(map, callback) { + for (const [key, value] of map) callback(value, key, map); +} +//#endregion +export { forEach }; diff --git a/tools/ui/node_modules/es-toolkit/dist/map/hasValue.d.mts b/tools/ui/node_modules/es-toolkit/dist/map/hasValue.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..36bfd0bf62c69bea888726e891ed5163a60eb0ad --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/hasValue.d.mts @@ -0,0 +1,29 @@ +//#region src/map/hasValue.d.ts +/** + * Checks if a Map contains a specific value. + * + * This function iterates through all values in the Map and checks if any value + * is equal to the search element using SameValueZero comparison (similar to + * Array.prototype.includes). This means that NaN is considered equal to NaN. + * + * @template K - The type of keys in the Map. + * @template V - The type of values in the Map. + * @param {Map} map - The Map to search. + * @param {V} searchElement - The value to search for. + * @returns {boolean} true if the Map contains the value, false otherwise. + * + * @example + * const map = new Map([ + * ['a', 1], + * ['b', 2], + * ['c', 3] + * ]); + * const result = hasValue(map, 2); + * // result will be: true + * + * const result2 = hasValue(map, 5); + * // result2 will be: false + */ +declare function hasValue(map: Map, searchElement: V): boolean; +//#endregion +export { hasValue }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/map/hasValue.d.ts b/tools/ui/node_modules/es-toolkit/dist/map/hasValue.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..36bfd0bf62c69bea888726e891ed5163a60eb0ad --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/hasValue.d.ts @@ -0,0 +1,29 @@ +//#region src/map/hasValue.d.ts +/** + * Checks if a Map contains a specific value. + * + * This function iterates through all values in the Map and checks if any value + * is equal to the search element using SameValueZero comparison (similar to + * Array.prototype.includes). This means that NaN is considered equal to NaN. + * + * @template K - The type of keys in the Map. + * @template V - The type of values in the Map. + * @param {Map} map - The Map to search. + * @param {V} searchElement - The value to search for. + * @returns {boolean} true if the Map contains the value, false otherwise. + * + * @example + * const map = new Map([ + * ['a', 1], + * ['b', 2], + * ['c', 3] + * ]); + * const result = hasValue(map, 2); + * // result will be: true + * + * const result2 = hasValue(map, 5); + * // result2 will be: false + */ +declare function hasValue(map: Map, searchElement: V): boolean; +//#endregion +export { hasValue }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/map/hasValue.js b/tools/ui/node_modules/es-toolkit/dist/map/hasValue.js new file mode 100644 index 0000000000000000000000000000000000000000..763e85a96c4892665034c94988d71a4e258f45c0 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/hasValue.js @@ -0,0 +1,33 @@ +const require_isEqualsSameValueZero = require("../_internal/isEqualsSameValueZero.js"); +//#region src/map/hasValue.ts +/** +* Checks if a Map contains a specific value. +* +* This function iterates through all values in the Map and checks if any value +* is equal to the search element using SameValueZero comparison (similar to +* Array.prototype.includes). This means that NaN is considered equal to NaN. +* +* @template K - The type of keys in the Map. +* @template V - The type of values in the Map. +* @param {Map} map - The Map to search. +* @param {V} searchElement - The value to search for. +* @returns {boolean} true if the Map contains the value, false otherwise. +* +* @example +* const map = new Map([ +* ['a', 1], +* ['b', 2], +* ['c', 3] +* ]); +* const result = hasValue(map, 2); +* // result will be: true +* +* const result2 = hasValue(map, 5); +* // result2 will be: false +*/ +function hasValue(map, searchElement) { + for (const value of map.values()) if (require_isEqualsSameValueZero.isEqualsSameValueZero(value, searchElement)) return true; + return false; +} +//#endregion +exports.hasValue = hasValue; diff --git a/tools/ui/node_modules/es-toolkit/dist/map/hasValue.mjs b/tools/ui/node_modules/es-toolkit/dist/map/hasValue.mjs new file mode 100644 index 0000000000000000000000000000000000000000..985d640f05005b8203f7372da3b8690208fd883a --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/hasValue.mjs @@ -0,0 +1,33 @@ +import { isEqualsSameValueZero } from "../_internal/isEqualsSameValueZero.mjs"; +//#region src/map/hasValue.ts +/** +* Checks if a Map contains a specific value. +* +* This function iterates through all values in the Map and checks if any value +* is equal to the search element using SameValueZero comparison (similar to +* Array.prototype.includes). This means that NaN is considered equal to NaN. +* +* @template K - The type of keys in the Map. +* @template V - The type of values in the Map. +* @param {Map} map - The Map to search. +* @param {V} searchElement - The value to search for. +* @returns {boolean} true if the Map contains the value, false otherwise. +* +* @example +* const map = new Map([ +* ['a', 1], +* ['b', 2], +* ['c', 3] +* ]); +* const result = hasValue(map, 2); +* // result will be: true +* +* const result2 = hasValue(map, 5); +* // result2 will be: false +*/ +function hasValue(map, searchElement) { + for (const value of map.values()) if (isEqualsSameValueZero(value, searchElement)) return true; + return false; +} +//#endregion +export { hasValue }; diff --git a/tools/ui/node_modules/es-toolkit/dist/map/index.d.mts b/tools/ui/node_modules/es-toolkit/dist/map/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..b37e33bcceb7dca49c81b8d2c73dda8767d6ceab --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/index.d.mts @@ -0,0 +1,13 @@ +import { countBy } from "./countBy.mjs"; +import { every } from "./every.mjs"; +import { filter } from "./filter.mjs"; +import { findKey } from "./findKey.mjs"; +import { findValue } from "./findValue.mjs"; +import { forEach } from "./forEach.mjs"; +import { hasValue } from "./hasValue.mjs"; +import { keyBy } from "./keyBy.mjs"; +import { mapKeys } from "./mapKeys.mjs"; +import { mapValues } from "./mapValues.mjs"; +import { reduce } from "./reduce.mjs"; +import { some } from "./some.mjs"; +export { countBy, every, filter, findKey, findValue, forEach, hasValue, keyBy, mapKeys, mapValues, reduce, some }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/map/index.d.ts b/tools/ui/node_modules/es-toolkit/dist/map/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..34df790462ce93454d0146961c70864489fbaf73 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/index.d.ts @@ -0,0 +1,13 @@ +import { countBy } from "./countBy.js"; +import { every } from "./every.js"; +import { filter } from "./filter.js"; +import { findKey } from "./findKey.js"; +import { findValue } from "./findValue.js"; +import { forEach } from "./forEach.js"; +import { hasValue } from "./hasValue.js"; +import { keyBy } from "./keyBy.js"; +import { mapKeys } from "./mapKeys.js"; +import { mapValues } from "./mapValues.js"; +import { reduce } from "./reduce.js"; +import { some } from "./some.js"; +export { countBy, every, filter, findKey, findValue, forEach, hasValue, keyBy, mapKeys, mapValues, reduce, some }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/map/index.js b/tools/ui/node_modules/es-toolkit/dist/map/index.js new file mode 100644 index 0000000000000000000000000000000000000000..28139c8b840765076fb06d81836c791222b72d7e --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/index.js @@ -0,0 +1,25 @@ +Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); +const require_countBy = require("./countBy.js"); +const require_every = require("./every.js"); +const require_filter = require("./filter.js"); +const require_findKey = require("./findKey.js"); +const require_findValue = require("./findValue.js"); +const require_forEach = require("./forEach.js"); +const require_hasValue = require("./hasValue.js"); +const require_keyBy = require("./keyBy.js"); +const require_mapKeys = require("./mapKeys.js"); +const require_mapValues = require("./mapValues.js"); +const require_reduce = require("./reduce.js"); +const require_some = require("./some.js"); +exports.countBy = require_countBy.countBy; +exports.every = require_every.every; +exports.filter = require_filter.filter; +exports.findKey = require_findKey.findKey; +exports.findValue = require_findValue.findValue; +exports.forEach = require_forEach.forEach; +exports.hasValue = require_hasValue.hasValue; +exports.keyBy = require_keyBy.keyBy; +exports.mapKeys = require_mapKeys.mapKeys; +exports.mapValues = require_mapValues.mapValues; +exports.reduce = require_reduce.reduce; +exports.some = require_some.some; diff --git a/tools/ui/node_modules/es-toolkit/dist/map/index.mjs b/tools/ui/node_modules/es-toolkit/dist/map/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..354c85c635203b1498d0442471dacd2a8cde7ff6 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/index.mjs @@ -0,0 +1,13 @@ +import { countBy } from "./countBy.mjs"; +import { every } from "./every.mjs"; +import { filter } from "./filter.mjs"; +import { findKey } from "./findKey.mjs"; +import { findValue } from "./findValue.mjs"; +import { forEach } from "./forEach.mjs"; +import { hasValue } from "./hasValue.mjs"; +import { keyBy } from "./keyBy.mjs"; +import { mapKeys } from "./mapKeys.mjs"; +import { mapValues } from "./mapValues.mjs"; +import { reduce } from "./reduce.mjs"; +import { some } from "./some.mjs"; +export { countBy, every, filter, findKey, findValue, forEach, hasValue, keyBy, mapKeys, mapValues, reduce, some }; diff --git a/tools/ui/node_modules/es-toolkit/dist/map/keyBy.d.mts b/tools/ui/node_modules/es-toolkit/dist/map/keyBy.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..8dfb719d76f0fcf67d2c4151b55e931066477edb --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/keyBy.d.mts @@ -0,0 +1,32 @@ +//#region src/map/keyBy.d.ts +/** + * Maps each entry of a Map based on a provided key-generating function. + * + * This function takes a Map and a function that generates a key from each value-key pair. + * It returns a new Map where the keys are generated by the key function and the values are + * the corresponding values from the original map. If multiple entries produce the same key, + * the last value encountered will be used. + * + * @template K - The type of keys in the original Map. + * @template V - The type of values in the original Map. + * @template K2 - The type of keys to produce in the returned Map. + * @param {Map} map - The map of entries to be mapped. + * @param {(value: V, key: K, object: Map) => K2} getKeyFromEntry - A function that generates a key from a value-key pair. + * @returns {Map} A Map where the generated keys are mapped to each entry's value. + * + * @example + * const map = new Map([ + * ['x', { type: 'fruit', name: 'apple' }], + * ['y', { type: 'fruit', name: 'banana' }], + * ['z', { type: 'vegetable', name: 'carrot' }] + * ]); + * const result = keyBy(map, item => item.type); + * // result will be: + * // Map(2) { + * // 'fruit' => { type: 'fruit', name: 'banana' }, + * // 'vegetable' => { type: 'vegetable', name: 'carrot' } + * // } + */ +declare function keyBy(map: Map, getKeyFromEntry: (value: V, key: K, object: Map) => K2): Map; +//#endregion +export { keyBy }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/map/keyBy.d.ts b/tools/ui/node_modules/es-toolkit/dist/map/keyBy.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8dfb719d76f0fcf67d2c4151b55e931066477edb --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/keyBy.d.ts @@ -0,0 +1,32 @@ +//#region src/map/keyBy.d.ts +/** + * Maps each entry of a Map based on a provided key-generating function. + * + * This function takes a Map and a function that generates a key from each value-key pair. + * It returns a new Map where the keys are generated by the key function and the values are + * the corresponding values from the original map. If multiple entries produce the same key, + * the last value encountered will be used. + * + * @template K - The type of keys in the original Map. + * @template V - The type of values in the original Map. + * @template K2 - The type of keys to produce in the returned Map. + * @param {Map} map - The map of entries to be mapped. + * @param {(value: V, key: K, object: Map) => K2} getKeyFromEntry - A function that generates a key from a value-key pair. + * @returns {Map} A Map where the generated keys are mapped to each entry's value. + * + * @example + * const map = new Map([ + * ['x', { type: 'fruit', name: 'apple' }], + * ['y', { type: 'fruit', name: 'banana' }], + * ['z', { type: 'vegetable', name: 'carrot' }] + * ]); + * const result = keyBy(map, item => item.type); + * // result will be: + * // Map(2) { + * // 'fruit' => { type: 'fruit', name: 'banana' }, + * // 'vegetable' => { type: 'vegetable', name: 'carrot' } + * // } + */ +declare function keyBy(map: Map, getKeyFromEntry: (value: V, key: K, object: Map) => K2): Map; +//#endregion +export { keyBy }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/map/keyBy.js b/tools/ui/node_modules/es-toolkit/dist/map/keyBy.js new file mode 100644 index 0000000000000000000000000000000000000000..ba7a70280f51c0ce7376a5c34655a204347ed6cf --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/keyBy.js @@ -0,0 +1,39 @@ +//#region src/map/keyBy.ts +/** +* Maps each entry of a Map based on a provided key-generating function. +* +* This function takes a Map and a function that generates a key from each value-key pair. +* It returns a new Map where the keys are generated by the key function and the values are +* the corresponding values from the original map. If multiple entries produce the same key, +* the last value encountered will be used. +* +* @template K - The type of keys in the original Map. +* @template V - The type of values in the original Map. +* @template K2 - The type of keys to produce in the returned Map. +* @param {Map} map - The map of entries to be mapped. +* @param {(value: V, key: K, object: Map) => K2} getKeyFromEntry - A function that generates a key from a value-key pair. +* @returns {Map} A Map where the generated keys are mapped to each entry's value. +* +* @example +* const map = new Map([ +* ['x', { type: 'fruit', name: 'apple' }], +* ['y', { type: 'fruit', name: 'banana' }], +* ['z', { type: 'vegetable', name: 'carrot' }] +* ]); +* const result = keyBy(map, item => item.type); +* // result will be: +* // Map(2) { +* // 'fruit' => { type: 'fruit', name: 'banana' }, +* // 'vegetable' => { type: 'vegetable', name: 'carrot' } +* // } +*/ +function keyBy(map, getKeyFromEntry) { + const result = /* @__PURE__ */ new Map(); + for (const [key, value] of map) { + const newKey = getKeyFromEntry(value, key, map); + result.set(newKey, value); + } + return result; +} +//#endregion +exports.keyBy = keyBy; diff --git a/tools/ui/node_modules/es-toolkit/dist/map/keyBy.mjs b/tools/ui/node_modules/es-toolkit/dist/map/keyBy.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ead95782e579d1617d1ef02397f084c3e1f107da --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/keyBy.mjs @@ -0,0 +1,39 @@ +//#region src/map/keyBy.ts +/** +* Maps each entry of a Map based on a provided key-generating function. +* +* This function takes a Map and a function that generates a key from each value-key pair. +* It returns a new Map where the keys are generated by the key function and the values are +* the corresponding values from the original map. If multiple entries produce the same key, +* the last value encountered will be used. +* +* @template K - The type of keys in the original Map. +* @template V - The type of values in the original Map. +* @template K2 - The type of keys to produce in the returned Map. +* @param {Map} map - The map of entries to be mapped. +* @param {(value: V, key: K, object: Map) => K2} getKeyFromEntry - A function that generates a key from a value-key pair. +* @returns {Map} A Map where the generated keys are mapped to each entry's value. +* +* @example +* const map = new Map([ +* ['x', { type: 'fruit', name: 'apple' }], +* ['y', { type: 'fruit', name: 'banana' }], +* ['z', { type: 'vegetable', name: 'carrot' }] +* ]); +* const result = keyBy(map, item => item.type); +* // result will be: +* // Map(2) { +* // 'fruit' => { type: 'fruit', name: 'banana' }, +* // 'vegetable' => { type: 'vegetable', name: 'carrot' } +* // } +*/ +function keyBy(map, getKeyFromEntry) { + const result = /* @__PURE__ */ new Map(); + for (const [key, value] of map) { + const newKey = getKeyFromEntry(value, key, map); + result.set(newKey, value); + } + return result; +} +//#endregion +export { keyBy }; diff --git a/tools/ui/node_modules/es-toolkit/dist/map/mapKeys.d.mts b/tools/ui/node_modules/es-toolkit/dist/map/mapKeys.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..3f1dd577913c685cc420aabffa5428b073f57917 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/mapKeys.d.mts @@ -0,0 +1,31 @@ +//#region src/map/mapKeys.d.ts +/** + * Creates a new Map with the same values but with keys transformed by the provided function. + * + * This function takes a Map and a function that generates a new key from each value-key pair. + * It returns a new Map where the keys are the result of applying the function to each entry, + * while the values remain the same. + * + * @template K - The type of keys in the Map. + * @template V - The type of values in the Map. + * @param {Map} map - The Map to transform. + * @param {(value: V, key: K, object: Map) => K} getNewKey - A function that generates a new key from a value-key pair. + * @returns {Map} A new Map with transformed keys and the same values. + * + * @example + * const map = new Map([ + * ['a', 1], + * ['b', 2], + * ['c', 3] + * ]); + * const result = mapKeys(map, (value, key) => key.toUpperCase()); + * // result will be: + * // Map(3) { + * // 'A' => 1, + * // 'B' => 2, + * // 'C' => 3 + * // } + */ +declare function mapKeys(map: Map, getNewKey: (value: V, key: K, object: Map) => K): Map; +//#endregion +export { mapKeys }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/map/mapKeys.d.ts b/tools/ui/node_modules/es-toolkit/dist/map/mapKeys.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3f1dd577913c685cc420aabffa5428b073f57917 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/mapKeys.d.ts @@ -0,0 +1,31 @@ +//#region src/map/mapKeys.d.ts +/** + * Creates a new Map with the same values but with keys transformed by the provided function. + * + * This function takes a Map and a function that generates a new key from each value-key pair. + * It returns a new Map where the keys are the result of applying the function to each entry, + * while the values remain the same. + * + * @template K - The type of keys in the Map. + * @template V - The type of values in the Map. + * @param {Map} map - The Map to transform. + * @param {(value: V, key: K, object: Map) => K} getNewKey - A function that generates a new key from a value-key pair. + * @returns {Map} A new Map with transformed keys and the same values. + * + * @example + * const map = new Map([ + * ['a', 1], + * ['b', 2], + * ['c', 3] + * ]); + * const result = mapKeys(map, (value, key) => key.toUpperCase()); + * // result will be: + * // Map(3) { + * // 'A' => 1, + * // 'B' => 2, + * // 'C' => 3 + * // } + */ +declare function mapKeys(map: Map, getNewKey: (value: V, key: K, object: Map) => K): Map; +//#endregion +export { mapKeys }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/map/mapKeys.js b/tools/ui/node_modules/es-toolkit/dist/map/mapKeys.js new file mode 100644 index 0000000000000000000000000000000000000000..1a821b458fc8513d118266991a34a25df19b0d7a --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/mapKeys.js @@ -0,0 +1,38 @@ +//#region src/map/mapKeys.ts +/** +* Creates a new Map with the same values but with keys transformed by the provided function. +* +* This function takes a Map and a function that generates a new key from each value-key pair. +* It returns a new Map where the keys are the result of applying the function to each entry, +* while the values remain the same. +* +* @template K - The type of keys in the Map. +* @template V - The type of values in the Map. +* @param {Map} map - The Map to transform. +* @param {(value: V, key: K, object: Map) => K} getNewKey - A function that generates a new key from a value-key pair. +* @returns {Map} A new Map with transformed keys and the same values. +* +* @example +* const map = new Map([ +* ['a', 1], +* ['b', 2], +* ['c', 3] +* ]); +* const result = mapKeys(map, (value, key) => key.toUpperCase()); +* // result will be: +* // Map(3) { +* // 'A' => 1, +* // 'B' => 2, +* // 'C' => 3 +* // } +*/ +function mapKeys(map, getNewKey) { + const result = /* @__PURE__ */ new Map(); + for (const [key, value] of map) { + const newKey = getNewKey(value, key, map); + result.set(newKey, value); + } + return result; +} +//#endregion +exports.mapKeys = mapKeys; diff --git a/tools/ui/node_modules/es-toolkit/dist/map/mapKeys.mjs b/tools/ui/node_modules/es-toolkit/dist/map/mapKeys.mjs new file mode 100644 index 0000000000000000000000000000000000000000..dc4cfb7fadad92343dbcfb6db6af820de6e54f02 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/mapKeys.mjs @@ -0,0 +1,38 @@ +//#region src/map/mapKeys.ts +/** +* Creates a new Map with the same values but with keys transformed by the provided function. +* +* This function takes a Map and a function that generates a new key from each value-key pair. +* It returns a new Map where the keys are the result of applying the function to each entry, +* while the values remain the same. +* +* @template K - The type of keys in the Map. +* @template V - The type of values in the Map. +* @param {Map} map - The Map to transform. +* @param {(value: V, key: K, object: Map) => K} getNewKey - A function that generates a new key from a value-key pair. +* @returns {Map} A new Map with transformed keys and the same values. +* +* @example +* const map = new Map([ +* ['a', 1], +* ['b', 2], +* ['c', 3] +* ]); +* const result = mapKeys(map, (value, key) => key.toUpperCase()); +* // result will be: +* // Map(3) { +* // 'A' => 1, +* // 'B' => 2, +* // 'C' => 3 +* // } +*/ +function mapKeys(map, getNewKey) { + const result = /* @__PURE__ */ new Map(); + for (const [key, value] of map) { + const newKey = getNewKey(value, key, map); + result.set(newKey, value); + } + return result; +} +//#endregion +export { mapKeys }; diff --git a/tools/ui/node_modules/es-toolkit/dist/map/mapValues.d.mts b/tools/ui/node_modules/es-toolkit/dist/map/mapValues.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..6e4b0235abcad7c44f6dd4af0c2bebffb6445110 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/mapValues.d.mts @@ -0,0 +1,31 @@ +//#region src/map/mapValues.d.ts +/** + * Creates a new Map with the same keys but with values transformed by the provided function. + * + * This function takes a Map and a function that generates a new value from each value-key pair. + * It returns a new Map where the values are the result of applying the function to each entry, + * while the keys remain the same. + * + * @template K - The type of keys in the Map. + * @template V - The type of values in the Map. + * @param {Map} map - The Map to transform. + * @param {(value: V, key: K, object: Map) => V} getNewValue - A function that generates a new value from a value-key pair. + * @returns {Map} A new Map with the same keys and transformed values. + * + * @example + * const map = new Map([ + * ['a', 1], + * ['b', 2], + * ['c', 3] + * ]); + * const result = mapValues(map, (value) => value * 2); + * // result will be: + * // Map(3) { + * // 'a' => 2, + * // 'b' => 4, + * // 'c' => 6 + * // } + */ +declare function mapValues(map: Map, getNewValue: (value: V, key: K, object: Map) => R): Map; +//#endregion +export { mapValues }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/map/mapValues.d.ts b/tools/ui/node_modules/es-toolkit/dist/map/mapValues.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6e4b0235abcad7c44f6dd4af0c2bebffb6445110 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/mapValues.d.ts @@ -0,0 +1,31 @@ +//#region src/map/mapValues.d.ts +/** + * Creates a new Map with the same keys but with values transformed by the provided function. + * + * This function takes a Map and a function that generates a new value from each value-key pair. + * It returns a new Map where the values are the result of applying the function to each entry, + * while the keys remain the same. + * + * @template K - The type of keys in the Map. + * @template V - The type of values in the Map. + * @param {Map} map - The Map to transform. + * @param {(value: V, key: K, object: Map) => V} getNewValue - A function that generates a new value from a value-key pair. + * @returns {Map} A new Map with the same keys and transformed values. + * + * @example + * const map = new Map([ + * ['a', 1], + * ['b', 2], + * ['c', 3] + * ]); + * const result = mapValues(map, (value) => value * 2); + * // result will be: + * // Map(3) { + * // 'a' => 2, + * // 'b' => 4, + * // 'c' => 6 + * // } + */ +declare function mapValues(map: Map, getNewValue: (value: V, key: K, object: Map) => R): Map; +//#endregion +export { mapValues }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/map/mapValues.js b/tools/ui/node_modules/es-toolkit/dist/map/mapValues.js new file mode 100644 index 0000000000000000000000000000000000000000..34bb73cbcddb82bce2790e8c10ccdf9495651c4d --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/mapValues.js @@ -0,0 +1,38 @@ +//#region src/map/mapValues.ts +/** +* Creates a new Map with the same keys but with values transformed by the provided function. +* +* This function takes a Map and a function that generates a new value from each value-key pair. +* It returns a new Map where the values are the result of applying the function to each entry, +* while the keys remain the same. +* +* @template K - The type of keys in the Map. +* @template V - The type of values in the Map. +* @param {Map} map - The Map to transform. +* @param {(value: V, key: K, object: Map) => V} getNewValue - A function that generates a new value from a value-key pair. +* @returns {Map} A new Map with the same keys and transformed values. +* +* @example +* const map = new Map([ +* ['a', 1], +* ['b', 2], +* ['c', 3] +* ]); +* const result = mapValues(map, (value) => value * 2); +* // result will be: +* // Map(3) { +* // 'a' => 2, +* // 'b' => 4, +* // 'c' => 6 +* // } +*/ +function mapValues(map, getNewValue) { + const result = /* @__PURE__ */ new Map(); + for (const [key, value] of map) { + const newValue = getNewValue(value, key, map); + result.set(key, newValue); + } + return result; +} +//#endregion +exports.mapValues = mapValues; diff --git a/tools/ui/node_modules/es-toolkit/dist/map/mapValues.mjs b/tools/ui/node_modules/es-toolkit/dist/map/mapValues.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5f3a34b80a7dafa9a8ff6fcbe41704334ea458c4 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/mapValues.mjs @@ -0,0 +1,38 @@ +//#region src/map/mapValues.ts +/** +* Creates a new Map with the same keys but with values transformed by the provided function. +* +* This function takes a Map and a function that generates a new value from each value-key pair. +* It returns a new Map where the values are the result of applying the function to each entry, +* while the keys remain the same. +* +* @template K - The type of keys in the Map. +* @template V - The type of values in the Map. +* @param {Map} map - The Map to transform. +* @param {(value: V, key: K, object: Map) => V} getNewValue - A function that generates a new value from a value-key pair. +* @returns {Map} A new Map with the same keys and transformed values. +* +* @example +* const map = new Map([ +* ['a', 1], +* ['b', 2], +* ['c', 3] +* ]); +* const result = mapValues(map, (value) => value * 2); +* // result will be: +* // Map(3) { +* // 'a' => 2, +* // 'b' => 4, +* // 'c' => 6 +* // } +*/ +function mapValues(map, getNewValue) { + const result = /* @__PURE__ */ new Map(); + for (const [key, value] of map) { + const newValue = getNewValue(value, key, map); + result.set(key, newValue); + } + return result; +} +//#endregion +export { mapValues }; diff --git a/tools/ui/node_modules/es-toolkit/dist/map/reduce.d.mts b/tools/ui/node_modules/es-toolkit/dist/map/reduce.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..9c74d9b239e795d88ffb2807f8c1292e33f031d3 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/reduce.d.mts @@ -0,0 +1,36 @@ +//#region src/map/reduce.d.ts +/** + * Reduces a Map to a single value by iterating through its entries and applying a callback function. + * + * This function iterates through all entries of the Map and applies the callback function to each entry, + * accumulating the result. If an initial value is provided, it is used as the starting accumulator value. + * If no initial value is provided and the Map is empty, a TypeError is thrown. + * + * @template K - The type of keys in the Map. + * @template V - The type of values in the Map. + * @param {Map} map - The Map to reduce. + * @param {(accumulator: V, value: V, key: K, map: Map) => V} callback - A function that processes each entry and updates the accumulator. + * @param {V} [initialValue] - The initial value for the accumulator. If not provided, the first value in the Map is used. + * @returns {V} The final accumulated value. + * @throws {TypeError} If the Map is empty and no initial value is provided. + * + * @example + * const map = new Map([ + * ['a', 1], + * ['b', 2], + * ['c', 3] + * ]); + * const result = reduce(map, (acc, value) => acc + value, 0); + * // result will be: 6 + * + * @example + * const map = new Map([ + * ['a', 10], + * ['b', 20] + * ]); + * const result = reduce(map, (acc, value) => acc + value); + * // result will be: 30 (starts with first value 10) + */ +declare function reduce(map: Map, callback: (accumulator: A, value: V, key: K, map: Map) => A, initialValue?: A): A; +//#endregion +export { reduce }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/map/reduce.d.ts b/tools/ui/node_modules/es-toolkit/dist/map/reduce.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9c74d9b239e795d88ffb2807f8c1292e33f031d3 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/reduce.d.ts @@ -0,0 +1,36 @@ +//#region src/map/reduce.d.ts +/** + * Reduces a Map to a single value by iterating through its entries and applying a callback function. + * + * This function iterates through all entries of the Map and applies the callback function to each entry, + * accumulating the result. If an initial value is provided, it is used as the starting accumulator value. + * If no initial value is provided and the Map is empty, a TypeError is thrown. + * + * @template K - The type of keys in the Map. + * @template V - The type of values in the Map. + * @param {Map} map - The Map to reduce. + * @param {(accumulator: V, value: V, key: K, map: Map) => V} callback - A function that processes each entry and updates the accumulator. + * @param {V} [initialValue] - The initial value for the accumulator. If not provided, the first value in the Map is used. + * @returns {V} The final accumulated value. + * @throws {TypeError} If the Map is empty and no initial value is provided. + * + * @example + * const map = new Map([ + * ['a', 1], + * ['b', 2], + * ['c', 3] + * ]); + * const result = reduce(map, (acc, value) => acc + value, 0); + * // result will be: 6 + * + * @example + * const map = new Map([ + * ['a', 10], + * ['b', 20] + * ]); + * const result = reduce(map, (acc, value) => acc + value); + * // result will be: 30 (starts with first value 10) + */ +declare function reduce(map: Map, callback: (accumulator: A, value: V, key: K, map: Map) => A, initialValue?: A): A; +//#endregion +export { reduce }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/map/reduce.js b/tools/ui/node_modules/es-toolkit/dist/map/reduce.js new file mode 100644 index 0000000000000000000000000000000000000000..4bcdacd2b7f711fa459cb5ed244da0f54eaa740c --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/reduce.js @@ -0,0 +1,42 @@ +//#region src/map/reduce.ts +/** +* Reduces a Map to a single value by iterating through its entries and applying a callback function. +* +* This function iterates through all entries of the Map and applies the callback function to each entry, +* accumulating the result. If an initial value is provided, it is used as the starting accumulator value. +* If no initial value is provided and the Map is empty, a TypeError is thrown. +* +* @template K - The type of keys in the Map. +* @template V - The type of values in the Map. +* @param {Map} map - The Map to reduce. +* @param {(accumulator: V, value: V, key: K, map: Map) => V} callback - A function that processes each entry and updates the accumulator. +* @param {V} [initialValue] - The initial value for the accumulator. If not provided, the first value in the Map is used. +* @returns {V} The final accumulated value. +* @throws {TypeError} If the Map is empty and no initial value is provided. +* +* @example +* const map = new Map([ +* ['a', 1], +* ['b', 2], +* ['c', 3] +* ]); +* const result = reduce(map, (acc, value) => acc + value, 0); +* // result will be: 6 +* +* @example +* const map = new Map([ +* ['a', 10], +* ['b', 20] +* ]); +* const result = reduce(map, (acc, value) => acc + value); +* // result will be: 30 (starts with first value 10) +*/ +function reduce(map, callback, initialValue) { + if (initialValue == null && map.size === 0) throw new TypeError("Reduce of empty map with no initial value"); + let accumulator = initialValue; + for (const [key, value] of map) if (accumulator == null) accumulator = value; + else accumulator = callback(accumulator, value, key, map); + return accumulator; +} +//#endregion +exports.reduce = reduce; diff --git a/tools/ui/node_modules/es-toolkit/dist/map/reduce.mjs b/tools/ui/node_modules/es-toolkit/dist/map/reduce.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a4ec9fe15db8a0e013614a5f0413594feae8319a --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/reduce.mjs @@ -0,0 +1,42 @@ +//#region src/map/reduce.ts +/** +* Reduces a Map to a single value by iterating through its entries and applying a callback function. +* +* This function iterates through all entries of the Map and applies the callback function to each entry, +* accumulating the result. If an initial value is provided, it is used as the starting accumulator value. +* If no initial value is provided and the Map is empty, a TypeError is thrown. +* +* @template K - The type of keys in the Map. +* @template V - The type of values in the Map. +* @param {Map} map - The Map to reduce. +* @param {(accumulator: V, value: V, key: K, map: Map) => V} callback - A function that processes each entry and updates the accumulator. +* @param {V} [initialValue] - The initial value for the accumulator. If not provided, the first value in the Map is used. +* @returns {V} The final accumulated value. +* @throws {TypeError} If the Map is empty and no initial value is provided. +* +* @example +* const map = new Map([ +* ['a', 1], +* ['b', 2], +* ['c', 3] +* ]); +* const result = reduce(map, (acc, value) => acc + value, 0); +* // result will be: 6 +* +* @example +* const map = new Map([ +* ['a', 10], +* ['b', 20] +* ]); +* const result = reduce(map, (acc, value) => acc + value); +* // result will be: 30 (starts with first value 10) +*/ +function reduce(map, callback, initialValue) { + if (initialValue == null && map.size === 0) throw new TypeError("Reduce of empty map with no initial value"); + let accumulator = initialValue; + for (const [key, value] of map) if (accumulator == null) accumulator = value; + else accumulator = callback(accumulator, value, key, map); + return accumulator; +} +//#endregion +export { reduce }; diff --git a/tools/ui/node_modules/es-toolkit/dist/map/some.d.mts b/tools/ui/node_modules/es-toolkit/dist/map/some.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..e1b32c47db9886d550515f2640b79a81e293ed3a --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/some.d.mts @@ -0,0 +1,29 @@ +//#region src/map/some.d.ts +/** + * Tests whether at least one entry in a Map satisfies the provided predicate function. + * + * This function iterates through the entries of the Map and checks if the predicate function + * returns true for at least one entry. It returns true if any entry satisfies the predicate, + * and false otherwise. + * + * @template K - The type of keys in the Map. + * @template V - The type of values in the Map. + * @param {Map} map - The Map to test. + * @param {(value: V, key: K, map: Map) => boolean} doesMatch - A predicate function that tests each entry. + * @returns {boolean} true if at least one entry satisfies the predicate, false otherwise. + * + * @example + * const map = new Map([ + * ['a', 1], + * ['b', 2], + * ['c', 3] + * ]); + * const result = some(map, (value) => value > 2); + * // result will be: true + * + * const result2 = some(map, (value) => value > 5); + * // result2 will be: false + */ +declare function some(map: Map, doesMatch: (value: V, key: K, map: Map) => boolean): boolean; +//#endregion +export { some }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/map/some.d.ts b/tools/ui/node_modules/es-toolkit/dist/map/some.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e1b32c47db9886d550515f2640b79a81e293ed3a --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/some.d.ts @@ -0,0 +1,29 @@ +//#region src/map/some.d.ts +/** + * Tests whether at least one entry in a Map satisfies the provided predicate function. + * + * This function iterates through the entries of the Map and checks if the predicate function + * returns true for at least one entry. It returns true if any entry satisfies the predicate, + * and false otherwise. + * + * @template K - The type of keys in the Map. + * @template V - The type of values in the Map. + * @param {Map} map - The Map to test. + * @param {(value: V, key: K, map: Map) => boolean} doesMatch - A predicate function that tests each entry. + * @returns {boolean} true if at least one entry satisfies the predicate, false otherwise. + * + * @example + * const map = new Map([ + * ['a', 1], + * ['b', 2], + * ['c', 3] + * ]); + * const result = some(map, (value) => value > 2); + * // result will be: true + * + * const result2 = some(map, (value) => value > 5); + * // result2 will be: false + */ +declare function some(map: Map, doesMatch: (value: V, key: K, map: Map) => boolean): boolean; +//#endregion +export { some }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/map/some.js b/tools/ui/node_modules/es-toolkit/dist/map/some.js new file mode 100644 index 0000000000000000000000000000000000000000..fe62ddf16e40276e26f0c244ea5c873123f90184 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/some.js @@ -0,0 +1,32 @@ +//#region src/map/some.ts +/** +* Tests whether at least one entry in a Map satisfies the provided predicate function. +* +* This function iterates through the entries of the Map and checks if the predicate function +* returns true for at least one entry. It returns true if any entry satisfies the predicate, +* and false otherwise. +* +* @template K - The type of keys in the Map. +* @template V - The type of values in the Map. +* @param {Map} map - The Map to test. +* @param {(value: V, key: K, map: Map) => boolean} doesMatch - A predicate function that tests each entry. +* @returns {boolean} true if at least one entry satisfies the predicate, false otherwise. +* +* @example +* const map = new Map([ +* ['a', 1], +* ['b', 2], +* ['c', 3] +* ]); +* const result = some(map, (value) => value > 2); +* // result will be: true +* +* const result2 = some(map, (value) => value > 5); +* // result2 will be: false +*/ +function some(map, doesMatch) { + for (const [key, value] of map) if (doesMatch(value, key, map)) return true; + return false; +} +//#endregion +exports.some = some; diff --git a/tools/ui/node_modules/es-toolkit/dist/map/some.mjs b/tools/ui/node_modules/es-toolkit/dist/map/some.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b59d3805caeb343492d62729fc1e334c8cd2b108 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/map/some.mjs @@ -0,0 +1,32 @@ +//#region src/map/some.ts +/** +* Tests whether at least one entry in a Map satisfies the provided predicate function. +* +* This function iterates through the entries of the Map and checks if the predicate function +* returns true for at least one entry. It returns true if any entry satisfies the predicate, +* and false otherwise. +* +* @template K - The type of keys in the Map. +* @template V - The type of values in the Map. +* @param {Map} map - The Map to test. +* @param {(value: V, key: K, map: Map) => boolean} doesMatch - A predicate function that tests each entry. +* @returns {boolean} true if at least one entry satisfies the predicate, false otherwise. +* +* @example +* const map = new Map([ +* ['a', 1], +* ['b', 2], +* ['c', 3] +* ]); +* const result = some(map, (value) => value > 2); +* // result will be: true +* +* const result2 = some(map, (value) => value > 5); +* // result2 will be: false +*/ +function some(map, doesMatch) { + for (const [key, value] of map) if (doesMatch(value, key, map)) return true; + return false; +} +//#endregion +export { some }; diff --git a/tools/ui/node_modules/es-toolkit/dist/math/clamp.d.mts b/tools/ui/node_modules/es-toolkit/dist/math/clamp.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..4f660e1f9f5f6d99df7f094c07d72d51d4b64d81 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/clamp.d.mts @@ -0,0 +1,33 @@ +//#region src/math/clamp.d.ts +/** + * Clamps a number within the inclusive upper bound. + * + * This function takes a number and a maximum bound, and returns the number clamped within the specified upper bound. + * If only one bound is provided, it returns the minimum of the value and the bound. + * + * @param {number} value - The number to clamp. + * @param {number} maximum - The maximum bound to clamp the number. + * @returns {number} The clamped number within the specified upper bound. + * + * @example + * const result1 = clamp(10, 5); // result1 will be 5, as 10 is clamped to the bound 5 + */ +declare function clamp(value: number, maximum: number): number; +/** + * Clamps a number within the inclusive lower and upper bounds. + * + * This function takes a number and two bounds, and returns the number clamped within the specified bounds. + * + * @param {number} value - The number to clamp. + * @param {number} minimum - The minimum bound to clamp the number. + * @param {number} maximum - The maximum bound to clamp the number. + * @returns {number} The clamped number within the specified bounds. + * + * @example + * const result2 = clamp(10, 5, 15); // result2 will be 10, as it is within the bounds 5 and 15 + * const result3 = clamp(2, 5, 15); // result3 will be 5, as 2 is clamped to the lower bound 5 + * const result4 = clamp(20, 5, 15); // result4 will be 15, as 20 is clamped to the upper bound 15 + */ +declare function clamp(value: number, minimum: number, maximum: number): number; +//#endregion +export { clamp }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/math/clamp.d.ts b/tools/ui/node_modules/es-toolkit/dist/math/clamp.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4f660e1f9f5f6d99df7f094c07d72d51d4b64d81 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/clamp.d.ts @@ -0,0 +1,33 @@ +//#region src/math/clamp.d.ts +/** + * Clamps a number within the inclusive upper bound. + * + * This function takes a number and a maximum bound, and returns the number clamped within the specified upper bound. + * If only one bound is provided, it returns the minimum of the value and the bound. + * + * @param {number} value - The number to clamp. + * @param {number} maximum - The maximum bound to clamp the number. + * @returns {number} The clamped number within the specified upper bound. + * + * @example + * const result1 = clamp(10, 5); // result1 will be 5, as 10 is clamped to the bound 5 + */ +declare function clamp(value: number, maximum: number): number; +/** + * Clamps a number within the inclusive lower and upper bounds. + * + * This function takes a number and two bounds, and returns the number clamped within the specified bounds. + * + * @param {number} value - The number to clamp. + * @param {number} minimum - The minimum bound to clamp the number. + * @param {number} maximum - The maximum bound to clamp the number. + * @returns {number} The clamped number within the specified bounds. + * + * @example + * const result2 = clamp(10, 5, 15); // result2 will be 10, as it is within the bounds 5 and 15 + * const result3 = clamp(2, 5, 15); // result3 will be 5, as 2 is clamped to the lower bound 5 + * const result4 = clamp(20, 5, 15); // result4 will be 15, as 20 is clamped to the upper bound 15 + */ +declare function clamp(value: number, minimum: number, maximum: number): number; +//#endregion +export { clamp }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/math/clamp.js b/tools/ui/node_modules/es-toolkit/dist/math/clamp.js new file mode 100644 index 0000000000000000000000000000000000000000..c55003790568d6ced4d6db4e80866495fd3d7352 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/clamp.js @@ -0,0 +1,24 @@ +//#region src/math/clamp.ts +/** +* Clamps a number within the specified bounds. +* +* This function takes a number and one or two bounds, and returns the number clamped within the specified bounds. +* If only one bound is provided, it returns the minimum of the value and the bound. +* +* @param {number} value - The number to clamp. +* @param {number} bound1 - The minimum bound to clamp the number, or the maximum bound if bound2 is not provided. +* @param {number} [bound2] - The maximum bound to clamp the number. If not provided, the function will only consider bound1 as the upper limit. +* @returns {number} The clamped number within the specified bounds. +* +* @example +* const result1 = clamp(10, 5); // result1 will be 5, as 10 is clamped to the bound 5 +* const result2 = clamp(10, 5, 15); // result2 will be 10, as it is within the bounds 5 and 15 +* const result3 = clamp(2, 5, 15); // result3 will be 5, as 2 is clamped to the lower bound 5 +* const result4 = clamp(20, 5, 15); // result4 will be 15, as 20 is clamped to the upper bound 15 +*/ +function clamp(value, bound1, bound2) { + if (bound2 == null) return Math.min(value, bound1); + return Math.min(Math.max(value, bound1), bound2); +} +//#endregion +exports.clamp = clamp; diff --git a/tools/ui/node_modules/es-toolkit/dist/math/clamp.mjs b/tools/ui/node_modules/es-toolkit/dist/math/clamp.mjs new file mode 100644 index 0000000000000000000000000000000000000000..9015081c5b7a70cc0263d924f723413b0d5a2b70 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/clamp.mjs @@ -0,0 +1,24 @@ +//#region src/math/clamp.ts +/** +* Clamps a number within the specified bounds. +* +* This function takes a number and one or two bounds, and returns the number clamped within the specified bounds. +* If only one bound is provided, it returns the minimum of the value and the bound. +* +* @param {number} value - The number to clamp. +* @param {number} bound1 - The minimum bound to clamp the number, or the maximum bound if bound2 is not provided. +* @param {number} [bound2] - The maximum bound to clamp the number. If not provided, the function will only consider bound1 as the upper limit. +* @returns {number} The clamped number within the specified bounds. +* +* @example +* const result1 = clamp(10, 5); // result1 will be 5, as 10 is clamped to the bound 5 +* const result2 = clamp(10, 5, 15); // result2 will be 10, as it is within the bounds 5 and 15 +* const result3 = clamp(2, 5, 15); // result3 will be 5, as 2 is clamped to the lower bound 5 +* const result4 = clamp(20, 5, 15); // result4 will be 15, as 20 is clamped to the upper bound 15 +*/ +function clamp(value, bound1, bound2) { + if (bound2 == null) return Math.min(value, bound1); + return Math.min(Math.max(value, bound1), bound2); +} +//#endregion +export { clamp }; diff --git a/tools/ui/node_modules/es-toolkit/dist/math/inRange.d.mts b/tools/ui/node_modules/es-toolkit/dist/math/inRange.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..8f1abdeb9105006291679490861fa19ad0b68f8d --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/inRange.d.mts @@ -0,0 +1,28 @@ +//#region src/math/inRange.d.ts +/** + * Checks if the value is less than the maximum. + * + * @param {number} value The value to check. + * @param {number} maximum The upper bound of the range (exclusive). + * @returns {boolean} `true` if the value is less than the maximum, otherwise `false`. + * + * @example + * const result = inRange(3, 5); // result will be true. + * const result2 = inRange(5, 5); // result2 will be false. + */ +declare function inRange(value: number, maximum: number): boolean; +/** + * Checks if the value is within the range defined by minimum (inclusive) and maximum (exclusive). + * + * @param {number} value The value to check. + * @param {number} minimum The lower bound of the range (inclusive). + * @param {number} maximum The upper bound of the range (exclusive). + * @returns {boolean} `true` if the value is within the specified range, otherwise `false`. + * + * @example + * const result = inRange(3, 2, 5); // result will be true. + * const result2 = inRange(1, 2, 5); // result2 will be false. + */ +declare function inRange(value: number, minimum: number, maximum: number): boolean; +//#endregion +export { inRange }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/math/inRange.d.ts b/tools/ui/node_modules/es-toolkit/dist/math/inRange.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8f1abdeb9105006291679490861fa19ad0b68f8d --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/inRange.d.ts @@ -0,0 +1,28 @@ +//#region src/math/inRange.d.ts +/** + * Checks if the value is less than the maximum. + * + * @param {number} value The value to check. + * @param {number} maximum The upper bound of the range (exclusive). + * @returns {boolean} `true` if the value is less than the maximum, otherwise `false`. + * + * @example + * const result = inRange(3, 5); // result will be true. + * const result2 = inRange(5, 5); // result2 will be false. + */ +declare function inRange(value: number, maximum: number): boolean; +/** + * Checks if the value is within the range defined by minimum (inclusive) and maximum (exclusive). + * + * @param {number} value The value to check. + * @param {number} minimum The lower bound of the range (inclusive). + * @param {number} maximum The upper bound of the range (exclusive). + * @returns {boolean} `true` if the value is within the specified range, otherwise `false`. + * + * @example + * const result = inRange(3, 2, 5); // result will be true. + * const result2 = inRange(1, 2, 5); // result2 will be false. + */ +declare function inRange(value: number, minimum: number, maximum: number): boolean; +//#endregion +export { inRange }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/math/inRange.js b/tools/ui/node_modules/es-toolkit/dist/math/inRange.js new file mode 100644 index 0000000000000000000000000000000000000000..d28069b28d95de6454e8a96caf5667892d15a022 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/inRange.js @@ -0,0 +1,25 @@ +//#region src/math/inRange.ts +/** +* Checks if the value is within a specified range. +* +* @param {number} value The value to check. +* @param {number} minimum The lower bound of the range (inclusive). +* @param {number} maximum The upper bound of the range (exclusive). +* @returns {boolean} `true` if the value is within the specified range, otherwise `false`. +* @throws {Error} Throws an error if the `minimum` is greater or equal than the `maximum`. +* +* @example +* const result1 = inRange(3, 5); // result1 will be true. +* const result2 = inRange(1, 2, 5); // result2 will be false. +* const result3 = inRange(1, 5, 2); // If the minimum is greater or equal than the maximum, an error is thrown. +*/ +function inRange(value, minimum, maximum) { + if (maximum == null) { + maximum = minimum; + minimum = 0; + } + if (minimum >= maximum) throw new Error("The maximum value must be greater than the minimum value."); + return minimum <= value && value < maximum; +} +//#endregion +exports.inRange = inRange; diff --git a/tools/ui/node_modules/es-toolkit/dist/math/inRange.mjs b/tools/ui/node_modules/es-toolkit/dist/math/inRange.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4f4cbd8ef71d2ce63518fcaee795495b6a4789bc --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/inRange.mjs @@ -0,0 +1,25 @@ +//#region src/math/inRange.ts +/** +* Checks if the value is within a specified range. +* +* @param {number} value The value to check. +* @param {number} minimum The lower bound of the range (inclusive). +* @param {number} maximum The upper bound of the range (exclusive). +* @returns {boolean} `true` if the value is within the specified range, otherwise `false`. +* @throws {Error} Throws an error if the `minimum` is greater or equal than the `maximum`. +* +* @example +* const result1 = inRange(3, 5); // result1 will be true. +* const result2 = inRange(1, 2, 5); // result2 will be false. +* const result3 = inRange(1, 5, 2); // If the minimum is greater or equal than the maximum, an error is thrown. +*/ +function inRange(value, minimum, maximum) { + if (maximum == null) { + maximum = minimum; + minimum = 0; + } + if (minimum >= maximum) throw new Error("The maximum value must be greater than the minimum value."); + return minimum <= value && value < maximum; +} +//#endregion +export { inRange }; diff --git a/tools/ui/node_modules/es-toolkit/dist/math/index.d.mts b/tools/ui/node_modules/es-toolkit/dist/math/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..ee33b40fae949e498a62b1b41b63aa0ac0d9b652 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/index.d.mts @@ -0,0 +1,15 @@ +import { clamp } from "./clamp.mjs"; +import { inRange } from "./inRange.mjs"; +import { mean } from "./mean.mjs"; +import { meanBy } from "./meanBy.mjs"; +import { median } from "./median.mjs"; +import { medianBy } from "./medianBy.mjs"; +import { percentile } from "./percentile.mjs"; +import { random } from "./random.mjs"; +import { randomInt } from "./randomInt.mjs"; +import { range } from "./range.mjs"; +import { rangeRight } from "./rangeRight.mjs"; +import { round } from "./round.mjs"; +import { sum } from "./sum.mjs"; +import { sumBy } from "./sumBy.mjs"; +export { clamp, inRange, mean, meanBy, median, medianBy, percentile, random, randomInt, range, rangeRight, round, sum, sumBy }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/math/index.d.ts b/tools/ui/node_modules/es-toolkit/dist/math/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6fac392cb40c46ac455d3f8bb6e0e886a9927a16 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/index.d.ts @@ -0,0 +1,15 @@ +import { clamp } from "./clamp.js"; +import { inRange } from "./inRange.js"; +import { mean } from "./mean.js"; +import { meanBy } from "./meanBy.js"; +import { median } from "./median.js"; +import { medianBy } from "./medianBy.js"; +import { percentile } from "./percentile.js"; +import { random } from "./random.js"; +import { randomInt } from "./randomInt.js"; +import { range } from "./range.js"; +import { rangeRight } from "./rangeRight.js"; +import { round } from "./round.js"; +import { sum } from "./sum.js"; +import { sumBy } from "./sumBy.js"; +export { clamp, inRange, mean, meanBy, median, medianBy, percentile, random, randomInt, range, rangeRight, round, sum, sumBy }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/math/index.js b/tools/ui/node_modules/es-toolkit/dist/math/index.js new file mode 100644 index 0000000000000000000000000000000000000000..8b5df29f34d7ae780b2902d654b9ee3f0d226c74 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/index.js @@ -0,0 +1,29 @@ +Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); +const require_random = require("./random.js"); +const require_randomInt = require("./randomInt.js"); +const require_clamp = require("./clamp.js"); +const require_inRange = require("./inRange.js"); +const require_sum = require("./sum.js"); +const require_mean = require("./mean.js"); +const require_sumBy = require("./sumBy.js"); +const require_meanBy = require("./meanBy.js"); +const require_median = require("./median.js"); +const require_medianBy = require("./medianBy.js"); +const require_percentile = require("./percentile.js"); +const require_range = require("./range.js"); +const require_rangeRight = require("./rangeRight.js"); +const require_round = require("./round.js"); +exports.clamp = require_clamp.clamp; +exports.inRange = require_inRange.inRange; +exports.mean = require_mean.mean; +exports.meanBy = require_meanBy.meanBy; +exports.median = require_median.median; +exports.medianBy = require_medianBy.medianBy; +exports.percentile = require_percentile.percentile; +exports.random = require_random.random; +exports.randomInt = require_randomInt.randomInt; +exports.range = require_range.range; +exports.rangeRight = require_rangeRight.rangeRight; +exports.round = require_round.round; +exports.sum = require_sum.sum; +exports.sumBy = require_sumBy.sumBy; diff --git a/tools/ui/node_modules/es-toolkit/dist/math/index.mjs b/tools/ui/node_modules/es-toolkit/dist/math/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e3b92f2f933a1ab6bcb9fc5187ce13d9f5e2b32d --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/index.mjs @@ -0,0 +1,15 @@ +import { random } from "./random.mjs"; +import { randomInt } from "./randomInt.mjs"; +import { clamp } from "./clamp.mjs"; +import { inRange } from "./inRange.mjs"; +import { sum } from "./sum.mjs"; +import { mean } from "./mean.mjs"; +import { sumBy } from "./sumBy.mjs"; +import { meanBy } from "./meanBy.mjs"; +import { median } from "./median.mjs"; +import { medianBy } from "./medianBy.mjs"; +import { percentile } from "./percentile.mjs"; +import { range } from "./range.mjs"; +import { rangeRight } from "./rangeRight.mjs"; +import { round } from "./round.mjs"; +export { clamp, inRange, mean, meanBy, median, medianBy, percentile, random, randomInt, range, rangeRight, round, sum, sumBy }; diff --git a/tools/ui/node_modules/es-toolkit/dist/math/mean.d.mts b/tools/ui/node_modules/es-toolkit/dist/math/mean.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..fe5958effba09857bc4a8327b0505a2edc5c72ee --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/mean.d.mts @@ -0,0 +1,17 @@ +//#region src/math/mean.d.ts +/** + * Calculates the average of an array of numbers. + * + * If the array is empty, this function returns `NaN`. + * + * @param {number[]} nums - An array of numbers to calculate the average. + * @returns {number} The average of all the numbers in the array. + * + * @example + * const numbers = [1, 2, 3, 4, 5]; + * const result = mean(numbers); + * // result will be 3 + */ +declare function mean(nums: readonly number[]): number; +//#endregion +export { mean }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/math/mean.d.ts b/tools/ui/node_modules/es-toolkit/dist/math/mean.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fe5958effba09857bc4a8327b0505a2edc5c72ee --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/mean.d.ts @@ -0,0 +1,17 @@ +//#region src/math/mean.d.ts +/** + * Calculates the average of an array of numbers. + * + * If the array is empty, this function returns `NaN`. + * + * @param {number[]} nums - An array of numbers to calculate the average. + * @returns {number} The average of all the numbers in the array. + * + * @example + * const numbers = [1, 2, 3, 4, 5]; + * const result = mean(numbers); + * // result will be 3 + */ +declare function mean(nums: readonly number[]): number; +//#endregion +export { mean }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/math/mean.js b/tools/ui/node_modules/es-toolkit/dist/math/mean.js new file mode 100644 index 0000000000000000000000000000000000000000..7f3099561a019cf0edd5ff580912c5a991b61192 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/mean.js @@ -0,0 +1,20 @@ +const require_sum = require("./sum.js"); +//#region src/math/mean.ts +/** +* Calculates the average of an array of numbers. +* +* If the array is empty, this function returns `NaN`. +* +* @param {number[]} nums - An array of numbers to calculate the average. +* @returns {number} The average of all the numbers in the array. +* +* @example +* const numbers = [1, 2, 3, 4, 5]; +* const result = mean(numbers); +* // result will be 3 +*/ +function mean(nums) { + return require_sum.sum(nums) / nums.length; +} +//#endregion +exports.mean = mean; diff --git a/tools/ui/node_modules/es-toolkit/dist/math/mean.mjs b/tools/ui/node_modules/es-toolkit/dist/math/mean.mjs new file mode 100644 index 0000000000000000000000000000000000000000..136aa61c825f07d4ffb31b862714822ca2fcf5cf --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/mean.mjs @@ -0,0 +1,20 @@ +import { sum } from "./sum.mjs"; +//#region src/math/mean.ts +/** +* Calculates the average of an array of numbers. +* +* If the array is empty, this function returns `NaN`. +* +* @param {number[]} nums - An array of numbers to calculate the average. +* @returns {number} The average of all the numbers in the array. +* +* @example +* const numbers = [1, 2, 3, 4, 5]; +* const result = mean(numbers); +* // result will be 3 +*/ +function mean(nums) { + return sum(nums) / nums.length; +} +//#endregion +export { mean }; diff --git a/tools/ui/node_modules/es-toolkit/dist/math/meanBy.d.mts b/tools/ui/node_modules/es-toolkit/dist/math/meanBy.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..de9acfe3c680d412991b12aa75d61cf1454b3921 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/meanBy.d.mts @@ -0,0 +1,19 @@ +//#region src/math/meanBy.d.ts +/** + * Calculates the average of an array of numbers when applying + * the `getValue` function to each element. + * + * If the array is empty, this function returns `NaN`. + * + * @template T - The type of elements in the array. + * @param {T[]} items An array to calculate the average. + * @param {(element: T) => number} getValue A function that selects a numeric value from each element. + * @returns {number} The average of all the numbers as determined by the `getValue` function. + * + * @example + * meanBy([{ a: 1 }, { a: 2 }, { a: 3 }], x => x.a); // Returns: 2 + * meanBy([], x => x.a); // Returns: NaN + */ +declare function meanBy(items: readonly T[], getValue: (element: T) => number): number; +//#endregion +export { meanBy }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/math/meanBy.d.ts b/tools/ui/node_modules/es-toolkit/dist/math/meanBy.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..de9acfe3c680d412991b12aa75d61cf1454b3921 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/meanBy.d.ts @@ -0,0 +1,19 @@ +//#region src/math/meanBy.d.ts +/** + * Calculates the average of an array of numbers when applying + * the `getValue` function to each element. + * + * If the array is empty, this function returns `NaN`. + * + * @template T - The type of elements in the array. + * @param {T[]} items An array to calculate the average. + * @param {(element: T) => number} getValue A function that selects a numeric value from each element. + * @returns {number} The average of all the numbers as determined by the `getValue` function. + * + * @example + * meanBy([{ a: 1 }, { a: 2 }, { a: 3 }], x => x.a); // Returns: 2 + * meanBy([], x => x.a); // Returns: NaN + */ +declare function meanBy(items: readonly T[], getValue: (element: T) => number): number; +//#endregion +export { meanBy }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/math/meanBy.js b/tools/ui/node_modules/es-toolkit/dist/math/meanBy.js new file mode 100644 index 0000000000000000000000000000000000000000..77907faafd43b5a7a34e790d6e861e1fc6e34c77 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/meanBy.js @@ -0,0 +1,22 @@ +const require_sumBy = require("./sumBy.js"); +//#region src/math/meanBy.ts +/** +* Calculates the average of an array of numbers when applying +* the `getValue` function to each element. +* +* If the array is empty, this function returns `NaN`. +* +* @template T - The type of elements in the array. +* @param {T[]} items An array to calculate the average. +* @param {(element: T) => number} getValue A function that selects a numeric value from each element. +* @returns {number} The average of all the numbers as determined by the `getValue` function. +* +* @example +* meanBy([{ a: 1 }, { a: 2 }, { a: 3 }], x => x.a); // Returns: 2 +* meanBy([], x => x.a); // Returns: NaN +*/ +function meanBy(items, getValue) { + return require_sumBy.sumBy(items, (item) => getValue(item)) / items.length; +} +//#endregion +exports.meanBy = meanBy; diff --git a/tools/ui/node_modules/es-toolkit/dist/math/meanBy.mjs b/tools/ui/node_modules/es-toolkit/dist/math/meanBy.mjs new file mode 100644 index 0000000000000000000000000000000000000000..056650a9a574a464bb7b8937cdccda8bb5b5c6e0 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/meanBy.mjs @@ -0,0 +1,22 @@ +import { sumBy } from "./sumBy.mjs"; +//#region src/math/meanBy.ts +/** +* Calculates the average of an array of numbers when applying +* the `getValue` function to each element. +* +* If the array is empty, this function returns `NaN`. +* +* @template T - The type of elements in the array. +* @param {T[]} items An array to calculate the average. +* @param {(element: T) => number} getValue A function that selects a numeric value from each element. +* @returns {number} The average of all the numbers as determined by the `getValue` function. +* +* @example +* meanBy([{ a: 1 }, { a: 2 }, { a: 3 }], x => x.a); // Returns: 2 +* meanBy([], x => x.a); // Returns: NaN +*/ +function meanBy(items, getValue) { + return sumBy(items, (item) => getValue(item)) / items.length; +} +//#endregion +export { meanBy }; diff --git a/tools/ui/node_modules/es-toolkit/dist/math/median.d.mts b/tools/ui/node_modules/es-toolkit/dist/math/median.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..8b4ed3bbdb9744ef67ca32fa01c132353935eda8 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/median.d.mts @@ -0,0 +1,26 @@ +//#region src/math/median.d.ts +/** + * Calculates the median of an array of numbers. + * + * The median is the middle value of a sorted array. + * If the array has an odd number of elements, the median is the middle value. + * If the array has an even number of elements, it returns the average of the two middle values. + * + * If the array is empty, this function returns `NaN`. + * + * @param {number[]} nums - An array of numbers to calculate the median. + * @returns {number} The median of all the numbers in the array. + * + * @example + * const arrayWithOddNumberOfElements = [1, 2, 3, 4, 5]; + * const result = median(arrayWithOddNumberOfElements); + * // result will be 3 + * + * @example + * const arrayWithEvenNumberOfElements = [1, 2, 3, 4]; + * const result = median(arrayWithEvenNumberOfElements); + * // result will be 2.5 + */ +declare function median(nums: readonly number[]): number; +//#endregion +export { median }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/math/median.d.ts b/tools/ui/node_modules/es-toolkit/dist/math/median.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8b4ed3bbdb9744ef67ca32fa01c132353935eda8 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/median.d.ts @@ -0,0 +1,26 @@ +//#region src/math/median.d.ts +/** + * Calculates the median of an array of numbers. + * + * The median is the middle value of a sorted array. + * If the array has an odd number of elements, the median is the middle value. + * If the array has an even number of elements, it returns the average of the two middle values. + * + * If the array is empty, this function returns `NaN`. + * + * @param {number[]} nums - An array of numbers to calculate the median. + * @returns {number} The median of all the numbers in the array. + * + * @example + * const arrayWithOddNumberOfElements = [1, 2, 3, 4, 5]; + * const result = median(arrayWithOddNumberOfElements); + * // result will be 3 + * + * @example + * const arrayWithEvenNumberOfElements = [1, 2, 3, 4]; + * const result = median(arrayWithEvenNumberOfElements); + * // result will be 2.5 + */ +declare function median(nums: readonly number[]): number; +//#endregion +export { median }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/math/median.js b/tools/ui/node_modules/es-toolkit/dist/math/median.js new file mode 100644 index 0000000000000000000000000000000000000000..aab7c3c7e17fbaa2870d3512d5707d2d6a92675a --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/median.js @@ -0,0 +1,32 @@ +//#region src/math/median.ts +/** +* Calculates the median of an array of numbers. +* +* The median is the middle value of a sorted array. +* If the array has an odd number of elements, the median is the middle value. +* If the array has an even number of elements, it returns the average of the two middle values. +* +* If the array is empty, this function returns `NaN`. +* +* @param {number[]} nums - An array of numbers to calculate the median. +* @returns {number} The median of all the numbers in the array. +* +* @example +* const arrayWithOddNumberOfElements = [1, 2, 3, 4, 5]; +* const result = median(arrayWithOddNumberOfElements); +* // result will be 3 +* +* @example +* const arrayWithEvenNumberOfElements = [1, 2, 3, 4]; +* const result = median(arrayWithEvenNumberOfElements); +* // result will be 2.5 +*/ +function median(nums) { + if (nums.length === 0) return NaN; + const sorted = nums.slice().sort((a, b) => a - b); + const middleIndex = Math.floor(sorted.length / 2); + if (sorted.length % 2 === 0) return (sorted[middleIndex - 1] + sorted[middleIndex]) / 2; + else return sorted[middleIndex]; +} +//#endregion +exports.median = median; diff --git a/tools/ui/node_modules/es-toolkit/dist/math/median.mjs b/tools/ui/node_modules/es-toolkit/dist/math/median.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4a4454fa3f3ee9dbb7c4d8c8f8cc7b6c108ef523 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/median.mjs @@ -0,0 +1,32 @@ +//#region src/math/median.ts +/** +* Calculates the median of an array of numbers. +* +* The median is the middle value of a sorted array. +* If the array has an odd number of elements, the median is the middle value. +* If the array has an even number of elements, it returns the average of the two middle values. +* +* If the array is empty, this function returns `NaN`. +* +* @param {number[]} nums - An array of numbers to calculate the median. +* @returns {number} The median of all the numbers in the array. +* +* @example +* const arrayWithOddNumberOfElements = [1, 2, 3, 4, 5]; +* const result = median(arrayWithOddNumberOfElements); +* // result will be 3 +* +* @example +* const arrayWithEvenNumberOfElements = [1, 2, 3, 4]; +* const result = median(arrayWithEvenNumberOfElements); +* // result will be 2.5 +*/ +function median(nums) { + if (nums.length === 0) return NaN; + const sorted = nums.slice().sort((a, b) => a - b); + const middleIndex = Math.floor(sorted.length / 2); + if (sorted.length % 2 === 0) return (sorted[middleIndex - 1] + sorted[middleIndex]) / 2; + else return sorted[middleIndex]; +} +//#endregion +export { median }; diff --git a/tools/ui/node_modules/es-toolkit/dist/math/medianBy.d.mts b/tools/ui/node_modules/es-toolkit/dist/math/medianBy.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..161b437cc74fc72d567b33e96cdf492baa4270a5 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/medianBy.d.mts @@ -0,0 +1,24 @@ +//#region src/math/medianBy.d.ts +/** + * Calculates the median of an array of elements when applying + * the `getValue` function to each element. + * + * The median is the middle value of a sorted array. + * If the array has an odd number of elements, the median is the middle value. + * If the array has an even number of elements, it returns the average of the two middle values. + * + * If the array is empty, this function returns `NaN`. + * + * @template T - The type of elements in the array. + * @param {T[]} items An array to calculate the median. + * @param {(element: T) => number} getValue A function that selects a numeric value from each element. + * @returns {number} The median of all the numbers as determined by the `getValue` function. + * + * @example + * medianBy([{ a: 1 }, { a: 2 }, { a: 3 }, { a: 4 }, { a: 5 }], x => x.a); // Returns: 3 + * medianBy([{ a: 1 }, { a: 2 }, { a: 3 }, { a: 4 }], x => x.a); // Returns: 2.5 + * medianBy([], x => x.a); // Returns: NaN + */ +declare function medianBy(items: readonly T[], getValue: (element: T) => number): number; +//#endregion +export { medianBy }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/math/medianBy.d.ts b/tools/ui/node_modules/es-toolkit/dist/math/medianBy.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..161b437cc74fc72d567b33e96cdf492baa4270a5 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/medianBy.d.ts @@ -0,0 +1,24 @@ +//#region src/math/medianBy.d.ts +/** + * Calculates the median of an array of elements when applying + * the `getValue` function to each element. + * + * The median is the middle value of a sorted array. + * If the array has an odd number of elements, the median is the middle value. + * If the array has an even number of elements, it returns the average of the two middle values. + * + * If the array is empty, this function returns `NaN`. + * + * @template T - The type of elements in the array. + * @param {T[]} items An array to calculate the median. + * @param {(element: T) => number} getValue A function that selects a numeric value from each element. + * @returns {number} The median of all the numbers as determined by the `getValue` function. + * + * @example + * medianBy([{ a: 1 }, { a: 2 }, { a: 3 }, { a: 4 }, { a: 5 }], x => x.a); // Returns: 3 + * medianBy([{ a: 1 }, { a: 2 }, { a: 3 }, { a: 4 }], x => x.a); // Returns: 2.5 + * medianBy([], x => x.a); // Returns: NaN + */ +declare function medianBy(items: readonly T[], getValue: (element: T) => number): number; +//#endregion +export { medianBy }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/math/medianBy.js b/tools/ui/node_modules/es-toolkit/dist/math/medianBy.js new file mode 100644 index 0000000000000000000000000000000000000000..754c8ceadf9a08a80e6495f8c1b902b30396d08b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/medianBy.js @@ -0,0 +1,28 @@ +const require_median = require("./median.js"); +//#region src/math/medianBy.ts +/** +* Calculates the median of an array of elements when applying +* the `getValue` function to each element. +* +* The median is the middle value of a sorted array. +* If the array has an odd number of elements, the median is the middle value. +* If the array has an even number of elements, it returns the average of the two middle values. +* +* If the array is empty, this function returns `NaN`. +* +* @template T - The type of elements in the array. +* @param {T[]} items An array to calculate the median. +* @param {(element: T) => number} getValue A function that selects a numeric value from each element. +* @returns {number} The median of all the numbers as determined by the `getValue` function. +* +* @example +* medianBy([{ a: 1 }, { a: 2 }, { a: 3 }, { a: 4 }, { a: 5 }], x => x.a); // Returns: 3 +* medianBy([{ a: 1 }, { a: 2 }, { a: 3 }, { a: 4 }], x => x.a); // Returns: 2.5 +* medianBy([], x => x.a); // Returns: NaN +*/ +function medianBy(items, getValue) { + const nums = items.map((x) => getValue(x)); + return require_median.median(nums); +} +//#endregion +exports.medianBy = medianBy; diff --git a/tools/ui/node_modules/es-toolkit/dist/math/medianBy.mjs b/tools/ui/node_modules/es-toolkit/dist/math/medianBy.mjs new file mode 100644 index 0000000000000000000000000000000000000000..929516130cc7d60cbbe3306ab753be5365d34221 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/medianBy.mjs @@ -0,0 +1,27 @@ +import { median } from "./median.mjs"; +//#region src/math/medianBy.ts +/** +* Calculates the median of an array of elements when applying +* the `getValue` function to each element. +* +* The median is the middle value of a sorted array. +* If the array has an odd number of elements, the median is the middle value. +* If the array has an even number of elements, it returns the average of the two middle values. +* +* If the array is empty, this function returns `NaN`. +* +* @template T - The type of elements in the array. +* @param {T[]} items An array to calculate the median. +* @param {(element: T) => number} getValue A function that selects a numeric value from each element. +* @returns {number} The median of all the numbers as determined by the `getValue` function. +* +* @example +* medianBy([{ a: 1 }, { a: 2 }, { a: 3 }, { a: 4 }, { a: 5 }], x => x.a); // Returns: 3 +* medianBy([{ a: 1 }, { a: 2 }, { a: 3 }, { a: 4 }], x => x.a); // Returns: 2.5 +* medianBy([], x => x.a); // Returns: NaN +*/ +function medianBy(items, getValue) { + return median(items.map((x) => getValue(x))); +} +//#endregion +export { medianBy }; diff --git a/tools/ui/node_modules/es-toolkit/dist/math/percentile.d.mts b/tools/ui/node_modules/es-toolkit/dist/math/percentile.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..42cf438d5fe3d6459b5599871a989a8993a13d90 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/percentile.d.mts @@ -0,0 +1,29 @@ +//#region src/math/percentile.d.ts +/** + * Calculates the value at the given percentile of an array of numbers. + * + * Sorts the array in ascending order and returns the element at the nearest rank. + * See {@link https://en.wikipedia.org/wiki/Percentile#The_nearest-rank_method | Nearest rank method}. + * + * `NaN` values are sorted as the smallest values. Returns `NaN` if the array is empty. + * + * @param {readonly number[]} arr - An array of numbers to calculate the percentile. + * @param {number} percentile - The percentile to compute, in the range `[0, 100]`. + * @returns {number} The value at the given percentile. + * @throws {Error} Throws an error if `percentile` is not a number, less than `0`, or greater than `100`. + * + * @example + * percentile([1, 2, 3, 4, 5], 50); + * // Returns 3 + * + * @example + * percentile([1, 2, 3, 4, 5], 75); + * // Returns 4 + * + * @example + * percentile([5, 1, 4, 2, 3], 0); + * // Returns 1 + */ +declare function percentile(arr: readonly number[], percentile: number): number; +//#endregion +export { percentile }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/math/percentile.d.ts b/tools/ui/node_modules/es-toolkit/dist/math/percentile.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..42cf438d5fe3d6459b5599871a989a8993a13d90 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/percentile.d.ts @@ -0,0 +1,29 @@ +//#region src/math/percentile.d.ts +/** + * Calculates the value at the given percentile of an array of numbers. + * + * Sorts the array in ascending order and returns the element at the nearest rank. + * See {@link https://en.wikipedia.org/wiki/Percentile#The_nearest-rank_method | Nearest rank method}. + * + * `NaN` values are sorted as the smallest values. Returns `NaN` if the array is empty. + * + * @param {readonly number[]} arr - An array of numbers to calculate the percentile. + * @param {number} percentile - The percentile to compute, in the range `[0, 100]`. + * @returns {number} The value at the given percentile. + * @throws {Error} Throws an error if `percentile` is not a number, less than `0`, or greater than `100`. + * + * @example + * percentile([1, 2, 3, 4, 5], 50); + * // Returns 3 + * + * @example + * percentile([1, 2, 3, 4, 5], 75); + * // Returns 4 + * + * @example + * percentile([5, 1, 4, 2, 3], 0); + * // Returns 1 + */ +declare function percentile(arr: readonly number[], percentile: number): number; +//#endregion +export { percentile }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/math/percentile.js b/tools/ui/node_modules/es-toolkit/dist/math/percentile.js new file mode 100644 index 0000000000000000000000000000000000000000..026c072d3950d988e76fdc2f67714567c0912e77 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/percentile.js @@ -0,0 +1,39 @@ +//#region src/math/percentile.ts +/** +* Calculates the value at the given percentile of an array of numbers. +* +* Sorts the array in ascending order and returns the element at the nearest rank. +* See {@link https://en.wikipedia.org/wiki/Percentile#The_nearest-rank_method | Nearest rank method}. +* +* `NaN` values are sorted as the smallest values. Returns `NaN` if the array is empty. +* +* @param {readonly number[]} arr - An array of numbers to calculate the percentile. +* @param {number} percentile - The percentile to compute, in the range `[0, 100]`. +* @returns {number} The value at the given percentile. +* @throws {Error} Throws an error if `percentile` is not a number, less than `0`, or greater than `100`. +* +* @example +* percentile([1, 2, 3, 4, 5], 50); +* // Returns 3 +* +* @example +* percentile([1, 2, 3, 4, 5], 75); +* // Returns 4 +* +* @example +* percentile([5, 1, 4, 2, 3], 0); +* // Returns 1 +*/ +function percentile(arr, percentile) { + if (Number.isNaN(Number(percentile))) throw new Error(`Expected percentile to be a number but got "${percentile}".`); + if (percentile < 0) throw new Error(`Expected percentile to be >= 0 but got "${percentile}".`); + if (percentile > 100) throw new Error(`Expected percentile to be <= 100 but got "${percentile}".`); + if (arr.length === 0) return NaN; + const sorted = arr.slice().sort((a, b) => { + return (Number.isNaN(a) ? Number.NEGATIVE_INFINITY : a) - (Number.isNaN(b) ? Number.NEGATIVE_INFINITY : b); + }); + if (percentile === 0) return sorted[0]; + return sorted[Math.ceil(sorted.length * (percentile / 100)) - 1]; +} +//#endregion +exports.percentile = percentile; diff --git a/tools/ui/node_modules/es-toolkit/dist/math/percentile.mjs b/tools/ui/node_modules/es-toolkit/dist/math/percentile.mjs new file mode 100644 index 0000000000000000000000000000000000000000..30f67ffa5952650b10eb271465765ab3c4475718 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/percentile.mjs @@ -0,0 +1,39 @@ +//#region src/math/percentile.ts +/** +* Calculates the value at the given percentile of an array of numbers. +* +* Sorts the array in ascending order and returns the element at the nearest rank. +* See {@link https://en.wikipedia.org/wiki/Percentile#The_nearest-rank_method | Nearest rank method}. +* +* `NaN` values are sorted as the smallest values. Returns `NaN` if the array is empty. +* +* @param {readonly number[]} arr - An array of numbers to calculate the percentile. +* @param {number} percentile - The percentile to compute, in the range `[0, 100]`. +* @returns {number} The value at the given percentile. +* @throws {Error} Throws an error if `percentile` is not a number, less than `0`, or greater than `100`. +* +* @example +* percentile([1, 2, 3, 4, 5], 50); +* // Returns 3 +* +* @example +* percentile([1, 2, 3, 4, 5], 75); +* // Returns 4 +* +* @example +* percentile([5, 1, 4, 2, 3], 0); +* // Returns 1 +*/ +function percentile(arr, percentile) { + if (Number.isNaN(Number(percentile))) throw new Error(`Expected percentile to be a number but got "${percentile}".`); + if (percentile < 0) throw new Error(`Expected percentile to be >= 0 but got "${percentile}".`); + if (percentile > 100) throw new Error(`Expected percentile to be <= 100 but got "${percentile}".`); + if (arr.length === 0) return NaN; + const sorted = arr.slice().sort((a, b) => { + return (Number.isNaN(a) ? Number.NEGATIVE_INFINITY : a) - (Number.isNaN(b) ? Number.NEGATIVE_INFINITY : b); + }); + if (percentile === 0) return sorted[0]; + return sorted[Math.ceil(sorted.length * (percentile / 100)) - 1]; +} +//#endregion +export { percentile }; diff --git a/tools/ui/node_modules/es-toolkit/dist/math/random.d.mts b/tools/ui/node_modules/es-toolkit/dist/math/random.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..64d561bd055453938ce5818ff3b7eba0f6d53c08 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/random.d.mts @@ -0,0 +1,31 @@ +//#region src/math/random.d.ts +/** + * Generate a random number within the given range. + * + * If only one argument is provided, a number between `0` and the given number is returned. + * + * @param {number} maximum - The upper bound (exclusive). + * @returns {number} A random number between 0 (inclusive) and maximum (exclusive). The number can be an integer or a decimal. + * @throws {Error} Throws an error if `maximum` is not greater than `0`. + * + * @example + * const result1 = random(5); // Returns a random number between 0 and 5. + * const result2 = random(0); // If the `maximum` is less than or equal to 0, an error is thrown. + */ +declare function random(maximum: number): number; +/** + * Generate a random number within the given range. + * + * @param {number} minimum - The lower bound (inclusive). + * @param {number} maximum - The upper bound (exclusive). + * @returns {number} A random number between minimum (inclusive) and maximum (exclusive). The number can be an integer or a decimal. + * @throws {Error} Throws an error if `maximum` is not greater than `minimum`. + * + * @example + * const result1 = random(0, 5); // Returns a random number between 0 and 5. + * const result2 = random(5, 0); // If the minimum is greater than the maximum, an error is thrown. + * const result3 = random(5, 5); // If the minimum is equal to the maximum, an error is thrown. + */ +declare function random(minimum: number, maximum: number): number; +//#endregion +export { random }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/math/random.d.ts b/tools/ui/node_modules/es-toolkit/dist/math/random.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..64d561bd055453938ce5818ff3b7eba0f6d53c08 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/random.d.ts @@ -0,0 +1,31 @@ +//#region src/math/random.d.ts +/** + * Generate a random number within the given range. + * + * If only one argument is provided, a number between `0` and the given number is returned. + * + * @param {number} maximum - The upper bound (exclusive). + * @returns {number} A random number between 0 (inclusive) and maximum (exclusive). The number can be an integer or a decimal. + * @throws {Error} Throws an error if `maximum` is not greater than `0`. + * + * @example + * const result1 = random(5); // Returns a random number between 0 and 5. + * const result2 = random(0); // If the `maximum` is less than or equal to 0, an error is thrown. + */ +declare function random(maximum: number): number; +/** + * Generate a random number within the given range. + * + * @param {number} minimum - The lower bound (inclusive). + * @param {number} maximum - The upper bound (exclusive). + * @returns {number} A random number between minimum (inclusive) and maximum (exclusive). The number can be an integer or a decimal. + * @throws {Error} Throws an error if `maximum` is not greater than `minimum`. + * + * @example + * const result1 = random(0, 5); // Returns a random number between 0 and 5. + * const result2 = random(5, 0); // If the minimum is greater than the maximum, an error is thrown. + * const result3 = random(5, 5); // If the minimum is equal to the maximum, an error is thrown. + */ +declare function random(minimum: number, maximum: number): number; +//#endregion +export { random }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/math/random.js b/tools/ui/node_modules/es-toolkit/dist/math/random.js new file mode 100644 index 0000000000000000000000000000000000000000..4607ba536c70ef278c41e842d928fbb462e05c12 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/random.js @@ -0,0 +1,24 @@ +//#region src/math/random.ts +/** +* Generate a random number within the given range. +* +* @param {number} minimum - The lower bound (inclusive). +* @param {number} maximum - The upper bound (exclusive). +* @returns {number} A random number between minimum (inclusive) and maximum (exclusive). The number can be an integer or a decimal. +* @throws {Error} Throws an error if `maximum` is not greater than `minimum`. +* +* @example +* const result1 = random(0, 5); // Returns a random number between 0 and 5. +* const result2 = random(5, 0); // If the minimum is greater than the maximum, an error is thrown. +* const result3 = random(5, 5); // If the minimum is equal to the maximum, an error is thrown. +*/ +function random(minimum, maximum) { + if (maximum == null) { + maximum = minimum; + minimum = 0; + } + if (minimum >= maximum) throw new Error("Invalid input: The maximum value must be greater than the minimum value."); + return Math.random() * (maximum - minimum) + minimum; +} +//#endregion +exports.random = random; diff --git a/tools/ui/node_modules/es-toolkit/dist/math/random.mjs b/tools/ui/node_modules/es-toolkit/dist/math/random.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f3b96b48d399367bc2c822ce41c0f7207abc7eb9 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/random.mjs @@ -0,0 +1,24 @@ +//#region src/math/random.ts +/** +* Generate a random number within the given range. +* +* @param {number} minimum - The lower bound (inclusive). +* @param {number} maximum - The upper bound (exclusive). +* @returns {number} A random number between minimum (inclusive) and maximum (exclusive). The number can be an integer or a decimal. +* @throws {Error} Throws an error if `maximum` is not greater than `minimum`. +* +* @example +* const result1 = random(0, 5); // Returns a random number between 0 and 5. +* const result2 = random(5, 0); // If the minimum is greater than the maximum, an error is thrown. +* const result3 = random(5, 5); // If the minimum is equal to the maximum, an error is thrown. +*/ +function random(minimum, maximum) { + if (maximum == null) { + maximum = minimum; + minimum = 0; + } + if (minimum >= maximum) throw new Error("Invalid input: The maximum value must be greater than the minimum value."); + return Math.random() * (maximum - minimum) + minimum; +} +//#endregion +export { random }; diff --git a/tools/ui/node_modules/es-toolkit/dist/math/randomInt.d.mts b/tools/ui/node_modules/es-toolkit/dist/math/randomInt.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..f83ea207d715f220a388d96786f0704e2f96a5e1 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/randomInt.d.mts @@ -0,0 +1,27 @@ +//#region src/math/randomInt.d.ts +/** + * Generates a random integer between 0 (inclusive) and the given maximum (exclusive). + * + * @param {number} maximum - The upper bound (exclusive). + * @returns {number} A random integer between 0 (inclusive) and maximum (exclusive). + * @throws {Error} Throws an error if `maximum` is not greater than `0`. + * + * @example + * const result = randomInt(5); // result will be a random integer between 0 (inclusive) and 5 (exclusive) + */ +declare function randomInt(maximum: number): number; +/** + * Generates a random integer between minimum (inclusive) and maximum (exclusive). + * + * @param {number} minimum - The lower bound (inclusive). + * @param {number} maximum - The upper bound (exclusive). + * @returns {number} A random integer between minimum (inclusive) and maximum (exclusive). + * @throws {Error} Throws an error if `maximum` is not greater than `minimum`. + * + * @example + * const result = randomInt(0, 5); // result will be a random integer between 0 (inclusive) and 5 (exclusive) + * const result2 = randomInt(5, 0); // This will throw an error + */ +declare function randomInt(minimum: number, maximum: number): number; +//#endregion +export { randomInt }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/math/randomInt.d.ts b/tools/ui/node_modules/es-toolkit/dist/math/randomInt.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f83ea207d715f220a388d96786f0704e2f96a5e1 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/randomInt.d.ts @@ -0,0 +1,27 @@ +//#region src/math/randomInt.d.ts +/** + * Generates a random integer between 0 (inclusive) and the given maximum (exclusive). + * + * @param {number} maximum - The upper bound (exclusive). + * @returns {number} A random integer between 0 (inclusive) and maximum (exclusive). + * @throws {Error} Throws an error if `maximum` is not greater than `0`. + * + * @example + * const result = randomInt(5); // result will be a random integer between 0 (inclusive) and 5 (exclusive) + */ +declare function randomInt(maximum: number): number; +/** + * Generates a random integer between minimum (inclusive) and maximum (exclusive). + * + * @param {number} minimum - The lower bound (inclusive). + * @param {number} maximum - The upper bound (exclusive). + * @returns {number} A random integer between minimum (inclusive) and maximum (exclusive). + * @throws {Error} Throws an error if `maximum` is not greater than `minimum`. + * + * @example + * const result = randomInt(0, 5); // result will be a random integer between 0 (inclusive) and 5 (exclusive) + * const result2 = randomInt(5, 0); // This will throw an error + */ +declare function randomInt(minimum: number, maximum: number): number; +//#endregion +export { randomInt }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/math/randomInt.js b/tools/ui/node_modules/es-toolkit/dist/math/randomInt.js new file mode 100644 index 0000000000000000000000000000000000000000..85af5701e9ad2e0778a72bcef70ac5ebe5978c01 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/randomInt.js @@ -0,0 +1,21 @@ +const require_random = require("./random.js"); +//#region src/math/randomInt.ts +/** +* Generates a random integer between minimum (inclusive) and maximum (exclusive). +* +* If only one argument is provided, a number between `0` and the given number is returned. +* +* @param {number} minimum - The lower bound (inclusive). +* @param {number} maximum - The upper bound (exclusive). +* @returns {number} A random integer between minimum (inclusive) and maximum (exclusive). +* @throws {Error} Throws an error if `maximum` is not greater than `minimum`. +* +* @example +* const result = randomInt(0, 5); // result will be a random integer between 0 (inclusive) and 5 (exclusive) +* const result2 = randomInt(5, 0); // This will throw an error +*/ +function randomInt(minimum, maximum) { + return Math.floor(require_random.random(minimum, maximum)); +} +//#endregion +exports.randomInt = randomInt; diff --git a/tools/ui/node_modules/es-toolkit/dist/math/randomInt.mjs b/tools/ui/node_modules/es-toolkit/dist/math/randomInt.mjs new file mode 100644 index 0000000000000000000000000000000000000000..49a74cbc787a940b942a2e1d97457075322774ec --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/randomInt.mjs @@ -0,0 +1,21 @@ +import { random } from "./random.mjs"; +//#region src/math/randomInt.ts +/** +* Generates a random integer between minimum (inclusive) and maximum (exclusive). +* +* If only one argument is provided, a number between `0` and the given number is returned. +* +* @param {number} minimum - The lower bound (inclusive). +* @param {number} maximum - The upper bound (exclusive). +* @returns {number} A random integer between minimum (inclusive) and maximum (exclusive). +* @throws {Error} Throws an error if `maximum` is not greater than `minimum`. +* +* @example +* const result = randomInt(0, 5); // result will be a random integer between 0 (inclusive) and 5 (exclusive) +* const result2 = randomInt(5, 0); // This will throw an error +*/ +function randomInt(minimum, maximum) { + return Math.floor(random(minimum, maximum)); +} +//#endregion +export { randomInt }; diff --git a/tools/ui/node_modules/es-toolkit/dist/math/range.d.mts b/tools/ui/node_modules/es-toolkit/dist/math/range.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..452848f854b3ce6615369aa7f0c7c08565249a46 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/range.d.mts @@ -0,0 +1,39 @@ +//#region src/math/range.d.ts +/** + * Returns an array of numbers from `0` (inclusive) to `end` (exclusive), incrementing by `1`. + * + * @param {number} end - The end number of the range (exclusive). + * @returns {number[]} An array of numbers from `0` (inclusive) to `end` (exclusive) with a step of `1`. + * + * @example + * // Returns [0, 1, 2, 3] + * range(4); + */ +declare function range(end: number): number[]; +/** + * Returns an array of numbers from `start` (inclusive) to `end` (exclusive), incrementing by `1`. + * + * @param {number} start - The starting number of the range (inclusive). + * @param {number} end - The end number of the range (exclusive). + * @returns {number[]} An array of numbers from `start` (inclusive) to `end` (exclusive) with a step of `1`. + * + * @example + * // Returns [1, 2, 3] + * range(1, 4); + */ +declare function range(start: number, end: number): number[]; +/** + * Returns an array of numbers from `start` (inclusive) to `end` (exclusive), incrementing by `step`. + * + * @param {number} start - The starting number of the range (inclusive). + * @param {number} end - The end number of the range (exclusive). + * @param {number} step - The step value for the range. + * @returns {number[]} An array of numbers from `start` (inclusive) to `end` (exclusive) with the specified `step`. + * + * @example + * // Returns [0, 5, 10, 15] + * range(0, 20, 5); + */ +declare function range(start: number, end: number, step: number): number[]; +//#endregion +export { range }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/math/range.d.ts b/tools/ui/node_modules/es-toolkit/dist/math/range.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..452848f854b3ce6615369aa7f0c7c08565249a46 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/range.d.ts @@ -0,0 +1,39 @@ +//#region src/math/range.d.ts +/** + * Returns an array of numbers from `0` (inclusive) to `end` (exclusive), incrementing by `1`. + * + * @param {number} end - The end number of the range (exclusive). + * @returns {number[]} An array of numbers from `0` (inclusive) to `end` (exclusive) with a step of `1`. + * + * @example + * // Returns [0, 1, 2, 3] + * range(4); + */ +declare function range(end: number): number[]; +/** + * Returns an array of numbers from `start` (inclusive) to `end` (exclusive), incrementing by `1`. + * + * @param {number} start - The starting number of the range (inclusive). + * @param {number} end - The end number of the range (exclusive). + * @returns {number[]} An array of numbers from `start` (inclusive) to `end` (exclusive) with a step of `1`. + * + * @example + * // Returns [1, 2, 3] + * range(1, 4); + */ +declare function range(start: number, end: number): number[]; +/** + * Returns an array of numbers from `start` (inclusive) to `end` (exclusive), incrementing by `step`. + * + * @param {number} start - The starting number of the range (inclusive). + * @param {number} end - The end number of the range (exclusive). + * @param {number} step - The step value for the range. + * @returns {number[]} An array of numbers from `start` (inclusive) to `end` (exclusive) with the specified `step`. + * + * @example + * // Returns [0, 5, 10, 15] + * range(0, 20, 5); + */ +declare function range(start: number, end: number, step: number): number[]; +//#endregion +export { range }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/math/range.js b/tools/ui/node_modules/es-toolkit/dist/math/range.js new file mode 100644 index 0000000000000000000000000000000000000000..c9efbb9cce29c30d2b0c515e3835b6a62ab50fbf --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/range.js @@ -0,0 +1,31 @@ +//#region src/math/range.ts +/** +* Returns an array of numbers from `start` (inclusive) to `end` (exclusive), incrementing by `step`. +* +* @param {number} start - The starting number of the range (inclusive). +* @param {number} end - The end number of the range (exclusive). +* @param {number} step - The step value for the range. +* @returns {number[]} An array of numbers from `start` (inclusive) to `end` (exclusive) with the specified `step`. +* @throws {Error} Throws an error if the step value is not a non-zero integer. +* +* @example +* // Returns [0, 1, 2, 3] +* range(4); +* +* @example +* // Returns [0, -1, -2, -3] +* range(0, -4, -1); +*/ +function range(start, end, step = 1) { + if (end == null) { + end = start; + start = 0; + } + if (!Number.isInteger(step) || step === 0) throw new Error(`The step value must be a non-zero integer.`); + const length = Math.max(Math.ceil((end - start) / step), 0); + const result = new Array(length); + for (let i = 0; i < length; i++) result[i] = start + i * step; + return result; +} +//#endregion +exports.range = range; diff --git a/tools/ui/node_modules/es-toolkit/dist/math/range.mjs b/tools/ui/node_modules/es-toolkit/dist/math/range.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3327820df6325ab843ea7d7f8a64173484208b1f --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/range.mjs @@ -0,0 +1,31 @@ +//#region src/math/range.ts +/** +* Returns an array of numbers from `start` (inclusive) to `end` (exclusive), incrementing by `step`. +* +* @param {number} start - The starting number of the range (inclusive). +* @param {number} end - The end number of the range (exclusive). +* @param {number} step - The step value for the range. +* @returns {number[]} An array of numbers from `start` (inclusive) to `end` (exclusive) with the specified `step`. +* @throws {Error} Throws an error if the step value is not a non-zero integer. +* +* @example +* // Returns [0, 1, 2, 3] +* range(4); +* +* @example +* // Returns [0, -1, -2, -3] +* range(0, -4, -1); +*/ +function range(start, end, step = 1) { + if (end == null) { + end = start; + start = 0; + } + if (!Number.isInteger(step) || step === 0) throw new Error(`The step value must be a non-zero integer.`); + const length = Math.max(Math.ceil((end - start) / step), 0); + const result = new Array(length); + for (let i = 0; i < length; i++) result[i] = start + i * step; + return result; +} +//#endregion +export { range }; diff --git a/tools/ui/node_modules/es-toolkit/dist/math/rangeRight.d.mts b/tools/ui/node_modules/es-toolkit/dist/math/rangeRight.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..159729cfc2e87cf6da4a1133516d76a939fe811d --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/rangeRight.d.mts @@ -0,0 +1,39 @@ +//#region src/math/rangeRight.d.ts +/** + * Returns an array of numbers from `end` (exclusive) to `0` (inclusive), decrementing by `1`. + * + * @param {number} end - The end number of the range (exclusive). + * @returns {number[]} An array of numbers from `end` (exclusive) to `0` (inclusive) with a step of `1`. + * + * @example + * // Returns [3, 2, 1, 0] + * rangeRight(4); + */ +declare function rangeRight(end: number): number[]; +/** + * Returns an array of numbers from `end` (exclusive) to `start` (inclusive), decrementing by `1`. + * + * @param {number} start - The starting number of the range (inclusive). + * @param {number} end - The end number of the range (exclusive). + * @returns {number[]} An array of numbers from `end` (exclusive) to `start` (inclusive) with a step of `1`. + * + * @example + * // Returns [3, 2, 1] + * rangeRight(1, 4); + */ +declare function rangeRight(start: number, end: number): number[]; +/** + * Returns an array of numbers from `end` (exclusive) to `start` (inclusive), decrementing by `step`. + * + * @param {number} start - The starting number of the range (inclusive). + * @param {number} end - The end number of the range (exclusive). + * @param {number} step - The step value for the range. + * @returns {number[]} An array of numbers from `end` (exclusive) to `start` (inclusive) with the specified `step`. + * + * @example + * // Returns [15, 10, 5, 0] + * rangeRight(0, 20, 5); + */ +declare function rangeRight(start: number, end: number, step: number): number[]; +//#endregion +export { rangeRight }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/math/rangeRight.d.ts b/tools/ui/node_modules/es-toolkit/dist/math/rangeRight.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..159729cfc2e87cf6da4a1133516d76a939fe811d --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/rangeRight.d.ts @@ -0,0 +1,39 @@ +//#region src/math/rangeRight.d.ts +/** + * Returns an array of numbers from `end` (exclusive) to `0` (inclusive), decrementing by `1`. + * + * @param {number} end - The end number of the range (exclusive). + * @returns {number[]} An array of numbers from `end` (exclusive) to `0` (inclusive) with a step of `1`. + * + * @example + * // Returns [3, 2, 1, 0] + * rangeRight(4); + */ +declare function rangeRight(end: number): number[]; +/** + * Returns an array of numbers from `end` (exclusive) to `start` (inclusive), decrementing by `1`. + * + * @param {number} start - The starting number of the range (inclusive). + * @param {number} end - The end number of the range (exclusive). + * @returns {number[]} An array of numbers from `end` (exclusive) to `start` (inclusive) with a step of `1`. + * + * @example + * // Returns [3, 2, 1] + * rangeRight(1, 4); + */ +declare function rangeRight(start: number, end: number): number[]; +/** + * Returns an array of numbers from `end` (exclusive) to `start` (inclusive), decrementing by `step`. + * + * @param {number} start - The starting number of the range (inclusive). + * @param {number} end - The end number of the range (exclusive). + * @param {number} step - The step value for the range. + * @returns {number[]} An array of numbers from `end` (exclusive) to `start` (inclusive) with the specified `step`. + * + * @example + * // Returns [15, 10, 5, 0] + * rangeRight(0, 20, 5); + */ +declare function rangeRight(start: number, end: number, step: number): number[]; +//#endregion +export { rangeRight }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/math/rangeRight.js b/tools/ui/node_modules/es-toolkit/dist/math/rangeRight.js new file mode 100644 index 0000000000000000000000000000000000000000..209271127200077da025d6ca342517a441917e40 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/rangeRight.js @@ -0,0 +1,31 @@ +//#region src/math/rangeRight.ts +/** +* Returns an array of numbers from `end` (exclusive) to `start` (inclusive), decrementing by `step`. +* +* @param {number} start - The starting number of the range (inclusive). +* @param {number} end - The end number of the range (exclusive). +* @param {number} step - The step value for the range. +* @returns {number[]} An array of numbers from `end` (exclusive) to `start` (inclusive) with the specified `step`. +* @throws {Error} Throws an error if the step value is not a non-zero integer. +* +* @example +* // Returns [3, 2, 1, 0] +* rangeRight(4); +* +* @example +* // Returns [-3, -2, -1, 0] +* rangeRight(0, -4, -1); +*/ +function rangeRight(start, end, step = 1) { + if (end == null) { + end = start; + start = 0; + } + if (!Number.isInteger(step) || step === 0) throw new Error(`The step value must be a non-zero integer.`); + const length = Math.max(Math.ceil((end - start) / step), 0); + const result = new Array(length); + for (let i = 0; i < length; i++) result[i] = start + (length - i - 1) * step; + return result; +} +//#endregion +exports.rangeRight = rangeRight; diff --git a/tools/ui/node_modules/es-toolkit/dist/math/rangeRight.mjs b/tools/ui/node_modules/es-toolkit/dist/math/rangeRight.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7e2ed378c0fa6cb4bcaa090fd0750667ee4c4d90 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/rangeRight.mjs @@ -0,0 +1,31 @@ +//#region src/math/rangeRight.ts +/** +* Returns an array of numbers from `end` (exclusive) to `start` (inclusive), decrementing by `step`. +* +* @param {number} start - The starting number of the range (inclusive). +* @param {number} end - The end number of the range (exclusive). +* @param {number} step - The step value for the range. +* @returns {number[]} An array of numbers from `end` (exclusive) to `start` (inclusive) with the specified `step`. +* @throws {Error} Throws an error if the step value is not a non-zero integer. +* +* @example +* // Returns [3, 2, 1, 0] +* rangeRight(4); +* +* @example +* // Returns [-3, -2, -1, 0] +* rangeRight(0, -4, -1); +*/ +function rangeRight(start, end, step = 1) { + if (end == null) { + end = start; + start = 0; + } + if (!Number.isInteger(step) || step === 0) throw new Error(`The step value must be a non-zero integer.`); + const length = Math.max(Math.ceil((end - start) / step), 0); + const result = new Array(length); + for (let i = 0; i < length; i++) result[i] = start + (length - i - 1) * step; + return result; +} +//#endregion +export { rangeRight }; diff --git a/tools/ui/node_modules/es-toolkit/dist/math/round.d.mts b/tools/ui/node_modules/es-toolkit/dist/math/round.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..bdf333f7b05fd3b986921074de2a7303cbbc30d9 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/round.d.mts @@ -0,0 +1,21 @@ +//#region src/math/round.d.ts +/** + * Rounds a number to a specified precision. + * + * This function takes a number and an optional precision value, and returns the number rounded + * to the specified number of decimal places. + * + * @param {number} value - The number to round. + * @param {number} [precision=0] - The number of decimal places to round to. Defaults to 0. + * @returns {number} The rounded number. + * @throws {Error} Throws an error if `Precision` is not integer. + * + * @example + * const result1 = round(1.2345); // result1 will be 1 + * const result2 = round(1.2345, 2); // result2 will be 1.23 + * const result3 = round(1.2345, 3); // result3 will be 1.235 + * const result4 = round(1.2345, 3.1); // This will throw an error + */ +declare function round(value: number, precision?: number): number; +//#endregion +export { round }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/math/round.d.ts b/tools/ui/node_modules/es-toolkit/dist/math/round.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bdf333f7b05fd3b986921074de2a7303cbbc30d9 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/round.d.ts @@ -0,0 +1,21 @@ +//#region src/math/round.d.ts +/** + * Rounds a number to a specified precision. + * + * This function takes a number and an optional precision value, and returns the number rounded + * to the specified number of decimal places. + * + * @param {number} value - The number to round. + * @param {number} [precision=0] - The number of decimal places to round to. Defaults to 0. + * @returns {number} The rounded number. + * @throws {Error} Throws an error if `Precision` is not integer. + * + * @example + * const result1 = round(1.2345); // result1 will be 1 + * const result2 = round(1.2345, 2); // result2 will be 1.23 + * const result3 = round(1.2345, 3); // result3 will be 1.235 + * const result4 = round(1.2345, 3.1); // This will throw an error + */ +declare function round(value: number, precision?: number): number; +//#endregion +export { round }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/math/round.js b/tools/ui/node_modules/es-toolkit/dist/math/round.js new file mode 100644 index 0000000000000000000000000000000000000000..a2991a94a9cb2003d73f7bbf1779e15843fb79c2 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/round.js @@ -0,0 +1,25 @@ +//#region src/math/round.ts +/** +* Rounds a number to a specified precision. +* +* This function takes a number and an optional precision value, and returns the number rounded +* to the specified number of decimal places. +* +* @param {number} value - The number to round. +* @param {number} [precision=0] - The number of decimal places to round to. Defaults to 0. +* @returns {number} The rounded number. +* @throws {Error} Throws an error if `Precision` is not integer. +* +* @example +* const result1 = round(1.2345); // result1 will be 1 +* const result2 = round(1.2345, 2); // result2 will be 1.23 +* const result3 = round(1.2345, 3); // result3 will be 1.235 +* const result4 = round(1.2345, 3.1); // This will throw an error +*/ +function round(value, precision = 0) { + if (!Number.isInteger(precision)) throw new Error("Precision must be an integer."); + const multiplier = Math.pow(10, precision); + return Math.round(value * multiplier) / multiplier; +} +//#endregion +exports.round = round; diff --git a/tools/ui/node_modules/es-toolkit/dist/math/round.mjs b/tools/ui/node_modules/es-toolkit/dist/math/round.mjs new file mode 100644 index 0000000000000000000000000000000000000000..504ab4f177c539bbbb44a31a7f1d0bd3d564a84f --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/round.mjs @@ -0,0 +1,25 @@ +//#region src/math/round.ts +/** +* Rounds a number to a specified precision. +* +* This function takes a number and an optional precision value, and returns the number rounded +* to the specified number of decimal places. +* +* @param {number} value - The number to round. +* @param {number} [precision=0] - The number of decimal places to round to. Defaults to 0. +* @returns {number} The rounded number. +* @throws {Error} Throws an error if `Precision` is not integer. +* +* @example +* const result1 = round(1.2345); // result1 will be 1 +* const result2 = round(1.2345, 2); // result2 will be 1.23 +* const result3 = round(1.2345, 3); // result3 will be 1.235 +* const result4 = round(1.2345, 3.1); // This will throw an error +*/ +function round(value, precision = 0) { + if (!Number.isInteger(precision)) throw new Error("Precision must be an integer."); + const multiplier = Math.pow(10, precision); + return Math.round(value * multiplier) / multiplier; +} +//#endregion +export { round }; diff --git a/tools/ui/node_modules/es-toolkit/dist/math/sum.d.mts b/tools/ui/node_modules/es-toolkit/dist/math/sum.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..6b3f2d80f2c04633c68e8c001fb64e0619827333 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/sum.d.mts @@ -0,0 +1,17 @@ +//#region src/math/sum.d.ts +/** + * Calculates the sum of an array of numbers. + * + * This function takes an array of numbers and returns the sum of all the elements in the array. + * + * @param {number[]} nums - An array of numbers to be summed. + * @returns {number} The sum of all the numbers in the array. + * + * @example + * const numbers = [1, 2, 3, 4, 5]; + * const result = sum(numbers); + * // result will be 15 + */ +declare function sum(nums: readonly number[]): number; +//#endregion +export { sum }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/math/sum.d.ts b/tools/ui/node_modules/es-toolkit/dist/math/sum.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6b3f2d80f2c04633c68e8c001fb64e0619827333 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/sum.d.ts @@ -0,0 +1,17 @@ +//#region src/math/sum.d.ts +/** + * Calculates the sum of an array of numbers. + * + * This function takes an array of numbers and returns the sum of all the elements in the array. + * + * @param {number[]} nums - An array of numbers to be summed. + * @returns {number} The sum of all the numbers in the array. + * + * @example + * const numbers = [1, 2, 3, 4, 5]; + * const result = sum(numbers); + * // result will be 15 + */ +declare function sum(nums: readonly number[]): number; +//#endregion +export { sum }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/math/sum.js b/tools/ui/node_modules/es-toolkit/dist/math/sum.js new file mode 100644 index 0000000000000000000000000000000000000000..d469f8dd16bb00a0b966cb26d327e82d13e87837 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/sum.js @@ -0,0 +1,21 @@ +//#region src/math/sum.ts +/** +* Calculates the sum of an array of numbers. +* +* This function takes an array of numbers and returns the sum of all the elements in the array. +* +* @param {number[]} nums - An array of numbers to be summed. +* @returns {number} The sum of all the numbers in the array. +* +* @example +* const numbers = [1, 2, 3, 4, 5]; +* const result = sum(numbers); +* // result will be 15 +*/ +function sum(nums) { + let result = 0; + for (let i = 0; i < nums.length; i++) result += nums[i]; + return result; +} +//#endregion +exports.sum = sum; diff --git a/tools/ui/node_modules/es-toolkit/dist/math/sum.mjs b/tools/ui/node_modules/es-toolkit/dist/math/sum.mjs new file mode 100644 index 0000000000000000000000000000000000000000..19391c7ac2d4fdba2d780d836c05dc8df2f8f6f4 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/sum.mjs @@ -0,0 +1,21 @@ +//#region src/math/sum.ts +/** +* Calculates the sum of an array of numbers. +* +* This function takes an array of numbers and returns the sum of all the elements in the array. +* +* @param {number[]} nums - An array of numbers to be summed. +* @returns {number} The sum of all the numbers in the array. +* +* @example +* const numbers = [1, 2, 3, 4, 5]; +* const result = sum(numbers); +* // result will be 15 +*/ +function sum(nums) { + let result = 0; + for (let i = 0; i < nums.length; i++) result += nums[i]; + return result; +} +//#endregion +export { sum }; diff --git a/tools/ui/node_modules/es-toolkit/dist/math/sumBy.d.mts b/tools/ui/node_modules/es-toolkit/dist/math/sumBy.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..4568661b1aa5fc5951c016ba840539f4d85be17e --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/sumBy.d.mts @@ -0,0 +1,20 @@ +//#region src/math/sumBy.d.ts +/** + * Calculates the sum of an array of numbers when applying + * the `getValue` function to each element. + * + * If the array is empty, this function returns `0`. + * + * @template T - The type of elements in the array. + * @param {readonly T[]} items - An array to calculate the sum. + * @param {(element: T, index: number) => number} getValue - A function that selects a numeric value from each element. + * It receives the element and its zero‑based index in the array. + * @returns {number} The sum of all the numbers as determined by the `getValue` function. + * + * @example + * sumBy([{ a: 1 }, { a: 2 }, { a: 3 }], (x, i) => x.a * i); // Returns: 8 + * sumBy([], () => 1); // Returns: 0 + */ +declare function sumBy(items: readonly T[], getValue: (element: T, index: number) => number): number; +//#endregion +export { sumBy }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/math/sumBy.d.ts b/tools/ui/node_modules/es-toolkit/dist/math/sumBy.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4568661b1aa5fc5951c016ba840539f4d85be17e --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/sumBy.d.ts @@ -0,0 +1,20 @@ +//#region src/math/sumBy.d.ts +/** + * Calculates the sum of an array of numbers when applying + * the `getValue` function to each element. + * + * If the array is empty, this function returns `0`. + * + * @template T - The type of elements in the array. + * @param {readonly T[]} items - An array to calculate the sum. + * @param {(element: T, index: number) => number} getValue - A function that selects a numeric value from each element. + * It receives the element and its zero‑based index in the array. + * @returns {number} The sum of all the numbers as determined by the `getValue` function. + * + * @example + * sumBy([{ a: 1 }, { a: 2 }, { a: 3 }], (x, i) => x.a * i); // Returns: 8 + * sumBy([], () => 1); // Returns: 0 + */ +declare function sumBy(items: readonly T[], getValue: (element: T, index: number) => number): number; +//#endregion +export { sumBy }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/math/sumBy.js b/tools/ui/node_modules/es-toolkit/dist/math/sumBy.js new file mode 100644 index 0000000000000000000000000000000000000000..4f88a41c74dae86abec2b83e817e5b101cc20c7d --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/sumBy.js @@ -0,0 +1,24 @@ +//#region src/math/sumBy.ts +/** +* Calculates the sum of an array of numbers when applying +* the `getValue` function to each element. +* +* If the array is empty, this function returns `0`. +* +* @template T - The type of elements in the array. +* @param {readonly T[]} items - An array to calculate the sum. +* @param {(element: T, index: number) => number} getValue - A function that selects a numeric value from each element. +* It receives the element and its zero‑based index in the array. +* @returns {number} The sum of all the numbers as determined by the `getValue` function. +* +* @example +* sumBy([{ a: 1 }, { a: 2 }, { a: 3 }], (x, i) => x.a * i); // Returns: 8 +* sumBy([], () => 1); // Returns: 0 +*/ +function sumBy(items, getValue) { + let result = 0; + for (let i = 0; i < items.length; i++) result += getValue(items[i], i); + return result; +} +//#endregion +exports.sumBy = sumBy; diff --git a/tools/ui/node_modules/es-toolkit/dist/math/sumBy.mjs b/tools/ui/node_modules/es-toolkit/dist/math/sumBy.mjs new file mode 100644 index 0000000000000000000000000000000000000000..69838cc1319abbc036a31d2cd4627a0120995d8e --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/math/sumBy.mjs @@ -0,0 +1,24 @@ +//#region src/math/sumBy.ts +/** +* Calculates the sum of an array of numbers when applying +* the `getValue` function to each element. +* +* If the array is empty, this function returns `0`. +* +* @template T - The type of elements in the array. +* @param {readonly T[]} items - An array to calculate the sum. +* @param {(element: T, index: number) => number} getValue - A function that selects a numeric value from each element. +* It receives the element and its zero‑based index in the array. +* @returns {number} The sum of all the numbers as determined by the `getValue` function. +* +* @example +* sumBy([{ a: 1 }, { a: 2 }, { a: 3 }], (x, i) => x.a * i); // Returns: 8 +* sumBy([], () => 1); // Returns: 0 +*/ +function sumBy(items, getValue) { + let result = 0; + for (let i = 0; i < items.length; i++) result += getValue(items[i], i); + return result; +} +//#endregion +export { sumBy }; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/clone.d.mts b/tools/ui/node_modules/es-toolkit/dist/object/clone.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..c32c470141c82a77edfef0eec28e1fb3bef537c8 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/clone.d.mts @@ -0,0 +1,32 @@ +//#region src/object/clone.d.ts +/** + * Creates a shallow clone of the given object. + * + * @template T - The type of the object. + * @param {T} obj - The object to clone. + * @returns {T} - A shallow clone of the given object. + * + * @example + * // Clone a primitive values + * const num = 29; + * const clonedNum = clone(num); + * console.log(clonedNum); // 29 + * console.log(clonedNum === num); // true + * + * @example + * // Clone an array + * const arr = [1, 2, 3]; + * const clonedArr = clone(arr); + * console.log(clonedArr); // [1, 2, 3] + * console.log(clonedArr === arr); // false + * + * @example + * // Clone an object + * const obj = { a: 1, b: 'es-toolkit', c: [1, 2, 3] }; + * const clonedObj = clone(obj); + * console.log(clonedObj); // { a: 1, b: 'es-toolkit', c: [1, 2, 3] } + * console.log(clonedObj === obj); // false + */ +declare function clone(obj: T): T; +//#endregion +export { clone }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/clone.d.ts b/tools/ui/node_modules/es-toolkit/dist/object/clone.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c32c470141c82a77edfef0eec28e1fb3bef537c8 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/clone.d.ts @@ -0,0 +1,32 @@ +//#region src/object/clone.d.ts +/** + * Creates a shallow clone of the given object. + * + * @template T - The type of the object. + * @param {T} obj - The object to clone. + * @returns {T} - A shallow clone of the given object. + * + * @example + * // Clone a primitive values + * const num = 29; + * const clonedNum = clone(num); + * console.log(clonedNum); // 29 + * console.log(clonedNum === num); // true + * + * @example + * // Clone an array + * const arr = [1, 2, 3]; + * const clonedArr = clone(arr); + * console.log(clonedArr); // [1, 2, 3] + * console.log(clonedArr === arr); // false + * + * @example + * // Clone an object + * const obj = { a: 1, b: 'es-toolkit', c: [1, 2, 3] }; + * const clonedObj = clone(obj); + * console.log(clonedObj); // { a: 1, b: 'es-toolkit', c: [1, 2, 3] } + * console.log(clonedObj === obj); // false + */ +declare function clone(obj: T): T; +//#endregion +export { clone }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/clone.js b/tools/ui/node_modules/es-toolkit/dist/object/clone.js new file mode 100644 index 0000000000000000000000000000000000000000..41c8ee095d673db3a19bab8f8f450bec9c661a2d --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/clone.js @@ -0,0 +1,61 @@ +const require_isPrimitive = require("../predicate/isPrimitive.js"); +const require_isTypedArray = require("../predicate/isTypedArray.js"); +//#region src/object/clone.ts +/** +* Creates a shallow clone of the given object. +* +* @template T - The type of the object. +* @param {T} obj - The object to clone. +* @returns {T} - A shallow clone of the given object. +* +* @example +* // Clone a primitive values +* const num = 29; +* const clonedNum = clone(num); +* console.log(clonedNum); // 29 +* console.log(clonedNum === num); // true +* +* @example +* // Clone an array +* const arr = [1, 2, 3]; +* const clonedArr = clone(arr); +* console.log(clonedArr); // [1, 2, 3] +* console.log(clonedArr === arr); // false +* +* @example +* // Clone an object +* const obj = { a: 1, b: 'es-toolkit', c: [1, 2, 3] }; +* const clonedObj = clone(obj); +* console.log(clonedObj); // { a: 1, b: 'es-toolkit', c: [1, 2, 3] } +* console.log(clonedObj === obj); // false +*/ +function clone(obj) { + if (require_isPrimitive.isPrimitive(obj)) return obj; + if (Array.isArray(obj) || require_isTypedArray.isTypedArray(obj) || obj instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && obj instanceof SharedArrayBuffer) return obj.slice(0); + const prototype = Object.getPrototypeOf(obj); + if (prototype == null) return Object.assign(Object.create(prototype), obj); + const Constructor = prototype.constructor; + if (obj instanceof Date || obj instanceof Map || obj instanceof Set) return new Constructor(obj); + if (obj instanceof RegExp) { + const newRegExp = new Constructor(obj); + newRegExp.lastIndex = obj.lastIndex; + return newRegExp; + } + if (obj instanceof DataView) return new Constructor(obj.buffer.slice(0)); + if (obj instanceof Error) { + let newError; + if (obj instanceof AggregateError) newError = new Constructor(obj.errors, obj.message, { cause: obj.cause }); + else newError = new Constructor(obj.message, { cause: obj.cause }); + newError.stack = obj.stack; + Object.assign(newError, obj); + return newError; + } + if (typeof File !== "undefined" && obj instanceof File) return new Constructor([obj], obj.name, { + type: obj.type, + lastModified: obj.lastModified + }); + if (typeof obj === "object") return Object.assign(Object.create(prototype), obj); + return obj; +} +//#endregion +exports.clone = clone; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/clone.mjs b/tools/ui/node_modules/es-toolkit/dist/object/clone.mjs new file mode 100644 index 0000000000000000000000000000000000000000..23559c1d0e759eb3310c83e14f61002cec254577 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/clone.mjs @@ -0,0 +1,61 @@ +import { isPrimitive } from "../predicate/isPrimitive.mjs"; +import { isTypedArray } from "../predicate/isTypedArray.mjs"; +//#region src/object/clone.ts +/** +* Creates a shallow clone of the given object. +* +* @template T - The type of the object. +* @param {T} obj - The object to clone. +* @returns {T} - A shallow clone of the given object. +* +* @example +* // Clone a primitive values +* const num = 29; +* const clonedNum = clone(num); +* console.log(clonedNum); // 29 +* console.log(clonedNum === num); // true +* +* @example +* // Clone an array +* const arr = [1, 2, 3]; +* const clonedArr = clone(arr); +* console.log(clonedArr); // [1, 2, 3] +* console.log(clonedArr === arr); // false +* +* @example +* // Clone an object +* const obj = { a: 1, b: 'es-toolkit', c: [1, 2, 3] }; +* const clonedObj = clone(obj); +* console.log(clonedObj); // { a: 1, b: 'es-toolkit', c: [1, 2, 3] } +* console.log(clonedObj === obj); // false +*/ +function clone(obj) { + if (isPrimitive(obj)) return obj; + if (Array.isArray(obj) || isTypedArray(obj) || obj instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && obj instanceof SharedArrayBuffer) return obj.slice(0); + const prototype = Object.getPrototypeOf(obj); + if (prototype == null) return Object.assign(Object.create(prototype), obj); + const Constructor = prototype.constructor; + if (obj instanceof Date || obj instanceof Map || obj instanceof Set) return new Constructor(obj); + if (obj instanceof RegExp) { + const newRegExp = new Constructor(obj); + newRegExp.lastIndex = obj.lastIndex; + return newRegExp; + } + if (obj instanceof DataView) return new Constructor(obj.buffer.slice(0)); + if (obj instanceof Error) { + let newError; + if (obj instanceof AggregateError) newError = new Constructor(obj.errors, obj.message, { cause: obj.cause }); + else newError = new Constructor(obj.message, { cause: obj.cause }); + newError.stack = obj.stack; + Object.assign(newError, obj); + return newError; + } + if (typeof File !== "undefined" && obj instanceof File) return new Constructor([obj], obj.name, { + type: obj.type, + lastModified: obj.lastModified + }); + if (typeof obj === "object") return Object.assign(Object.create(prototype), obj); + return obj; +} +//#endregion +export { clone }; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/cloneDeep.d.mts b/tools/ui/node_modules/es-toolkit/dist/object/cloneDeep.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..9232e351ef64087c4653509435d378122fb4a6bb --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/cloneDeep.d.mts @@ -0,0 +1,50 @@ +//#region src/object/cloneDeep.d.ts +/** + * Creates a deep clone of the given object. + * + * @template T - The type of the object. + * @param {T} obj - The object to clone. + * @returns {T} - A deep clone of the given object. + * + * @example + * // Clone a primitive values + * const num = 29; + * const clonedNum = cloneDeep(num); + * console.log(clonedNum); // 29 + * console.log(clonedNum === num); // true + * + * @example + * // Clone an array + * const arr = [1, 2, 3]; + * const clonedArr = cloneDeep(arr); + * console.log(clonedArr); // [1, 2, 3] + * console.log(clonedArr === arr); // false + * + * @example + * // Clone an array with nested objects + * const arr = [1, { a: 1 }, [1, 2, 3]]; + * const clonedArr = cloneDeep(arr); + * arr[1].a = 2; + * console.log(arr); // [1, { a: 2 }, [1, 2, 3]] + * console.log(clonedArr); // [1, { a: 1 }, [1, 2, 3]] + * console.log(clonedArr === arr); // false + * + * @example + * // Clone an object + * const obj = { a: 1, b: 'es-toolkit', c: [1, 2, 3] }; + * const clonedObj = cloneDeep(obj); + * console.log(clonedObj); // { a: 1, b: 'es-toolkit', c: [1, 2, 3] } + * console.log(clonedObj === obj); // false + * + * @example + * // Clone an object with nested objects + * const obj = { a: 1, b: { c: 1 } }; + * const clonedObj = cloneDeep(obj); + * obj.b.c = 2; + * console.log(obj); // { a: 1, b: { c: 2 } } + * console.log(clonedObj); // { a: 1, b: { c: 1 } } + * console.log(clonedObj === obj); // false + */ +declare function cloneDeep(obj: T): T; +//#endregion +export { cloneDeep }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/cloneDeep.d.ts b/tools/ui/node_modules/es-toolkit/dist/object/cloneDeep.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9232e351ef64087c4653509435d378122fb4a6bb --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/cloneDeep.d.ts @@ -0,0 +1,50 @@ +//#region src/object/cloneDeep.d.ts +/** + * Creates a deep clone of the given object. + * + * @template T - The type of the object. + * @param {T} obj - The object to clone. + * @returns {T} - A deep clone of the given object. + * + * @example + * // Clone a primitive values + * const num = 29; + * const clonedNum = cloneDeep(num); + * console.log(clonedNum); // 29 + * console.log(clonedNum === num); // true + * + * @example + * // Clone an array + * const arr = [1, 2, 3]; + * const clonedArr = cloneDeep(arr); + * console.log(clonedArr); // [1, 2, 3] + * console.log(clonedArr === arr); // false + * + * @example + * // Clone an array with nested objects + * const arr = [1, { a: 1 }, [1, 2, 3]]; + * const clonedArr = cloneDeep(arr); + * arr[1].a = 2; + * console.log(arr); // [1, { a: 2 }, [1, 2, 3]] + * console.log(clonedArr); // [1, { a: 1 }, [1, 2, 3]] + * console.log(clonedArr === arr); // false + * + * @example + * // Clone an object + * const obj = { a: 1, b: 'es-toolkit', c: [1, 2, 3] }; + * const clonedObj = cloneDeep(obj); + * console.log(clonedObj); // { a: 1, b: 'es-toolkit', c: [1, 2, 3] } + * console.log(clonedObj === obj); // false + * + * @example + * // Clone an object with nested objects + * const obj = { a: 1, b: { c: 1 } }; + * const clonedObj = cloneDeep(obj); + * obj.b.c = 2; + * console.log(obj); // { a: 1, b: { c: 2 } } + * console.log(clonedObj); // { a: 1, b: { c: 1 } } + * console.log(clonedObj === obj); // false + */ +declare function cloneDeep(obj: T): T; +//#endregion +export { cloneDeep }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/cloneDeep.js b/tools/ui/node_modules/es-toolkit/dist/object/cloneDeep.js new file mode 100644 index 0000000000000000000000000000000000000000..3e1c58146f62c3161931d44759d48655cf17953d --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/cloneDeep.js @@ -0,0 +1,53 @@ +const require_cloneDeepWith = require("./cloneDeepWith.js"); +//#region src/object/cloneDeep.ts +/** +* Creates a deep clone of the given object. +* +* @template T - The type of the object. +* @param {T} obj - The object to clone. +* @returns {T} - A deep clone of the given object. +* +* @example +* // Clone a primitive values +* const num = 29; +* const clonedNum = cloneDeep(num); +* console.log(clonedNum); // 29 +* console.log(clonedNum === num); // true +* +* @example +* // Clone an array +* const arr = [1, 2, 3]; +* const clonedArr = cloneDeep(arr); +* console.log(clonedArr); // [1, 2, 3] +* console.log(clonedArr === arr); // false +* +* @example +* // Clone an array with nested objects +* const arr = [1, { a: 1 }, [1, 2, 3]]; +* const clonedArr = cloneDeep(arr); +* arr[1].a = 2; +* console.log(arr); // [1, { a: 2 }, [1, 2, 3]] +* console.log(clonedArr); // [1, { a: 1 }, [1, 2, 3]] +* console.log(clonedArr === arr); // false +* +* @example +* // Clone an object +* const obj = { a: 1, b: 'es-toolkit', c: [1, 2, 3] }; +* const clonedObj = cloneDeep(obj); +* console.log(clonedObj); // { a: 1, b: 'es-toolkit', c: [1, 2, 3] } +* console.log(clonedObj === obj); // false +* +* @example +* // Clone an object with nested objects +* const obj = { a: 1, b: { c: 1 } }; +* const clonedObj = cloneDeep(obj); +* obj.b.c = 2; +* console.log(obj); // { a: 1, b: { c: 2 } } +* console.log(clonedObj); // { a: 1, b: { c: 1 } } +* console.log(clonedObj === obj); // false +*/ +function cloneDeep(obj) { + return require_cloneDeepWith.cloneDeepWithImpl(obj, void 0, obj, /* @__PURE__ */ new Map(), void 0); +} +//#endregion +exports.cloneDeep = cloneDeep; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/cloneDeep.mjs b/tools/ui/node_modules/es-toolkit/dist/object/cloneDeep.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e56695f47afa9ecae9bf5ae28002ac5f57c7ad72 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/cloneDeep.mjs @@ -0,0 +1,53 @@ +import { cloneDeepWithImpl } from "./cloneDeepWith.mjs"; +//#region src/object/cloneDeep.ts +/** +* Creates a deep clone of the given object. +* +* @template T - The type of the object. +* @param {T} obj - The object to clone. +* @returns {T} - A deep clone of the given object. +* +* @example +* // Clone a primitive values +* const num = 29; +* const clonedNum = cloneDeep(num); +* console.log(clonedNum); // 29 +* console.log(clonedNum === num); // true +* +* @example +* // Clone an array +* const arr = [1, 2, 3]; +* const clonedArr = cloneDeep(arr); +* console.log(clonedArr); // [1, 2, 3] +* console.log(clonedArr === arr); // false +* +* @example +* // Clone an array with nested objects +* const arr = [1, { a: 1 }, [1, 2, 3]]; +* const clonedArr = cloneDeep(arr); +* arr[1].a = 2; +* console.log(arr); // [1, { a: 2 }, [1, 2, 3]] +* console.log(clonedArr); // [1, { a: 1 }, [1, 2, 3]] +* console.log(clonedArr === arr); // false +* +* @example +* // Clone an object +* const obj = { a: 1, b: 'es-toolkit', c: [1, 2, 3] }; +* const clonedObj = cloneDeep(obj); +* console.log(clonedObj); // { a: 1, b: 'es-toolkit', c: [1, 2, 3] } +* console.log(clonedObj === obj); // false +* +* @example +* // Clone an object with nested objects +* const obj = { a: 1, b: { c: 1 } }; +* const clonedObj = cloneDeep(obj); +* obj.b.c = 2; +* console.log(obj); // { a: 1, b: { c: 2 } } +* console.log(clonedObj); // { a: 1, b: { c: 1 } } +* console.log(clonedObj === obj); // false +*/ +function cloneDeep(obj) { + return cloneDeepWithImpl(obj, void 0, obj, /* @__PURE__ */ new Map(), void 0); +} +//#endregion +export { cloneDeep }; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/cloneDeepWith.d.mts b/tools/ui/node_modules/es-toolkit/dist/object/cloneDeepWith.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..c8fbcce5f89c39a4e971a0f39ca651b25ffd31d6 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/cloneDeepWith.d.mts @@ -0,0 +1,46 @@ +//#region src/object/cloneDeepWith.d.ts +/** + * Deeply clones the given object. + * + * You can customize the deep cloning process using the `cloneValue` function. + * The function takes the current value `value`, the property name `key`, and the entire object `obj` as arguments. + * If the function returns a value, that value is used; + * if it returns `undefined`, the default cloning method is used. + * + * @template T - The type of the object. + * @param {T} obj - The object to clone. + * @param {Function} [cloneValue] - A function to customize the cloning process. + * @returns {T} - A deep clone of the given object. + * + * @example + * // Clone a primitive value + * const num = 29; + * const clonedNum = cloneDeepWith(num); + * console.log(clonedNum); // 29 + * console.log(clonedNum === num); // true + * + * @example + * // Clone an object with a customizer + * const obj = { a: 1, b: 2 }; + * const clonedObj = cloneDeepWith(obj, (value) => { + * if (typeof value === 'number') { + * return value * 2; // Double the number + * } + * }); + * console.log(clonedObj); // { a: 2, b: 4 } + * console.log(clonedObj === obj); // false + * + * @example + * // Clone an array with a customizer + * const arr = [1, 2, 3]; + * const clonedArr = cloneDeepWith(arr, (value) => { + * return value + 1; // Increment each value + * }); + * console.log(clonedArr); // [2, 3, 4] + * console.log(clonedArr === arr); // false + */ +declare function cloneDeepWith(obj: T, cloneValue: (value: any, key: PropertyKey | undefined, obj: T, stack: Map) => any): T; +declare function cloneDeepWithImpl(valueToClone: any, keyToClone: PropertyKey | undefined, objectToClone: T, stack?: Map, cloneValue?: ((value: any, key: PropertyKey | undefined, obj: T, stack: Map) => any) | undefined): T; +declare function copyProperties(target: any, source: any, objectToClone?: T, stack?: Map | undefined, cloneValue?: ((value: any, key: PropertyKey | undefined, obj: T, stack: Map) => any) | undefined): void; +//#endregion +export { cloneDeepWith }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/cloneDeepWith.d.ts b/tools/ui/node_modules/es-toolkit/dist/object/cloneDeepWith.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c8fbcce5f89c39a4e971a0f39ca651b25ffd31d6 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/cloneDeepWith.d.ts @@ -0,0 +1,46 @@ +//#region src/object/cloneDeepWith.d.ts +/** + * Deeply clones the given object. + * + * You can customize the deep cloning process using the `cloneValue` function. + * The function takes the current value `value`, the property name `key`, and the entire object `obj` as arguments. + * If the function returns a value, that value is used; + * if it returns `undefined`, the default cloning method is used. + * + * @template T - The type of the object. + * @param {T} obj - The object to clone. + * @param {Function} [cloneValue] - A function to customize the cloning process. + * @returns {T} - A deep clone of the given object. + * + * @example + * // Clone a primitive value + * const num = 29; + * const clonedNum = cloneDeepWith(num); + * console.log(clonedNum); // 29 + * console.log(clonedNum === num); // true + * + * @example + * // Clone an object with a customizer + * const obj = { a: 1, b: 2 }; + * const clonedObj = cloneDeepWith(obj, (value) => { + * if (typeof value === 'number') { + * return value * 2; // Double the number + * } + * }); + * console.log(clonedObj); // { a: 2, b: 4 } + * console.log(clonedObj === obj); // false + * + * @example + * // Clone an array with a customizer + * const arr = [1, 2, 3]; + * const clonedArr = cloneDeepWith(arr, (value) => { + * return value + 1; // Increment each value + * }); + * console.log(clonedArr); // [2, 3, 4] + * console.log(clonedArr === arr); // false + */ +declare function cloneDeepWith(obj: T, cloneValue: (value: any, key: PropertyKey | undefined, obj: T, stack: Map) => any): T; +declare function cloneDeepWithImpl(valueToClone: any, keyToClone: PropertyKey | undefined, objectToClone: T, stack?: Map, cloneValue?: ((value: any, key: PropertyKey | undefined, obj: T, stack: Map) => any) | undefined): T; +declare function copyProperties(target: any, source: any, objectToClone?: T, stack?: Map | undefined, cloneValue?: ((value: any, key: PropertyKey | undefined, obj: T, stack: Map) => any) | undefined): void; +//#endregion +export { cloneDeepWith }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/cloneDeepWith.js b/tools/ui/node_modules/es-toolkit/dist/object/cloneDeepWith.js new file mode 100644 index 0000000000000000000000000000000000000000..1b17e301daab30468182b729b6ba1054574ddadd --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/cloneDeepWith.js @@ -0,0 +1,183 @@ +const require_isPrimitive = require("../predicate/isPrimitive.js"); +const require_isTypedArray = require("../predicate/isTypedArray.js"); +const require_getSymbols = require("../compat/_internal/getSymbols.js"); +const require_getTag = require("../compat/_internal/getTag.js"); +const require_tags = require("../compat/_internal/tags.js"); +const require_isBuffer = require("../predicate/isBuffer.js"); +//#region src/object/cloneDeepWith.ts +/** +* Deeply clones the given object. +* +* You can customize the deep cloning process using the `cloneValue` function. +* The function takes the current value `value`, the property name `key`, and the entire object `obj` as arguments. +* If the function returns a value, that value is used; +* if it returns `undefined`, the default cloning method is used. +* +* @template T - The type of the object. +* @param {T} obj - The object to clone. +* @param {Function} [cloneValue] - A function to customize the cloning process. +* @returns {T} - A deep clone of the given object. +* +* @example +* // Clone a primitive value +* const num = 29; +* const clonedNum = cloneDeepWith(num); +* console.log(clonedNum); // 29 +* console.log(clonedNum === num); // true +* +* @example +* // Clone an object with a customizer +* const obj = { a: 1, b: 2 }; +* const clonedObj = cloneDeepWith(obj, (value) => { +* if (typeof value === 'number') { +* return value * 2; // Double the number +* } +* }); +* console.log(clonedObj); // { a: 2, b: 4 } +* console.log(clonedObj === obj); // false +* +* @example +* // Clone an array with a customizer +* const arr = [1, 2, 3]; +* const clonedArr = cloneDeepWith(arr, (value) => { +* return value + 1; // Increment each value +* }); +* console.log(clonedArr); // [2, 3, 4] +* console.log(clonedArr === arr); // false +*/ +function cloneDeepWith(obj, cloneValue) { + return cloneDeepWithImpl(obj, void 0, obj, /* @__PURE__ */ new Map(), cloneValue); +} +function cloneDeepWithImpl(valueToClone, keyToClone, objectToClone, stack = /* @__PURE__ */ new Map(), cloneValue = void 0) { + const cloned = cloneValue?.(valueToClone, keyToClone, objectToClone, stack); + if (cloned !== void 0) return cloned; + if (require_isPrimitive.isPrimitive(valueToClone)) return valueToClone; + if (stack.has(valueToClone)) return stack.get(valueToClone); + if (Array.isArray(valueToClone)) { + const result = new Array(valueToClone.length); + stack.set(valueToClone, result); + for (let i = 0; i < valueToClone.length; i++) result[i] = cloneDeepWithImpl(valueToClone[i], i, objectToClone, stack, cloneValue); + if (Object.hasOwn(valueToClone, "index")) result.index = valueToClone.index; + if (Object.hasOwn(valueToClone, "input")) result.input = valueToClone.input; + return result; + } + if (valueToClone instanceof Date) return new Date(valueToClone.getTime()); + if (valueToClone instanceof RegExp) { + const result = new RegExp(valueToClone.source, valueToClone.flags); + result.lastIndex = valueToClone.lastIndex; + return result; + } + if (valueToClone instanceof Map) { + const result = /* @__PURE__ */ new Map(); + stack.set(valueToClone, result); + for (const [key, value] of valueToClone) result.set(key, cloneDeepWithImpl(value, key, objectToClone, stack, cloneValue)); + return result; + } + if (valueToClone instanceof Set) { + const result = /* @__PURE__ */ new Set(); + stack.set(valueToClone, result); + for (const value of valueToClone) result.add(cloneDeepWithImpl(value, void 0, objectToClone, stack, cloneValue)); + return result; + } + if (require_isBuffer.isBuffer(valueToClone)) return valueToClone.subarray(); + if (require_isTypedArray.isTypedArray(valueToClone)) { + const result = new (Object.getPrototypeOf(valueToClone)).constructor(valueToClone.length); + stack.set(valueToClone, result); + for (let i = 0; i < valueToClone.length; i++) result[i] = cloneDeepWithImpl(valueToClone[i], i, objectToClone, stack, cloneValue); + return result; + } + if (valueToClone instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && valueToClone instanceof SharedArrayBuffer) return valueToClone.slice(0); + if (valueToClone instanceof DataView) { + const result = new DataView(valueToClone.buffer.slice(0), valueToClone.byteOffset, valueToClone.byteLength); + stack.set(valueToClone, result); + copyProperties(result, valueToClone, objectToClone, stack, cloneValue); + return result; + } + if (typeof File !== "undefined" && valueToClone instanceof File) { + const result = new File([valueToClone], valueToClone.name, { type: valueToClone.type }); + stack.set(valueToClone, result); + copyProperties(result, valueToClone, objectToClone, stack, cloneValue); + return result; + } + if (typeof Blob !== "undefined" && valueToClone instanceof Blob) { + const result = new Blob([valueToClone], { type: valueToClone.type }); + stack.set(valueToClone, result); + copyProperties(result, valueToClone, objectToClone, stack, cloneValue); + return result; + } + if (valueToClone instanceof Error) { + const result = structuredClone(valueToClone); + stack.set(valueToClone, result); + result.message = valueToClone.message; + result.name = valueToClone.name; + result.stack = valueToClone.stack; + result.cause = valueToClone.cause; + result.constructor = valueToClone.constructor; + copyProperties(result, valueToClone, objectToClone, stack, cloneValue); + return result; + } + if (valueToClone instanceof Boolean) { + const result = new Boolean(valueToClone.valueOf()); + stack.set(valueToClone, result); + copyProperties(result, valueToClone, objectToClone, stack, cloneValue); + return result; + } + if (valueToClone instanceof Number) { + const result = new Number(valueToClone.valueOf()); + stack.set(valueToClone, result); + copyProperties(result, valueToClone, objectToClone, stack, cloneValue); + return result; + } + if (valueToClone instanceof String) { + const result = new String(valueToClone.valueOf()); + stack.set(valueToClone, result); + copyProperties(result, valueToClone, objectToClone, stack, cloneValue); + return result; + } + if (typeof valueToClone === "object" && isCloneableObject(valueToClone)) { + const result = Object.create(Object.getPrototypeOf(valueToClone)); + stack.set(valueToClone, result); + copyProperties(result, valueToClone, objectToClone, stack, cloneValue); + return result; + } + return valueToClone; +} +function copyProperties(target, source, objectToClone = target, stack, cloneValue) { + const keys = [...Object.keys(source), ...require_getSymbols.getSymbols(source)]; + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const descriptor = Object.getOwnPropertyDescriptor(target, key); + if (descriptor == null || descriptor.writable) target[key] = cloneDeepWithImpl(source[key], key, objectToClone, stack, cloneValue); + } +} +function isCloneableObject(object) { + switch (require_getTag.getTag(object)) { + case require_tags.argumentsTag: + case require_tags.arrayTag: + case require_tags.arrayBufferTag: + case require_tags.dataViewTag: + case require_tags.booleanTag: + case require_tags.dateTag: + case require_tags.float32ArrayTag: + case require_tags.float64ArrayTag: + case require_tags.int8ArrayTag: + case require_tags.int16ArrayTag: + case require_tags.int32ArrayTag: + case require_tags.mapTag: + case require_tags.numberTag: + case require_tags.objectTag: + case require_tags.regexpTag: + case require_tags.setTag: + case require_tags.stringTag: + case require_tags.symbolTag: + case require_tags.uint8ArrayTag: + case require_tags.uint8ClampedArrayTag: + case require_tags.uint16ArrayTag: + case require_tags.uint32ArrayTag: return true; + default: return false; + } +} +//#endregion +exports.cloneDeepWith = cloneDeepWith; +exports.cloneDeepWithImpl = cloneDeepWithImpl; +exports.copyProperties = copyProperties; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/cloneDeepWith.mjs b/tools/ui/node_modules/es-toolkit/dist/object/cloneDeepWith.mjs new file mode 100644 index 0000000000000000000000000000000000000000..9d047131beac640061a1d17eb6c010f9a8d5a4c0 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/cloneDeepWith.mjs @@ -0,0 +1,181 @@ +import { isPrimitive } from "../predicate/isPrimitive.mjs"; +import { isTypedArray } from "../predicate/isTypedArray.mjs"; +import { getSymbols } from "../compat/_internal/getSymbols.mjs"; +import { getTag } from "../compat/_internal/getTag.mjs"; +import { argumentsTag, arrayBufferTag, arrayTag, booleanTag, dataViewTag, dateTag, float32ArrayTag, float64ArrayTag, int16ArrayTag, int32ArrayTag, int8ArrayTag, mapTag, numberTag, objectTag, regexpTag, setTag, stringTag, symbolTag, uint16ArrayTag, uint32ArrayTag, uint8ArrayTag, uint8ClampedArrayTag } from "../compat/_internal/tags.mjs"; +import { isBuffer } from "../predicate/isBuffer.mjs"; +//#region src/object/cloneDeepWith.ts +/** +* Deeply clones the given object. +* +* You can customize the deep cloning process using the `cloneValue` function. +* The function takes the current value `value`, the property name `key`, and the entire object `obj` as arguments. +* If the function returns a value, that value is used; +* if it returns `undefined`, the default cloning method is used. +* +* @template T - The type of the object. +* @param {T} obj - The object to clone. +* @param {Function} [cloneValue] - A function to customize the cloning process. +* @returns {T} - A deep clone of the given object. +* +* @example +* // Clone a primitive value +* const num = 29; +* const clonedNum = cloneDeepWith(num); +* console.log(clonedNum); // 29 +* console.log(clonedNum === num); // true +* +* @example +* // Clone an object with a customizer +* const obj = { a: 1, b: 2 }; +* const clonedObj = cloneDeepWith(obj, (value) => { +* if (typeof value === 'number') { +* return value * 2; // Double the number +* } +* }); +* console.log(clonedObj); // { a: 2, b: 4 } +* console.log(clonedObj === obj); // false +* +* @example +* // Clone an array with a customizer +* const arr = [1, 2, 3]; +* const clonedArr = cloneDeepWith(arr, (value) => { +* return value + 1; // Increment each value +* }); +* console.log(clonedArr); // [2, 3, 4] +* console.log(clonedArr === arr); // false +*/ +function cloneDeepWith(obj, cloneValue) { + return cloneDeepWithImpl(obj, void 0, obj, /* @__PURE__ */ new Map(), cloneValue); +} +function cloneDeepWithImpl(valueToClone, keyToClone, objectToClone, stack = /* @__PURE__ */ new Map(), cloneValue = void 0) { + const cloned = cloneValue?.(valueToClone, keyToClone, objectToClone, stack); + if (cloned !== void 0) return cloned; + if (isPrimitive(valueToClone)) return valueToClone; + if (stack.has(valueToClone)) return stack.get(valueToClone); + if (Array.isArray(valueToClone)) { + const result = new Array(valueToClone.length); + stack.set(valueToClone, result); + for (let i = 0; i < valueToClone.length; i++) result[i] = cloneDeepWithImpl(valueToClone[i], i, objectToClone, stack, cloneValue); + if (Object.hasOwn(valueToClone, "index")) result.index = valueToClone.index; + if (Object.hasOwn(valueToClone, "input")) result.input = valueToClone.input; + return result; + } + if (valueToClone instanceof Date) return new Date(valueToClone.getTime()); + if (valueToClone instanceof RegExp) { + const result = new RegExp(valueToClone.source, valueToClone.flags); + result.lastIndex = valueToClone.lastIndex; + return result; + } + if (valueToClone instanceof Map) { + const result = /* @__PURE__ */ new Map(); + stack.set(valueToClone, result); + for (const [key, value] of valueToClone) result.set(key, cloneDeepWithImpl(value, key, objectToClone, stack, cloneValue)); + return result; + } + if (valueToClone instanceof Set) { + const result = /* @__PURE__ */ new Set(); + stack.set(valueToClone, result); + for (const value of valueToClone) result.add(cloneDeepWithImpl(value, void 0, objectToClone, stack, cloneValue)); + return result; + } + if (isBuffer(valueToClone)) return valueToClone.subarray(); + if (isTypedArray(valueToClone)) { + const result = new (Object.getPrototypeOf(valueToClone)).constructor(valueToClone.length); + stack.set(valueToClone, result); + for (let i = 0; i < valueToClone.length; i++) result[i] = cloneDeepWithImpl(valueToClone[i], i, objectToClone, stack, cloneValue); + return result; + } + if (valueToClone instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && valueToClone instanceof SharedArrayBuffer) return valueToClone.slice(0); + if (valueToClone instanceof DataView) { + const result = new DataView(valueToClone.buffer.slice(0), valueToClone.byteOffset, valueToClone.byteLength); + stack.set(valueToClone, result); + copyProperties(result, valueToClone, objectToClone, stack, cloneValue); + return result; + } + if (typeof File !== "undefined" && valueToClone instanceof File) { + const result = new File([valueToClone], valueToClone.name, { type: valueToClone.type }); + stack.set(valueToClone, result); + copyProperties(result, valueToClone, objectToClone, stack, cloneValue); + return result; + } + if (typeof Blob !== "undefined" && valueToClone instanceof Blob) { + const result = new Blob([valueToClone], { type: valueToClone.type }); + stack.set(valueToClone, result); + copyProperties(result, valueToClone, objectToClone, stack, cloneValue); + return result; + } + if (valueToClone instanceof Error) { + const result = structuredClone(valueToClone); + stack.set(valueToClone, result); + result.message = valueToClone.message; + result.name = valueToClone.name; + result.stack = valueToClone.stack; + result.cause = valueToClone.cause; + result.constructor = valueToClone.constructor; + copyProperties(result, valueToClone, objectToClone, stack, cloneValue); + return result; + } + if (valueToClone instanceof Boolean) { + const result = new Boolean(valueToClone.valueOf()); + stack.set(valueToClone, result); + copyProperties(result, valueToClone, objectToClone, stack, cloneValue); + return result; + } + if (valueToClone instanceof Number) { + const result = new Number(valueToClone.valueOf()); + stack.set(valueToClone, result); + copyProperties(result, valueToClone, objectToClone, stack, cloneValue); + return result; + } + if (valueToClone instanceof String) { + const result = new String(valueToClone.valueOf()); + stack.set(valueToClone, result); + copyProperties(result, valueToClone, objectToClone, stack, cloneValue); + return result; + } + if (typeof valueToClone === "object" && isCloneableObject(valueToClone)) { + const result = Object.create(Object.getPrototypeOf(valueToClone)); + stack.set(valueToClone, result); + copyProperties(result, valueToClone, objectToClone, stack, cloneValue); + return result; + } + return valueToClone; +} +function copyProperties(target, source, objectToClone = target, stack, cloneValue) { + const keys = [...Object.keys(source), ...getSymbols(source)]; + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const descriptor = Object.getOwnPropertyDescriptor(target, key); + if (descriptor == null || descriptor.writable) target[key] = cloneDeepWithImpl(source[key], key, objectToClone, stack, cloneValue); + } +} +function isCloneableObject(object) { + switch (getTag(object)) { + case argumentsTag: + case arrayTag: + case arrayBufferTag: + case dataViewTag: + case booleanTag: + case dateTag: + case float32ArrayTag: + case float64ArrayTag: + case int8ArrayTag: + case int16ArrayTag: + case int32ArrayTag: + case mapTag: + case numberTag: + case objectTag: + case regexpTag: + case setTag: + case stringTag: + case symbolTag: + case uint8ArrayTag: + case uint8ClampedArrayTag: + case uint16ArrayTag: + case uint32ArrayTag: return true; + default: return false; + } +} +//#endregion +export { cloneDeepWith, cloneDeepWithImpl, copyProperties }; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/findKey.d.mts b/tools/ui/node_modules/es-toolkit/dist/object/findKey.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..d35de1a46746d5a34f386b13eb1822d4a9692a09 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/findKey.d.mts @@ -0,0 +1,22 @@ +//#region src/object/findKey.d.ts +/** + * Finds the key of the first element in the object that satisfies the provided testing function. + * + * @param {T} obj - The object to search. + * @param {(value: T[keyof T], key: keyof T, obj: T) => boolean} predicate - The function to execute on each value in the object. It takes three arguments: + * - value: The current value being processed in the object. + * - key: The key of the current value being processed in the object. + * - obj: The object that findKey was called upon. + * @returns {keyof T | undefined} The key of the first element in the object that passes the test, or undefined if no element passes. + * + * @example + * const users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * findKey(users, function(o) { return o.age < 40; }); => 'barney' + */ +declare function findKey>(obj: T, predicate: (value: T[keyof T], key: keyof T, obj: T) => boolean): keyof T | undefined; +//#endregion +export { findKey }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/findKey.d.ts b/tools/ui/node_modules/es-toolkit/dist/object/findKey.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d35de1a46746d5a34f386b13eb1822d4a9692a09 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/findKey.d.ts @@ -0,0 +1,22 @@ +//#region src/object/findKey.d.ts +/** + * Finds the key of the first element in the object that satisfies the provided testing function. + * + * @param {T} obj - The object to search. + * @param {(value: T[keyof T], key: keyof T, obj: T) => boolean} predicate - The function to execute on each value in the object. It takes three arguments: + * - value: The current value being processed in the object. + * - key: The key of the current value being processed in the object. + * - obj: The object that findKey was called upon. + * @returns {keyof T | undefined} The key of the first element in the object that passes the test, or undefined if no element passes. + * + * @example + * const users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * findKey(users, function(o) { return o.age < 40; }); => 'barney' + */ +declare function findKey>(obj: T, predicate: (value: T[keyof T], key: keyof T, obj: T) => boolean): keyof T | undefined; +//#endregion +export { findKey }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/findKey.js b/tools/ui/node_modules/es-toolkit/dist/object/findKey.js new file mode 100644 index 0000000000000000000000000000000000000000..98df7eb8f087c85524425d43fa3d7d674932aad2 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/findKey.js @@ -0,0 +1,24 @@ +//#region src/object/findKey.ts +/** +* Finds the key of the first element in the object that satisfies the provided testing function. +* +* @param {T} obj - The object to search. +* @param {(value: T[keyof T], key: keyof T, obj: T) => boolean} predicate - The function to execute on each value in the object. It takes three arguments: +* - value: The current value being processed in the object. +* - key: The key of the current value being processed in the object. +* - obj: The object that findKey was called upon. +* @returns {keyof T | undefined} The key of the first element in the object that passes the test, or undefined if no element passes. +* +* @example +* const users = { +* 'barney': { 'age': 36, 'active': true }, +* 'fred': { 'age': 40, 'active': false }, +* 'pebbles': { 'age': 1, 'active': true } +* }; +* findKey(users, function(o) { return o.age < 40; }); => 'barney' +*/ +function findKey(obj, predicate) { + return Object.keys(obj).find((key) => predicate(obj[key], key, obj)); +} +//#endregion +exports.findKey = findKey; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/findKey.mjs b/tools/ui/node_modules/es-toolkit/dist/object/findKey.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7924328ebb8766afec3bf207b9fdb2d4629016e8 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/findKey.mjs @@ -0,0 +1,24 @@ +//#region src/object/findKey.ts +/** +* Finds the key of the first element in the object that satisfies the provided testing function. +* +* @param {T} obj - The object to search. +* @param {(value: T[keyof T], key: keyof T, obj: T) => boolean} predicate - The function to execute on each value in the object. It takes three arguments: +* - value: The current value being processed in the object. +* - key: The key of the current value being processed in the object. +* - obj: The object that findKey was called upon. +* @returns {keyof T | undefined} The key of the first element in the object that passes the test, or undefined if no element passes. +* +* @example +* const users = { +* 'barney': { 'age': 36, 'active': true }, +* 'fred': { 'age': 40, 'active': false }, +* 'pebbles': { 'age': 1, 'active': true } +* }; +* findKey(users, function(o) { return o.age < 40; }); => 'barney' +*/ +function findKey(obj, predicate) { + return Object.keys(obj).find((key) => predicate(obj[key], key, obj)); +} +//#endregion +export { findKey }; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/flattenObject.d.mts b/tools/ui/node_modules/es-toolkit/dist/object/flattenObject.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..b1efcef24c5ed5c07122546d005ef1b697c0e55c --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/flattenObject.d.mts @@ -0,0 +1,39 @@ +//#region src/object/flattenObject.d.ts +interface FlattenObjectOptions { + /** + * The delimiter to use between nested keys. + * @default '.' + */ + delimiter?: string; +} +/** + * Flattens a nested object into a single level object with delimiter-separated keys. + * + * @param {object} object - The object to flatten. + * @param {string} [options.delimiter='.'] - The delimiter to use between nested keys. + * @returns {Record} - The flattened object. + * + * @example + * const nestedObject = { + * a: { + * b: { + * c: 1 + * } + * }, + * d: [2, 3] + * }; + * + * const flattened = flattenObject(nestedObject); + * console.log(flattened); + * // Output: + * // { + * // 'a.b.c': 1, + * // 'd.0': 2, + * // 'd.1': 3 + * // } + */ +declare function flattenObject(object: object, { + delimiter +}?: FlattenObjectOptions): Record; +//#endregion +export { flattenObject }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/flattenObject.d.ts b/tools/ui/node_modules/es-toolkit/dist/object/flattenObject.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b1efcef24c5ed5c07122546d005ef1b697c0e55c --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/flattenObject.d.ts @@ -0,0 +1,39 @@ +//#region src/object/flattenObject.d.ts +interface FlattenObjectOptions { + /** + * The delimiter to use between nested keys. + * @default '.' + */ + delimiter?: string; +} +/** + * Flattens a nested object into a single level object with delimiter-separated keys. + * + * @param {object} object - The object to flatten. + * @param {string} [options.delimiter='.'] - The delimiter to use between nested keys. + * @returns {Record} - The flattened object. + * + * @example + * const nestedObject = { + * a: { + * b: { + * c: 1 + * } + * }, + * d: [2, 3] + * }; + * + * const flattened = flattenObject(nestedObject); + * console.log(flattened); + * // Output: + * // { + * // 'a.b.c': 1, + * // 'd.0': 2, + * // 'd.1': 3 + * // } + */ +declare function flattenObject(object: object, { + delimiter +}?: FlattenObjectOptions): Record; +//#endregion +export { flattenObject }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/flattenObject.js b/tools/ui/node_modules/es-toolkit/dist/object/flattenObject.js new file mode 100644 index 0000000000000000000000000000000000000000..c9f549a0f255b530b98431c4dedba6695dac545a --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/flattenObject.js @@ -0,0 +1,52 @@ +const require_isPlainObject = require("../predicate/isPlainObject.js"); +//#region src/object/flattenObject.ts +/** +* Flattens a nested object into a single level object with delimiter-separated keys. +* +* @param {object} object - The object to flatten. +* @param {string} [options.delimiter='.'] - The delimiter to use between nested keys. +* @returns {Record} - The flattened object. +* +* @example +* const nestedObject = { +* a: { +* b: { +* c: 1 +* } +* }, +* d: [2, 3] +* }; +* +* const flattened = flattenObject(nestedObject); +* console.log(flattened); +* // Output: +* // { +* // 'a.b.c': 1, +* // 'd.0': 2, +* // 'd.1': 3 +* // } +*/ +function flattenObject(object, { delimiter = "." } = {}) { + return flattenObjectImpl(object, "", delimiter); +} +function flattenObjectImpl(object, prefix, delimiter) { + const result = {}; + const keys = Object.keys(object); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const value = object[key]; + const prefixedKey = prefix ? `${prefix}${delimiter}${key}` : key; + if (require_isPlainObject.isPlainObject(value) && Object.keys(value).length > 0) { + Object.assign(result, flattenObjectImpl(value, prefixedKey, delimiter)); + continue; + } + if (Array.isArray(value) && value.length > 0) { + Object.assign(result, flattenObjectImpl(value, prefixedKey, delimiter)); + continue; + } + result[prefixedKey] = value; + } + return result; +} +//#endregion +exports.flattenObject = flattenObject; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/flattenObject.mjs b/tools/ui/node_modules/es-toolkit/dist/object/flattenObject.mjs new file mode 100644 index 0000000000000000000000000000000000000000..cd2d1d2d41822aac1b8563610aa04f7b377aa787 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/flattenObject.mjs @@ -0,0 +1,52 @@ +import { isPlainObject } from "../predicate/isPlainObject.mjs"; +//#region src/object/flattenObject.ts +/** +* Flattens a nested object into a single level object with delimiter-separated keys. +* +* @param {object} object - The object to flatten. +* @param {string} [options.delimiter='.'] - The delimiter to use between nested keys. +* @returns {Record} - The flattened object. +* +* @example +* const nestedObject = { +* a: { +* b: { +* c: 1 +* } +* }, +* d: [2, 3] +* }; +* +* const flattened = flattenObject(nestedObject); +* console.log(flattened); +* // Output: +* // { +* // 'a.b.c': 1, +* // 'd.0': 2, +* // 'd.1': 3 +* // } +*/ +function flattenObject(object, { delimiter = "." } = {}) { + return flattenObjectImpl(object, "", delimiter); +} +function flattenObjectImpl(object, prefix, delimiter) { + const result = {}; + const keys = Object.keys(object); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const value = object[key]; + const prefixedKey = prefix ? `${prefix}${delimiter}${key}` : key; + if (isPlainObject(value) && Object.keys(value).length > 0) { + Object.assign(result, flattenObjectImpl(value, prefixedKey, delimiter)); + continue; + } + if (Array.isArray(value) && value.length > 0) { + Object.assign(result, flattenObjectImpl(value, prefixedKey, delimiter)); + continue; + } + result[prefixedKey] = value; + } + return result; +} +//#endregion +export { flattenObject }; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/index.d.mts b/tools/ui/node_modules/es-toolkit/dist/object/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..7fbdfda360b63fd31af27a5f5b9225f178f998d8 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/index.d.mts @@ -0,0 +1,19 @@ +import { clone } from "./clone.mjs"; +import { cloneDeep } from "./cloneDeep.mjs"; +import { cloneDeepWith } from "./cloneDeepWith.mjs"; +import { findKey } from "./findKey.mjs"; +import { flattenObject } from "./flattenObject.mjs"; +import { invert } from "./invert.mjs"; +import { mapKeys } from "./mapKeys.mjs"; +import { mapValues } from "./mapValues.mjs"; +import { merge } from "./merge.mjs"; +import { mergeWith } from "./mergeWith.mjs"; +import { omit } from "./omit.mjs"; +import { omitBy } from "./omitBy.mjs"; +import { pick } from "./pick.mjs"; +import { pickBy } from "./pickBy.mjs"; +import { sortKeys } from "./sortKeys.mjs"; +import { toCamelCaseKeys } from "./toCamelCaseKeys.mjs"; +import { toMerged } from "./toMerged.mjs"; +import { toSnakeCaseKeys } from "./toSnakeCaseKeys.mjs"; +export { clone, cloneDeep, cloneDeepWith, findKey, flattenObject, invert, mapKeys, mapValues, merge, mergeWith, omit, omitBy, pick, pickBy, sortKeys, toCamelCaseKeys, toMerged, toSnakeCaseKeys }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/index.d.ts b/tools/ui/node_modules/es-toolkit/dist/object/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e5e28289c74502f9c2c5a2cafa28a93bfc1b8739 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/index.d.ts @@ -0,0 +1,19 @@ +import { clone } from "./clone.js"; +import { cloneDeep } from "./cloneDeep.js"; +import { cloneDeepWith } from "./cloneDeepWith.js"; +import { findKey } from "./findKey.js"; +import { flattenObject } from "./flattenObject.js"; +import { invert } from "./invert.js"; +import { mapKeys } from "./mapKeys.js"; +import { mapValues } from "./mapValues.js"; +import { merge } from "./merge.js"; +import { mergeWith } from "./mergeWith.js"; +import { omit } from "./omit.js"; +import { omitBy } from "./omitBy.js"; +import { pick } from "./pick.js"; +import { pickBy } from "./pickBy.js"; +import { sortKeys } from "./sortKeys.js"; +import { toCamelCaseKeys } from "./toCamelCaseKeys.js"; +import { toMerged } from "./toMerged.js"; +import { toSnakeCaseKeys } from "./toSnakeCaseKeys.js"; +export { clone, cloneDeep, cloneDeepWith, findKey, flattenObject, invert, mapKeys, mapValues, merge, mergeWith, omit, omitBy, pick, pickBy, sortKeys, toCamelCaseKeys, toMerged, toSnakeCaseKeys }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/index.js b/tools/ui/node_modules/es-toolkit/dist/object/index.js new file mode 100644 index 0000000000000000000000000000000000000000..32aa6f336bd821db084463c4c655e75b77edb53e --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/index.js @@ -0,0 +1,37 @@ +Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); +const require_clone = require("./clone.js"); +const require_cloneDeepWith = require("./cloneDeepWith.js"); +const require_cloneDeep = require("./cloneDeep.js"); +const require_findKey = require("./findKey.js"); +const require_flattenObject = require("./flattenObject.js"); +const require_invert = require("./invert.js"); +const require_mapKeys = require("./mapKeys.js"); +const require_mapValues = require("./mapValues.js"); +const require_merge = require("./merge.js"); +const require_mergeWith = require("./mergeWith.js"); +const require_omit = require("./omit.js"); +const require_omitBy = require("./omitBy.js"); +const require_pick = require("./pick.js"); +const require_pickBy = require("./pickBy.js"); +const require_sortKeys = require("./sortKeys.js"); +const require_toCamelCaseKeys = require("./toCamelCaseKeys.js"); +const require_toMerged = require("./toMerged.js"); +const require_toSnakeCaseKeys = require("./toSnakeCaseKeys.js"); +exports.clone = require_clone.clone; +exports.cloneDeep = require_cloneDeep.cloneDeep; +exports.cloneDeepWith = require_cloneDeepWith.cloneDeepWith; +exports.findKey = require_findKey.findKey; +exports.flattenObject = require_flattenObject.flattenObject; +exports.invert = require_invert.invert; +exports.mapKeys = require_mapKeys.mapKeys; +exports.mapValues = require_mapValues.mapValues; +exports.merge = require_merge.merge; +exports.mergeWith = require_mergeWith.mergeWith; +exports.omit = require_omit.omit; +exports.omitBy = require_omitBy.omitBy; +exports.pick = require_pick.pick; +exports.pickBy = require_pickBy.pickBy; +exports.sortKeys = require_sortKeys.sortKeys; +exports.toCamelCaseKeys = require_toCamelCaseKeys.toCamelCaseKeys; +exports.toMerged = require_toMerged.toMerged; +exports.toSnakeCaseKeys = require_toSnakeCaseKeys.toSnakeCaseKeys; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/index.mjs b/tools/ui/node_modules/es-toolkit/dist/object/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f6bd6523bf38c5dfa4608b71a1f5993b4e3f12e3 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/index.mjs @@ -0,0 +1,19 @@ +import { clone } from "./clone.mjs"; +import { cloneDeepWith } from "./cloneDeepWith.mjs"; +import { cloneDeep } from "./cloneDeep.mjs"; +import { findKey } from "./findKey.mjs"; +import { flattenObject } from "./flattenObject.mjs"; +import { invert } from "./invert.mjs"; +import { mapKeys } from "./mapKeys.mjs"; +import { mapValues } from "./mapValues.mjs"; +import { merge } from "./merge.mjs"; +import { mergeWith } from "./mergeWith.mjs"; +import { omit } from "./omit.mjs"; +import { omitBy } from "./omitBy.mjs"; +import { pick } from "./pick.mjs"; +import { pickBy } from "./pickBy.mjs"; +import { sortKeys } from "./sortKeys.mjs"; +import { toCamelCaseKeys } from "./toCamelCaseKeys.mjs"; +import { toMerged } from "./toMerged.mjs"; +import { toSnakeCaseKeys } from "./toSnakeCaseKeys.mjs"; +export { clone, cloneDeep, cloneDeepWith, findKey, flattenObject, invert, mapKeys, mapValues, merge, mergeWith, omit, omitBy, pick, pickBy, sortKeys, toCamelCaseKeys, toMerged, toSnakeCaseKeys }; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/invert.d.mts b/tools/ui/node_modules/es-toolkit/dist/object/invert.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..9859d441c2f16f19ab958bc113c63e1ec1530a34 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/invert.d.mts @@ -0,0 +1,22 @@ +//#region src/object/invert.d.ts +/** + * Inverts the keys and values of an object. The keys of the input object become the values of the output object and vice versa. + * + * This function takes an object and creates a new object by inverting its keys and values. If the input object has duplicate values, + * the key of the last occurrence will be used as the value for the new key in the output object. It effectively creates a reverse mapping + * of the input object's key-value pairs. + * + * @template K - Type of the keys in the input object (string, number, symbol) + * @template V - Type of the values in the input object (string, number, symbol) + * @param {Record} obj - The input object whose keys and values are to be inverted + * @returns {Record} - A new object with keys and values inverted + * + * @example + * invert({ a: 1, b: 2, c: 3 }); // { 1: 'a', 2: 'b', 3: 'c' } + * invert({ 1: 'a', 2: 'b', 3: 'c' }); // { a: '1', b: '2', c: '3' } + * invert({ a: 1, 2: 'b', c: 3, 4: 'd' }); // { 1: 'a', b: '2', 3: 'c', d: '4' } + * invert({ a: Symbol('sym1'), b: Symbol('sym2') }); // { [Symbol('sym1')]: 'a', [Symbol('sym2')]: 'b' } + */ +declare function invert(obj: Record): Record; +//#endregion +export { invert }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/invert.d.ts b/tools/ui/node_modules/es-toolkit/dist/object/invert.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9859d441c2f16f19ab958bc113c63e1ec1530a34 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/invert.d.ts @@ -0,0 +1,22 @@ +//#region src/object/invert.d.ts +/** + * Inverts the keys and values of an object. The keys of the input object become the values of the output object and vice versa. + * + * This function takes an object and creates a new object by inverting its keys and values. If the input object has duplicate values, + * the key of the last occurrence will be used as the value for the new key in the output object. It effectively creates a reverse mapping + * of the input object's key-value pairs. + * + * @template K - Type of the keys in the input object (string, number, symbol) + * @template V - Type of the values in the input object (string, number, symbol) + * @param {Record} obj - The input object whose keys and values are to be inverted + * @returns {Record} - A new object with keys and values inverted + * + * @example + * invert({ a: 1, b: 2, c: 3 }); // { 1: 'a', 2: 'b', 3: 'c' } + * invert({ 1: 'a', 2: 'b', 3: 'c' }); // { a: '1', b: '2', c: '3' } + * invert({ a: 1, 2: 'b', c: 3, 4: 'd' }); // { 1: 'a', b: '2', 3: 'c', d: '4' } + * invert({ a: Symbol('sym1'), b: Symbol('sym2') }); // { [Symbol('sym1')]: 'a', [Symbol('sym2')]: 'b' } + */ +declare function invert(obj: Record): Record; +//#endregion +export { invert }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/invert.js b/tools/ui/node_modules/es-toolkit/dist/object/invert.js new file mode 100644 index 0000000000000000000000000000000000000000..fa3d7a6aec36f2caeb0d24baf0cbafc5897b3d24 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/invert.js @@ -0,0 +1,31 @@ +//#region src/object/invert.ts +/** +* Inverts the keys and values of an object. The keys of the input object become the values of the output object and vice versa. +* +* This function takes an object and creates a new object by inverting its keys and values. If the input object has duplicate values, +* the key of the last occurrence will be used as the value for the new key in the output object. It effectively creates a reverse mapping +* of the input object's key-value pairs. +* +* @template K - Type of the keys in the input object (string, number, symbol) +* @template V - Type of the values in the input object (string, number, symbol) +* @param {Record} obj - The input object whose keys and values are to be inverted +* @returns {Record} - A new object with keys and values inverted +* +* @example +* invert({ a: 1, b: 2, c: 3 }); // { 1: 'a', 2: 'b', 3: 'c' } +* invert({ 1: 'a', 2: 'b', 3: 'c' }); // { a: '1', b: '2', c: '3' } +* invert({ a: 1, 2: 'b', c: 3, 4: 'd' }); // { 1: 'a', b: '2', 3: 'c', d: '4' } +* invert({ a: Symbol('sym1'), b: Symbol('sym2') }); // { [Symbol('sym1')]: 'a', [Symbol('sym2')]: 'b' } +*/ +function invert(obj) { + const result = {}; + const keys = Object.keys(obj); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const value = obj[key]; + result[value] = key; + } + return result; +} +//#endregion +exports.invert = invert; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/invert.mjs b/tools/ui/node_modules/es-toolkit/dist/object/invert.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2cc474201453f6edaf1fb6ac03eef519d8fc8d3c --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/invert.mjs @@ -0,0 +1,31 @@ +//#region src/object/invert.ts +/** +* Inverts the keys and values of an object. The keys of the input object become the values of the output object and vice versa. +* +* This function takes an object and creates a new object by inverting its keys and values. If the input object has duplicate values, +* the key of the last occurrence will be used as the value for the new key in the output object. It effectively creates a reverse mapping +* of the input object's key-value pairs. +* +* @template K - Type of the keys in the input object (string, number, symbol) +* @template V - Type of the values in the input object (string, number, symbol) +* @param {Record} obj - The input object whose keys and values are to be inverted +* @returns {Record} - A new object with keys and values inverted +* +* @example +* invert({ a: 1, b: 2, c: 3 }); // { 1: 'a', 2: 'b', 3: 'c' } +* invert({ 1: 'a', 2: 'b', 3: 'c' }); // { a: '1', b: '2', c: '3' } +* invert({ a: 1, 2: 'b', c: 3, 4: 'd' }); // { 1: 'a', b: '2', 3: 'c', d: '4' } +* invert({ a: Symbol('sym1'), b: Symbol('sym2') }); // { [Symbol('sym1')]: 'a', [Symbol('sym2')]: 'b' } +*/ +function invert(obj) { + const result = {}; + const keys = Object.keys(obj); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const value = obj[key]; + result[value] = key; + } + return result; +} +//#endregion +export { invert }; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/mapKeys.d.mts b/tools/ui/node_modules/es-toolkit/dist/object/mapKeys.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..5808c8df82529d0b104f345d1957dbb00c345f99 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/mapKeys.d.mts @@ -0,0 +1,21 @@ +//#region src/object/mapKeys.d.ts +/** + * Creates a new object with the same values as the given object, but with keys generated + * by running each own enumerable property of the object through the iteratee function. + * + * @template T - The type of the object. + * @template K - The type of the new keys generated by the iteratee function. + * + * @param {T} object - The object to iterate over. + * @param {(value: T[keyof T], key: keyof T, object: T) => K} getNewKey - The function invoked per own enumerable property. + * @returns {Record} - Returns the new mapped object. + * + * @example + * // Example usage: + * const obj = { a: 1, b: 2 }; + * const result = mapKeys(obj, (value, key) => key + value); + * console.log(result); // { a1: 1, b2: 2 } + */ +declare function mapKeys, K extends PropertyKey>(object: T, getNewKey: (value: T[keyof T], key: keyof T, object: T) => K): Record; +//#endregion +export { mapKeys }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/mapKeys.d.ts b/tools/ui/node_modules/es-toolkit/dist/object/mapKeys.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5808c8df82529d0b104f345d1957dbb00c345f99 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/mapKeys.d.ts @@ -0,0 +1,21 @@ +//#region src/object/mapKeys.d.ts +/** + * Creates a new object with the same values as the given object, but with keys generated + * by running each own enumerable property of the object through the iteratee function. + * + * @template T - The type of the object. + * @template K - The type of the new keys generated by the iteratee function. + * + * @param {T} object - The object to iterate over. + * @param {(value: T[keyof T], key: keyof T, object: T) => K} getNewKey - The function invoked per own enumerable property. + * @returns {Record} - Returns the new mapped object. + * + * @example + * // Example usage: + * const obj = { a: 1, b: 2 }; + * const result = mapKeys(obj, (value, key) => key + value); + * console.log(result); // { a1: 1, b2: 2 } + */ +declare function mapKeys, K extends PropertyKey>(object: T, getNewKey: (value: T[keyof T], key: keyof T, object: T) => K): Record; +//#endregion +export { mapKeys }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/mapKeys.js b/tools/ui/node_modules/es-toolkit/dist/object/mapKeys.js new file mode 100644 index 0000000000000000000000000000000000000000..707a60a7cc32f962e68b43001b540b20e3f8b4fc --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/mapKeys.js @@ -0,0 +1,30 @@ +//#region src/object/mapKeys.ts +/** +* Creates a new object with the same values as the given object, but with keys generated +* by running each own enumerable property of the object through the iteratee function. +* +* @template T - The type of the object. +* @template K - The type of the new keys generated by the iteratee function. +* +* @param {T} object - The object to iterate over. +* @param {(value: T[keyof T], key: keyof T, object: T) => K} getNewKey - The function invoked per own enumerable property. +* @returns {Record} - Returns the new mapped object. +* +* @example +* // Example usage: +* const obj = { a: 1, b: 2 }; +* const result = mapKeys(obj, (value, key) => key + value); +* console.log(result); // { a1: 1, b2: 2 } +*/ +function mapKeys(object, getNewKey) { + const result = {}; + const keys = Object.keys(object); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const value = object[key]; + result[getNewKey(value, key, object)] = value; + } + return result; +} +//#endregion +exports.mapKeys = mapKeys; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/mapKeys.mjs b/tools/ui/node_modules/es-toolkit/dist/object/mapKeys.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3398b2255e7d89363e2377652fc8181f07dec939 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/mapKeys.mjs @@ -0,0 +1,30 @@ +//#region src/object/mapKeys.ts +/** +* Creates a new object with the same values as the given object, but with keys generated +* by running each own enumerable property of the object through the iteratee function. +* +* @template T - The type of the object. +* @template K - The type of the new keys generated by the iteratee function. +* +* @param {T} object - The object to iterate over. +* @param {(value: T[keyof T], key: keyof T, object: T) => K} getNewKey - The function invoked per own enumerable property. +* @returns {Record} - Returns the new mapped object. +* +* @example +* // Example usage: +* const obj = { a: 1, b: 2 }; +* const result = mapKeys(obj, (value, key) => key + value); +* console.log(result); // { a1: 1, b2: 2 } +*/ +function mapKeys(object, getNewKey) { + const result = {}; + const keys = Object.keys(object); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const value = object[key]; + result[getNewKey(value, key, object)] = value; + } + return result; +} +//#endregion +export { mapKeys }; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/mapValues.d.mts b/tools/ui/node_modules/es-toolkit/dist/object/mapValues.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..ed7c651c8dc4faaf8fd688314abc626509c6b52f --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/mapValues.d.mts @@ -0,0 +1,22 @@ +//#region src/object/mapValues.d.ts +/** + * Creates a new object with the same keys as the given object, but with values generated + * by running each own enumerable property of the object through the iteratee function. + * + * @template T - The type of the object. + * @template K - The type of the keys in the object. + * @template V - The type of the new values generated by the iteratee function. + * + * @param {T} object - The object to iterate over. + * @param {(value: T[K], key: K, object: T) => V} getNewValue - The function invoked per own enumerable property. + * @returns {Record} - Returns the new mapped object. + * + * @example + * // Example usage: + * const obj = { a: 1, b: 2 }; + * const result = mapValues(obj, (value) => value * 2); + * console.log(result); // { a: 2, b: 4 } + */ +declare function mapValues(object: T, getNewValue: (value: T[K], key: K, object: T) => V): Record; +//#endregion +export { mapValues }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/mapValues.d.ts b/tools/ui/node_modules/es-toolkit/dist/object/mapValues.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ed7c651c8dc4faaf8fd688314abc626509c6b52f --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/mapValues.d.ts @@ -0,0 +1,22 @@ +//#region src/object/mapValues.d.ts +/** + * Creates a new object with the same keys as the given object, but with values generated + * by running each own enumerable property of the object through the iteratee function. + * + * @template T - The type of the object. + * @template K - The type of the keys in the object. + * @template V - The type of the new values generated by the iteratee function. + * + * @param {T} object - The object to iterate over. + * @param {(value: T[K], key: K, object: T) => V} getNewValue - The function invoked per own enumerable property. + * @returns {Record} - Returns the new mapped object. + * + * @example + * // Example usage: + * const obj = { a: 1, b: 2 }; + * const result = mapValues(obj, (value) => value * 2); + * console.log(result); // { a: 2, b: 4 } + */ +declare function mapValues(object: T, getNewValue: (value: T[K], key: K, object: T) => V): Record; +//#endregion +export { mapValues }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/mapValues.js b/tools/ui/node_modules/es-toolkit/dist/object/mapValues.js new file mode 100644 index 0000000000000000000000000000000000000000..1722e825974f73d18cf1125ef426fd4f8f93c26d --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/mapValues.js @@ -0,0 +1,31 @@ +//#region src/object/mapValues.ts +/** +* Creates a new object with the same keys as the given object, but with values generated +* by running each own enumerable property of the object through the iteratee function. +* +* @template T - The type of the object. +* @template K - The type of the keys in the object. +* @template V - The type of the new values generated by the iteratee function. +* +* @param {T} object - The object to iterate over. +* @param {(value: T[K], key: K, object: T) => V} getNewValue - The function invoked per own enumerable property. +* @returns {Record} - Returns the new mapped object. +* +* @example +* // Example usage: +* const obj = { a: 1, b: 2 }; +* const result = mapValues(obj, (value) => value * 2); +* console.log(result); // { a: 2, b: 4 } +*/ +function mapValues(object, getNewValue) { + const result = {}; + const keys = Object.keys(object); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const value = object[key]; + result[key] = getNewValue(value, key, object); + } + return result; +} +//#endregion +exports.mapValues = mapValues; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/mapValues.mjs b/tools/ui/node_modules/es-toolkit/dist/object/mapValues.mjs new file mode 100644 index 0000000000000000000000000000000000000000..abb4fd6796bd49fa4eb9792132c5323d42a2c5aa --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/mapValues.mjs @@ -0,0 +1,31 @@ +//#region src/object/mapValues.ts +/** +* Creates a new object with the same keys as the given object, but with values generated +* by running each own enumerable property of the object through the iteratee function. +* +* @template T - The type of the object. +* @template K - The type of the keys in the object. +* @template V - The type of the new values generated by the iteratee function. +* +* @param {T} object - The object to iterate over. +* @param {(value: T[K], key: K, object: T) => V} getNewValue - The function invoked per own enumerable property. +* @returns {Record} - Returns the new mapped object. +* +* @example +* // Example usage: +* const obj = { a: 1, b: 2 }; +* const result = mapValues(obj, (value) => value * 2); +* console.log(result); // { a: 2, b: 4 } +*/ +function mapValues(object, getNewValue) { + const result = {}; + const keys = Object.keys(object); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const value = object[key]; + result[key] = getNewValue(value, key, object); + } + return result; +} +//#endregion +export { mapValues }; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/merge.d.mts b/tools/ui/node_modules/es-toolkit/dist/object/merge.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..b5ba581a58e970ca7981851e19dd66b35a7d454a --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/merge.d.mts @@ -0,0 +1,44 @@ +//#region src/object/merge.d.ts +/** + * Merges the properties of the source object into the target object. + * + * This function performs a deep merge, meaning nested objects and arrays are merged recursively. + * If a property in the source object is an array or an object and the corresponding property in the target object is also an array or object, they will be merged. + * If a property in the source object is undefined, it will not overwrite a defined property in the target object. + * + * Note that this function mutates the target object. + * + * @param {T} target - The target object into which the source object properties will be merged. This object is modified in place. + * @param {S} source - The source object whose properties will be merged into the target object. + * @returns {T & S} The updated target object with properties from the source object merged in. + * + * @template T - Type of the target object. + * @template S - Type of the source object. + * + * @example + * const target = { a: 1, b: { x: 1, y: 2 } }; + * const source = { b: { y: 3, z: 4 }, c: 5 }; + * + * const result = merge(target, source); + * console.log(result); + * // Output: { a: 1, b: { x: 1, y: 3, z: 4 }, c: 5 } + * + * @example + * const target = { a: [1, 2], b: { x: 1 } }; + * const source = { a: [3], b: { y: 2 } }; + * + * const result = merge(target, source); + * console.log(result); + * // Output: { a: [3, 2], b: { x: 1, y: 2 } } + * + * @example + * const target = { a: null }; + * const source = { a: [1, 2, 3] }; + * + * const result = merge(target, source); + * console.log(result); + * // Output: { a: [1, 2, 3] } + */ +declare function merge, S extends Record>(target: T, source: S): T & S; +//#endregion +export { merge }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/merge.d.ts b/tools/ui/node_modules/es-toolkit/dist/object/merge.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b5ba581a58e970ca7981851e19dd66b35a7d454a --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/merge.d.ts @@ -0,0 +1,44 @@ +//#region src/object/merge.d.ts +/** + * Merges the properties of the source object into the target object. + * + * This function performs a deep merge, meaning nested objects and arrays are merged recursively. + * If a property in the source object is an array or an object and the corresponding property in the target object is also an array or object, they will be merged. + * If a property in the source object is undefined, it will not overwrite a defined property in the target object. + * + * Note that this function mutates the target object. + * + * @param {T} target - The target object into which the source object properties will be merged. This object is modified in place. + * @param {S} source - The source object whose properties will be merged into the target object. + * @returns {T & S} The updated target object with properties from the source object merged in. + * + * @template T - Type of the target object. + * @template S - Type of the source object. + * + * @example + * const target = { a: 1, b: { x: 1, y: 2 } }; + * const source = { b: { y: 3, z: 4 }, c: 5 }; + * + * const result = merge(target, source); + * console.log(result); + * // Output: { a: 1, b: { x: 1, y: 3, z: 4 }, c: 5 } + * + * @example + * const target = { a: [1, 2], b: { x: 1 } }; + * const source = { a: [3], b: { y: 2 } }; + * + * const result = merge(target, source); + * console.log(result); + * // Output: { a: [3, 2], b: { x: 1, y: 2 } } + * + * @example + * const target = { a: null }; + * const source = { a: [1, 2, 3] }; + * + * const result = merge(target, source); + * console.log(result); + * // Output: { a: [1, 2, 3] } + */ +declare function merge, S extends Record>(target: T, source: S): T & S; +//#endregion +export { merge }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/merge.js b/tools/ui/node_modules/es-toolkit/dist/object/merge.js new file mode 100644 index 0000000000000000000000000000000000000000..2bba0d8a2b2ad375bf994f4d3cdbd855a1051755 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/merge.js @@ -0,0 +1,62 @@ +const require_isPlainObject = require("../predicate/isPlainObject.js"); +const require_isUnsafeProperty = require("../_internal/isUnsafeProperty.js"); +//#region src/object/merge.ts +/** +* Merges the properties of the source object into the target object. +* +* This function performs a deep merge, meaning nested objects and arrays are merged recursively. +* If a property in the source object is an array or an object and the corresponding property in the target object is also an array or object, they will be merged. +* If a property in the source object is undefined, it will not overwrite a defined property in the target object. +* +* Note that this function mutates the target object. +* +* @param {T} target - The target object into which the source object properties will be merged. This object is modified in place. +* @param {S} source - The source object whose properties will be merged into the target object. +* @returns {T & S} The updated target object with properties from the source object merged in. +* +* @template T - Type of the target object. +* @template S - Type of the source object. +* +* @example +* const target = { a: 1, b: { x: 1, y: 2 } }; +* const source = { b: { y: 3, z: 4 }, c: 5 }; +* +* const result = merge(target, source); +* console.log(result); +* // Output: { a: 1, b: { x: 1, y: 3, z: 4 }, c: 5 } +* +* @example +* const target = { a: [1, 2], b: { x: 1 } }; +* const source = { a: [3], b: { y: 2 } }; +* +* const result = merge(target, source); +* console.log(result); +* // Output: { a: [3, 2], b: { x: 1, y: 2 } } +* +* @example +* const target = { a: null }; +* const source = { a: [1, 2, 3] }; +* +* const result = merge(target, source); +* console.log(result); +* // Output: { a: [1, 2, 3] } +*/ +function merge(target, source) { + const sourceKeys = Object.keys(source); + for (let i = 0; i < sourceKeys.length; i++) { + const key = sourceKeys[i]; + if (require_isUnsafeProperty.isUnsafeProperty(key)) continue; + const sourceValue = source[key]; + const targetValue = target[key]; + if (isMergeableValue(sourceValue) && isMergeableValue(targetValue)) target[key] = merge(targetValue, sourceValue); + else if (Array.isArray(sourceValue)) target[key] = merge([], sourceValue); + else if (require_isPlainObject.isPlainObject(sourceValue)) target[key] = merge({}, sourceValue); + else if (targetValue === void 0 || sourceValue !== void 0) target[key] = sourceValue; + } + return target; +} +function isMergeableValue(value) { + return require_isPlainObject.isPlainObject(value) || Array.isArray(value); +} +//#endregion +exports.merge = merge; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/merge.mjs b/tools/ui/node_modules/es-toolkit/dist/object/merge.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2a9c82eb6974ef8ed6135409a15ad4956e9a8457 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/merge.mjs @@ -0,0 +1,62 @@ +import { isPlainObject } from "../predicate/isPlainObject.mjs"; +import { isUnsafeProperty } from "../_internal/isUnsafeProperty.mjs"; +//#region src/object/merge.ts +/** +* Merges the properties of the source object into the target object. +* +* This function performs a deep merge, meaning nested objects and arrays are merged recursively. +* If a property in the source object is an array or an object and the corresponding property in the target object is also an array or object, they will be merged. +* If a property in the source object is undefined, it will not overwrite a defined property in the target object. +* +* Note that this function mutates the target object. +* +* @param {T} target - The target object into which the source object properties will be merged. This object is modified in place. +* @param {S} source - The source object whose properties will be merged into the target object. +* @returns {T & S} The updated target object with properties from the source object merged in. +* +* @template T - Type of the target object. +* @template S - Type of the source object. +* +* @example +* const target = { a: 1, b: { x: 1, y: 2 } }; +* const source = { b: { y: 3, z: 4 }, c: 5 }; +* +* const result = merge(target, source); +* console.log(result); +* // Output: { a: 1, b: { x: 1, y: 3, z: 4 }, c: 5 } +* +* @example +* const target = { a: [1, 2], b: { x: 1 } }; +* const source = { a: [3], b: { y: 2 } }; +* +* const result = merge(target, source); +* console.log(result); +* // Output: { a: [3, 2], b: { x: 1, y: 2 } } +* +* @example +* const target = { a: null }; +* const source = { a: [1, 2, 3] }; +* +* const result = merge(target, source); +* console.log(result); +* // Output: { a: [1, 2, 3] } +*/ +function merge(target, source) { + const sourceKeys = Object.keys(source); + for (let i = 0; i < sourceKeys.length; i++) { + const key = sourceKeys[i]; + if (isUnsafeProperty(key)) continue; + const sourceValue = source[key]; + const targetValue = target[key]; + if (isMergeableValue(sourceValue) && isMergeableValue(targetValue)) target[key] = merge(targetValue, sourceValue); + else if (Array.isArray(sourceValue)) target[key] = merge([], sourceValue); + else if (isPlainObject(sourceValue)) target[key] = merge({}, sourceValue); + else if (targetValue === void 0 || sourceValue !== void 0) target[key] = sourceValue; + } + return target; +} +function isMergeableValue(value) { + return isPlainObject(value) || Array.isArray(value); +} +//#endregion +export { merge }; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/mergeWith.d.mts b/tools/ui/node_modules/es-toolkit/dist/object/mergeWith.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..45fbe2b2f38151e23cd71a38a9b62a019c1e4425 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/mergeWith.d.mts @@ -0,0 +1,52 @@ +//#region src/object/mergeWith.d.ts +/** + * Merges the properties of the source object into the target object. + * + * You can provide a custom `merge` function to control how properties are merged. It should return the value to be set in the target object. + * + * If it returns `undefined`, a default deep merge will be applied for arrays and objects: + * + * - If a property in the source object is an array or an object and the corresponding property in the target object is also an array or object, they will be merged. + * - If a property in the source object is undefined, it will not overwrite a defined property in the target object. + * + * Note that this function mutates the target object. + * + * @param {T} target - The target object into which the source object properties will be merged. This object is modified in place. + * @param {S} source - The source object whose properties will be merged into the target object. + * @param {(targetValue: any, sourceValue: any, key: string, target: T, source: S) => any} merge - A custom merge function that defines how properties should be combined. It receives the following arguments: + * - `targetValue`: The current value of the property in the target object. + * - `sourceValue`: The value of the property in the source object. + * - `key`: The key of the property being merged. + * - `target`: The target object. + * - `source`: The source object. + * + * @returns {T & S} The updated target object with properties from the source object merged in. + * + * @template T - Type of the target object. + * @template S - Type of the source object. + * + * @example + * const target = { a: 1, b: 2 }; + * const source = { b: 3, c: 4 }; + * + * mergeWith(target, source, (targetValue, sourceValue) => { + * if (typeof targetValue === 'number' && typeof sourceValue === 'number') { + * return targetValue + sourceValue; + * } + * }); + * // Returns { a: 1, b: 5, c: 4 } + * @example + * const target = { a: [1], b: [2] }; + * const source = { a: [3], b: [4] }; + * + * const result = mergeWith(target, source, (objValue, srcValue) => { + * if (Array.isArray(objValue)) { + * return objValue.concat(srcValue); + * } + * }); + * + * expect(result).toEqual({ a: [1, 3], b: [2, 4] }); + */ +declare function mergeWith, S extends Record>(target: T, source: S, merge: (targetValue: any, sourceValue: any, key: string, target: T, source: S) => any): T & S; +//#endregion +export { mergeWith }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/mergeWith.d.ts b/tools/ui/node_modules/es-toolkit/dist/object/mergeWith.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..45fbe2b2f38151e23cd71a38a9b62a019c1e4425 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/mergeWith.d.ts @@ -0,0 +1,52 @@ +//#region src/object/mergeWith.d.ts +/** + * Merges the properties of the source object into the target object. + * + * You can provide a custom `merge` function to control how properties are merged. It should return the value to be set in the target object. + * + * If it returns `undefined`, a default deep merge will be applied for arrays and objects: + * + * - If a property in the source object is an array or an object and the corresponding property in the target object is also an array or object, they will be merged. + * - If a property in the source object is undefined, it will not overwrite a defined property in the target object. + * + * Note that this function mutates the target object. + * + * @param {T} target - The target object into which the source object properties will be merged. This object is modified in place. + * @param {S} source - The source object whose properties will be merged into the target object. + * @param {(targetValue: any, sourceValue: any, key: string, target: T, source: S) => any} merge - A custom merge function that defines how properties should be combined. It receives the following arguments: + * - `targetValue`: The current value of the property in the target object. + * - `sourceValue`: The value of the property in the source object. + * - `key`: The key of the property being merged. + * - `target`: The target object. + * - `source`: The source object. + * + * @returns {T & S} The updated target object with properties from the source object merged in. + * + * @template T - Type of the target object. + * @template S - Type of the source object. + * + * @example + * const target = { a: 1, b: 2 }; + * const source = { b: 3, c: 4 }; + * + * mergeWith(target, source, (targetValue, sourceValue) => { + * if (typeof targetValue === 'number' && typeof sourceValue === 'number') { + * return targetValue + sourceValue; + * } + * }); + * // Returns { a: 1, b: 5, c: 4 } + * @example + * const target = { a: [1], b: [2] }; + * const source = { a: [3], b: [4] }; + * + * const result = mergeWith(target, source, (objValue, srcValue) => { + * if (Array.isArray(objValue)) { + * return objValue.concat(srcValue); + * } + * }); + * + * expect(result).toEqual({ a: [1, 3], b: [2, 4] }); + */ +declare function mergeWith, S extends Record>(target: T, source: S, merge: (targetValue: any, sourceValue: any, key: string, target: T, source: S) => any): T & S; +//#endregion +export { mergeWith }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/mergeWith.js b/tools/ui/node_modules/es-toolkit/dist/object/mergeWith.js new file mode 100644 index 0000000000000000000000000000000000000000..8ffef7f3fdc544e946a8381d3e9fe1dc2dd3df12 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/mergeWith.js @@ -0,0 +1,70 @@ +const require_isPlainObject = require("../predicate/isPlainObject.js"); +const require_isUnsafeProperty = require("../_internal/isUnsafeProperty.js"); +//#region src/object/mergeWith.ts +/** +* Merges the properties of the source object into the target object. +* +* You can provide a custom `merge` function to control how properties are merged. It should return the value to be set in the target object. +* +* If it returns `undefined`, a default deep merge will be applied for arrays and objects: +* +* - If a property in the source object is an array or an object and the corresponding property in the target object is also an array or object, they will be merged. +* - If a property in the source object is undefined, it will not overwrite a defined property in the target object. +* +* Note that this function mutates the target object. +* +* @param {T} target - The target object into which the source object properties will be merged. This object is modified in place. +* @param {S} source - The source object whose properties will be merged into the target object. +* @param {(targetValue: any, sourceValue: any, key: string, target: T, source: S) => any} merge - A custom merge function that defines how properties should be combined. It receives the following arguments: +* - `targetValue`: The current value of the property in the target object. +* - `sourceValue`: The value of the property in the source object. +* - `key`: The key of the property being merged. +* - `target`: The target object. +* - `source`: The source object. +* +* @returns {T & S} The updated target object with properties from the source object merged in. +* +* @template T - Type of the target object. +* @template S - Type of the source object. +* +* @example +* const target = { a: 1, b: 2 }; +* const source = { b: 3, c: 4 }; +* +* mergeWith(target, source, (targetValue, sourceValue) => { +* if (typeof targetValue === 'number' && typeof sourceValue === 'number') { +* return targetValue + sourceValue; +* } +* }); +* // Returns { a: 1, b: 5, c: 4 } +* @example +* const target = { a: [1], b: [2] }; +* const source = { a: [3], b: [4] }; +* +* const result = mergeWith(target, source, (objValue, srcValue) => { +* if (Array.isArray(objValue)) { +* return objValue.concat(srcValue); +* } +* }); +* +* expect(result).toEqual({ a: [1, 3], b: [2, 4] }); +*/ +function mergeWith(target, source, merge) { + const sourceKeys = Object.keys(source); + for (let i = 0; i < sourceKeys.length; i++) { + const key = sourceKeys[i]; + if (require_isUnsafeProperty.isUnsafeProperty(key)) continue; + const sourceValue = source[key]; + const targetValue = target[key]; + const merged = merge(targetValue, sourceValue, key, target, source); + if (merged !== void 0) target[key] = merged; + else if (Array.isArray(sourceValue)) if (Array.isArray(targetValue)) target[key] = mergeWith(targetValue, sourceValue, merge); + else target[key] = mergeWith([], sourceValue, merge); + else if (require_isPlainObject.isPlainObject(sourceValue)) if (require_isPlainObject.isPlainObject(targetValue)) target[key] = mergeWith(targetValue, sourceValue, merge); + else target[key] = mergeWith({}, sourceValue, merge); + else if (targetValue === void 0 || sourceValue !== void 0) target[key] = sourceValue; + } + return target; +} +//#endregion +exports.mergeWith = mergeWith; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/mergeWith.mjs b/tools/ui/node_modules/es-toolkit/dist/object/mergeWith.mjs new file mode 100644 index 0000000000000000000000000000000000000000..af1d3bb572e3a9c8c65e0d7061cc49625be9e052 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/mergeWith.mjs @@ -0,0 +1,70 @@ +import { isPlainObject } from "../predicate/isPlainObject.mjs"; +import { isUnsafeProperty } from "../_internal/isUnsafeProperty.mjs"; +//#region src/object/mergeWith.ts +/** +* Merges the properties of the source object into the target object. +* +* You can provide a custom `merge` function to control how properties are merged. It should return the value to be set in the target object. +* +* If it returns `undefined`, a default deep merge will be applied for arrays and objects: +* +* - If a property in the source object is an array or an object and the corresponding property in the target object is also an array or object, they will be merged. +* - If a property in the source object is undefined, it will not overwrite a defined property in the target object. +* +* Note that this function mutates the target object. +* +* @param {T} target - The target object into which the source object properties will be merged. This object is modified in place. +* @param {S} source - The source object whose properties will be merged into the target object. +* @param {(targetValue: any, sourceValue: any, key: string, target: T, source: S) => any} merge - A custom merge function that defines how properties should be combined. It receives the following arguments: +* - `targetValue`: The current value of the property in the target object. +* - `sourceValue`: The value of the property in the source object. +* - `key`: The key of the property being merged. +* - `target`: The target object. +* - `source`: The source object. +* +* @returns {T & S} The updated target object with properties from the source object merged in. +* +* @template T - Type of the target object. +* @template S - Type of the source object. +* +* @example +* const target = { a: 1, b: 2 }; +* const source = { b: 3, c: 4 }; +* +* mergeWith(target, source, (targetValue, sourceValue) => { +* if (typeof targetValue === 'number' && typeof sourceValue === 'number') { +* return targetValue + sourceValue; +* } +* }); +* // Returns { a: 1, b: 5, c: 4 } +* @example +* const target = { a: [1], b: [2] }; +* const source = { a: [3], b: [4] }; +* +* const result = mergeWith(target, source, (objValue, srcValue) => { +* if (Array.isArray(objValue)) { +* return objValue.concat(srcValue); +* } +* }); +* +* expect(result).toEqual({ a: [1, 3], b: [2, 4] }); +*/ +function mergeWith(target, source, merge) { + const sourceKeys = Object.keys(source); + for (let i = 0; i < sourceKeys.length; i++) { + const key = sourceKeys[i]; + if (isUnsafeProperty(key)) continue; + const sourceValue = source[key]; + const targetValue = target[key]; + const merged = merge(targetValue, sourceValue, key, target, source); + if (merged !== void 0) target[key] = merged; + else if (Array.isArray(sourceValue)) if (Array.isArray(targetValue)) target[key] = mergeWith(targetValue, sourceValue, merge); + else target[key] = mergeWith([], sourceValue, merge); + else if (isPlainObject(sourceValue)) if (isPlainObject(targetValue)) target[key] = mergeWith(targetValue, sourceValue, merge); + else target[key] = mergeWith({}, sourceValue, merge); + else if (targetValue === void 0 || sourceValue !== void 0) target[key] = sourceValue; + } + return target; +} +//#endregion +export { mergeWith }; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/omit.d.mts b/tools/ui/node_modules/es-toolkit/dist/object/omit.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..373c4c55f24c8570f9772c772dbfd566bf3c9715 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/omit.d.mts @@ -0,0 +1,21 @@ +//#region src/object/omit.d.ts +/** + * Creates a new object with specified keys omitted. + * + * This function takes an object and an array of keys, and returns a new object that + * excludes the properties corresponding to the specified keys. + * + * @template T - The type of object. + * @template K - The type of keys in object. + * @param {T} obj - The object to omit keys from. + * @param {K[]} keys - An array of keys to be omitted from the object. + * @returns {Omit} A new object with the specified keys omitted. + * + * @example + * const obj = { a: 1, b: 2, c: 3 }; + * const result = omit(obj, ['b', 'c']); + * // result will be { a: 1 } + */ +declare function omit, K extends keyof T>(obj: T, keys: readonly K[]): Omit; +//#endregion +export { omit }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/omit.d.ts b/tools/ui/node_modules/es-toolkit/dist/object/omit.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..373c4c55f24c8570f9772c772dbfd566bf3c9715 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/omit.d.ts @@ -0,0 +1,21 @@ +//#region src/object/omit.d.ts +/** + * Creates a new object with specified keys omitted. + * + * This function takes an object and an array of keys, and returns a new object that + * excludes the properties corresponding to the specified keys. + * + * @template T - The type of object. + * @template K - The type of keys in object. + * @param {T} obj - The object to omit keys from. + * @param {K[]} keys - An array of keys to be omitted from the object. + * @returns {Omit} A new object with the specified keys omitted. + * + * @example + * const obj = { a: 1, b: 2, c: 3 }; + * const result = omit(obj, ['b', 'c']); + * // result will be { a: 1 } + */ +declare function omit, K extends keyof T>(obj: T, keys: readonly K[]): Omit; +//#endregion +export { omit }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/omit.js b/tools/ui/node_modules/es-toolkit/dist/object/omit.js new file mode 100644 index 0000000000000000000000000000000000000000..341cbb50a62582573c3a8afee178ec3cb93733d4 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/omit.js @@ -0,0 +1,28 @@ +//#region src/object/omit.ts +/** +* Creates a new object with specified keys omitted. +* +* This function takes an object and an array of keys, and returns a new object that +* excludes the properties corresponding to the specified keys. +* +* @template T - The type of object. +* @template K - The type of keys in object. +* @param {T} obj - The object to omit keys from. +* @param {K[]} keys - An array of keys to be omitted from the object. +* @returns {Omit} A new object with the specified keys omitted. +* +* @example +* const obj = { a: 1, b: 2, c: 3 }; +* const result = omit(obj, ['b', 'c']); +* // result will be { a: 1 } +*/ +function omit(obj, keys) { + const result = { ...obj }; + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + delete result[key]; + } + return result; +} +//#endregion +exports.omit = omit; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/omit.mjs b/tools/ui/node_modules/es-toolkit/dist/object/omit.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ac8458bcd23468cae4ff6431ba4212e599cac6b6 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/omit.mjs @@ -0,0 +1,28 @@ +//#region src/object/omit.ts +/** +* Creates a new object with specified keys omitted. +* +* This function takes an object and an array of keys, and returns a new object that +* excludes the properties corresponding to the specified keys. +* +* @template T - The type of object. +* @template K - The type of keys in object. +* @param {T} obj - The object to omit keys from. +* @param {K[]} keys - An array of keys to be omitted from the object. +* @returns {Omit} A new object with the specified keys omitted. +* +* @example +* const obj = { a: 1, b: 2, c: 3 }; +* const result = omit(obj, ['b', 'c']); +* // result will be { a: 1 } +*/ +function omit(obj, keys) { + const result = { ...obj }; + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + delete result[key]; + } + return result; +} +//#endregion +export { omit }; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/omitBy.d.mts b/tools/ui/node_modules/es-toolkit/dist/object/omitBy.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..c027b21ede5e0cbe04d47ead945788f8cb04493a --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/omitBy.d.mts @@ -0,0 +1,23 @@ +//#region src/object/omitBy.d.ts +/** + * Creates a new object composed of the properties that do not satisfy the predicate function. + * + * This function takes an object and a predicate function, and returns a new object that + * includes only the properties for which the predicate function returns false. + * + * @template T - The type of object. + * @param {T} obj - The object to omit properties from. + * @param {(value: T[string], key: keyof T) => boolean} shouldOmit - A predicate function that determines + * whether a property should be omitted. It takes the property's key and value as arguments and returns `true` + * if the property should be omitted, and `false` otherwise. + * @returns {Partial} A new object with the properties that do not satisfy the predicate function. + * + * @example + * const obj = { a: 1, b: 'omit', c: 3 }; + * const shouldOmit = (value) => typeof value === 'string'; + * const result = omitBy(obj, shouldOmit); + * // result will be { a: 1, c: 3 } + */ +declare function omitBy>(obj: T, shouldOmit: (value: T[keyof T], key: keyof T) => boolean): Partial; +//#endregion +export { omitBy }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/omitBy.d.ts b/tools/ui/node_modules/es-toolkit/dist/object/omitBy.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c027b21ede5e0cbe04d47ead945788f8cb04493a --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/omitBy.d.ts @@ -0,0 +1,23 @@ +//#region src/object/omitBy.d.ts +/** + * Creates a new object composed of the properties that do not satisfy the predicate function. + * + * This function takes an object and a predicate function, and returns a new object that + * includes only the properties for which the predicate function returns false. + * + * @template T - The type of object. + * @param {T} obj - The object to omit properties from. + * @param {(value: T[string], key: keyof T) => boolean} shouldOmit - A predicate function that determines + * whether a property should be omitted. It takes the property's key and value as arguments and returns `true` + * if the property should be omitted, and `false` otherwise. + * @returns {Partial} A new object with the properties that do not satisfy the predicate function. + * + * @example + * const obj = { a: 1, b: 'omit', c: 3 }; + * const shouldOmit = (value) => typeof value === 'string'; + * const result = omitBy(obj, shouldOmit); + * // result will be { a: 1, c: 3 } + */ +declare function omitBy>(obj: T, shouldOmit: (value: T[keyof T], key: keyof T) => boolean): Partial; +//#endregion +export { omitBy }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/omitBy.js b/tools/ui/node_modules/es-toolkit/dist/object/omitBy.js new file mode 100644 index 0000000000000000000000000000000000000000..03e761af35a33be959eecc2e97d9c2bb78ac1a0e --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/omitBy.js @@ -0,0 +1,32 @@ +//#region src/object/omitBy.ts +/** +* Creates a new object composed of the properties that do not satisfy the predicate function. +* +* This function takes an object and a predicate function, and returns a new object that +* includes only the properties for which the predicate function returns false. +* +* @template T - The type of object. +* @param {T} obj - The object to omit properties from. +* @param {(value: T[string], key: keyof T) => boolean} shouldOmit - A predicate function that determines +* whether a property should be omitted. It takes the property's key and value as arguments and returns `true` +* if the property should be omitted, and `false` otherwise. +* @returns {Partial} A new object with the properties that do not satisfy the predicate function. +* +* @example +* const obj = { a: 1, b: 'omit', c: 3 }; +* const shouldOmit = (value) => typeof value === 'string'; +* const result = omitBy(obj, shouldOmit); +* // result will be { a: 1, c: 3 } +*/ +function omitBy(obj, shouldOmit) { + const result = {}; + const keys = Object.keys(obj); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const value = obj[key]; + if (!shouldOmit(value, key)) result[key] = value; + } + return result; +} +//#endregion +exports.omitBy = omitBy; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/omitBy.mjs b/tools/ui/node_modules/es-toolkit/dist/object/omitBy.mjs new file mode 100644 index 0000000000000000000000000000000000000000..73089df8c452852ae0e20bc9b2093e172eff3270 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/omitBy.mjs @@ -0,0 +1,32 @@ +//#region src/object/omitBy.ts +/** +* Creates a new object composed of the properties that do not satisfy the predicate function. +* +* This function takes an object and a predicate function, and returns a new object that +* includes only the properties for which the predicate function returns false. +* +* @template T - The type of object. +* @param {T} obj - The object to omit properties from. +* @param {(value: T[string], key: keyof T) => boolean} shouldOmit - A predicate function that determines +* whether a property should be omitted. It takes the property's key and value as arguments and returns `true` +* if the property should be omitted, and `false` otherwise. +* @returns {Partial} A new object with the properties that do not satisfy the predicate function. +* +* @example +* const obj = { a: 1, b: 'omit', c: 3 }; +* const shouldOmit = (value) => typeof value === 'string'; +* const result = omitBy(obj, shouldOmit); +* // result will be { a: 1, c: 3 } +*/ +function omitBy(obj, shouldOmit) { + const result = {}; + const keys = Object.keys(obj); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const value = obj[key]; + if (!shouldOmit(value, key)) result[key] = value; + } + return result; +} +//#endregion +export { omitBy }; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/pick.d.mts b/tools/ui/node_modules/es-toolkit/dist/object/pick.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..1bb136f306dc6e63c45d079891f8dd6c8c55f137 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/pick.d.mts @@ -0,0 +1,21 @@ +//#region src/object/pick.d.ts +/** + * Creates a new object composed of the picked object properties. + * + * This function takes an object and an array of keys, and returns a new object that + * includes only the properties corresponding to the specified keys. + * + * @template T - The type of object. + * @template K - The type of keys in object. + * @param {T} obj - The object to pick keys from. + * @param {K[]} keys - An array of keys to be picked from the object. + * @returns {Pick} A new object with the specified keys picked. + * + * @example + * const obj = { a: 1, b: 2, c: 3 }; + * const result = pick(obj, ['a', 'c']); + * // result will be { a: 1, c: 3 } + */ +declare function pick, K extends keyof T>(obj: T, keys: readonly K[]): Pick; +//#endregion +export { pick }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/pick.d.ts b/tools/ui/node_modules/es-toolkit/dist/object/pick.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1bb136f306dc6e63c45d079891f8dd6c8c55f137 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/pick.d.ts @@ -0,0 +1,21 @@ +//#region src/object/pick.d.ts +/** + * Creates a new object composed of the picked object properties. + * + * This function takes an object and an array of keys, and returns a new object that + * includes only the properties corresponding to the specified keys. + * + * @template T - The type of object. + * @template K - The type of keys in object. + * @param {T} obj - The object to pick keys from. + * @param {K[]} keys - An array of keys to be picked from the object. + * @returns {Pick} A new object with the specified keys picked. + * + * @example + * const obj = { a: 1, b: 2, c: 3 }; + * const result = pick(obj, ['a', 'c']); + * // result will be { a: 1, c: 3 } + */ +declare function pick, K extends keyof T>(obj: T, keys: readonly K[]): Pick; +//#endregion +export { pick }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/pick.js b/tools/ui/node_modules/es-toolkit/dist/object/pick.js new file mode 100644 index 0000000000000000000000000000000000000000..7f3eb4d03975581de16a32cac45d91295a75388e --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/pick.js @@ -0,0 +1,28 @@ +//#region src/object/pick.ts +/** +* Creates a new object composed of the picked object properties. +* +* This function takes an object and an array of keys, and returns a new object that +* includes only the properties corresponding to the specified keys. +* +* @template T - The type of object. +* @template K - The type of keys in object. +* @param {T} obj - The object to pick keys from. +* @param {K[]} keys - An array of keys to be picked from the object. +* @returns {Pick} A new object with the specified keys picked. +* +* @example +* const obj = { a: 1, b: 2, c: 3 }; +* const result = pick(obj, ['a', 'c']); +* // result will be { a: 1, c: 3 } +*/ +function pick(obj, keys) { + const result = {}; + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + if (Object.hasOwn(obj, key)) result[key] = obj[key]; + } + return result; +} +//#endregion +exports.pick = pick; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/pick.mjs b/tools/ui/node_modules/es-toolkit/dist/object/pick.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e3da18c00bed933304e607d40dda4188e13ceb73 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/pick.mjs @@ -0,0 +1,28 @@ +//#region src/object/pick.ts +/** +* Creates a new object composed of the picked object properties. +* +* This function takes an object and an array of keys, and returns a new object that +* includes only the properties corresponding to the specified keys. +* +* @template T - The type of object. +* @template K - The type of keys in object. +* @param {T} obj - The object to pick keys from. +* @param {K[]} keys - An array of keys to be picked from the object. +* @returns {Pick} A new object with the specified keys picked. +* +* @example +* const obj = { a: 1, b: 2, c: 3 }; +* const result = pick(obj, ['a', 'c']); +* // result will be { a: 1, c: 3 } +*/ +function pick(obj, keys) { + const result = {}; + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + if (Object.hasOwn(obj, key)) result[key] = obj[key]; + } + return result; +} +//#endregion +export { pick }; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/pickBy.d.mts b/tools/ui/node_modules/es-toolkit/dist/object/pickBy.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..835799d070a44e6003a15e58a2f4ea05b168efbc --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/pickBy.d.mts @@ -0,0 +1,23 @@ +//#region src/object/pickBy.d.ts +/** + * Creates a new object composed of the properties that satisfy the predicate function. + * + * This function takes an object and a predicate function, and returns a new object that + * includes only the properties for which the predicate function returns true. + * + * @template T - The type of object. + * @param {T} obj - The object to pick properties from. + * @param {(value: T[keyof T], key: keyof T) => boolean} shouldPick - A predicate function that determines + * whether a property should be picked. It takes the property's key and value as arguments and returns `true` + * if the property should be picked, and `false` otherwise. + * @returns {Partial} A new object with the properties that satisfy the predicate function. + * + * @example + * const obj = { a: 1, b: 'pick', c: 3 }; + * const shouldPick = (value) => typeof value === 'string'; + * const result = pickBy(obj, shouldPick); + * // result will be { b: 'pick' } + */ +declare function pickBy>(obj: T, shouldPick: (value: T[keyof T], key: keyof T) => boolean): Partial; +//#endregion +export { pickBy }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/pickBy.d.ts b/tools/ui/node_modules/es-toolkit/dist/object/pickBy.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..835799d070a44e6003a15e58a2f4ea05b168efbc --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/pickBy.d.ts @@ -0,0 +1,23 @@ +//#region src/object/pickBy.d.ts +/** + * Creates a new object composed of the properties that satisfy the predicate function. + * + * This function takes an object and a predicate function, and returns a new object that + * includes only the properties for which the predicate function returns true. + * + * @template T - The type of object. + * @param {T} obj - The object to pick properties from. + * @param {(value: T[keyof T], key: keyof T) => boolean} shouldPick - A predicate function that determines + * whether a property should be picked. It takes the property's key and value as arguments and returns `true` + * if the property should be picked, and `false` otherwise. + * @returns {Partial} A new object with the properties that satisfy the predicate function. + * + * @example + * const obj = { a: 1, b: 'pick', c: 3 }; + * const shouldPick = (value) => typeof value === 'string'; + * const result = pickBy(obj, shouldPick); + * // result will be { b: 'pick' } + */ +declare function pickBy>(obj: T, shouldPick: (value: T[keyof T], key: keyof T) => boolean): Partial; +//#endregion +export { pickBy }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/pickBy.js b/tools/ui/node_modules/es-toolkit/dist/object/pickBy.js new file mode 100644 index 0000000000000000000000000000000000000000..60ae43b783734767ad31282145c74829407b421a --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/pickBy.js @@ -0,0 +1,32 @@ +//#region src/object/pickBy.ts +/** +* Creates a new object composed of the properties that satisfy the predicate function. +* +* This function takes an object and a predicate function, and returns a new object that +* includes only the properties for which the predicate function returns true. +* +* @template T - The type of object. +* @param {T} obj - The object to pick properties from. +* @param {(value: T[keyof T], key: keyof T) => boolean} shouldPick - A predicate function that determines +* whether a property should be picked. It takes the property's key and value as arguments and returns `true` +* if the property should be picked, and `false` otherwise. +* @returns {Partial} A new object with the properties that satisfy the predicate function. +* +* @example +* const obj = { a: 1, b: 'pick', c: 3 }; +* const shouldPick = (value) => typeof value === 'string'; +* const result = pickBy(obj, shouldPick); +* // result will be { b: 'pick' } +*/ +function pickBy(obj, shouldPick) { + const result = {}; + const keys = Object.keys(obj); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const value = obj[key]; + if (shouldPick(value, key)) result[key] = value; + } + return result; +} +//#endregion +exports.pickBy = pickBy; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/pickBy.mjs b/tools/ui/node_modules/es-toolkit/dist/object/pickBy.mjs new file mode 100644 index 0000000000000000000000000000000000000000..427cf5248bf30f78831b9345532a945b9dbf76dd --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/pickBy.mjs @@ -0,0 +1,32 @@ +//#region src/object/pickBy.ts +/** +* Creates a new object composed of the properties that satisfy the predicate function. +* +* This function takes an object and a predicate function, and returns a new object that +* includes only the properties for which the predicate function returns true. +* +* @template T - The type of object. +* @param {T} obj - The object to pick properties from. +* @param {(value: T[keyof T], key: keyof T) => boolean} shouldPick - A predicate function that determines +* whether a property should be picked. It takes the property's key and value as arguments and returns `true` +* if the property should be picked, and `false` otherwise. +* @returns {Partial} A new object with the properties that satisfy the predicate function. +* +* @example +* const obj = { a: 1, b: 'pick', c: 3 }; +* const shouldPick = (value) => typeof value === 'string'; +* const result = pickBy(obj, shouldPick); +* // result will be { b: 'pick' } +*/ +function pickBy(obj, shouldPick) { + const result = {}; + const keys = Object.keys(obj); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const value = obj[key]; + if (shouldPick(value, key)) result[key] = value; + } + return result; +} +//#endregion +export { pickBy }; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/sortKeys.d.mts b/tools/ui/node_modules/es-toolkit/dist/object/sortKeys.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..232ee0fddca908fabaa2e1a4189af8872355e8d8 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/sortKeys.d.mts @@ -0,0 +1,22 @@ +//#region src/object/sortKeys.d.ts +/** + * Creates a new object with the keys sorted. + * + * The keys are sorted alphabetically by default, but a custom compare function can be provided. + * + * @template T - The type of the object. + * @param {T} object - The object to sort keys from. + * @param {(a: string, b: string) => number} [compareKeys] - A custom compare function for sorting keys. + * @returns {T} A new object with the keys sorted. + * + * @example + * sortKeys({ b: 2, a: 1, c: 3 }); + * // => { a: 1, b: 2, c: 3 } + * + * @example + * sortKeys({ b: 2, a: 1, c: 3 }, (a, b) => b.localeCompare(a)); + * // => { c: 3, b: 2, a: 1 } + */ +declare function sortKeys>(object: T, compareKeys?: (a: string, b: string) => number): T; +//#endregion +export { sortKeys }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/sortKeys.d.ts b/tools/ui/node_modules/es-toolkit/dist/object/sortKeys.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..232ee0fddca908fabaa2e1a4189af8872355e8d8 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/sortKeys.d.ts @@ -0,0 +1,22 @@ +//#region src/object/sortKeys.d.ts +/** + * Creates a new object with the keys sorted. + * + * The keys are sorted alphabetically by default, but a custom compare function can be provided. + * + * @template T - The type of the object. + * @param {T} object - The object to sort keys from. + * @param {(a: string, b: string) => number} [compareKeys] - A custom compare function for sorting keys. + * @returns {T} A new object with the keys sorted. + * + * @example + * sortKeys({ b: 2, a: 1, c: 3 }); + * // => { a: 1, b: 2, c: 3 } + * + * @example + * sortKeys({ b: 2, a: 1, c: 3 }, (a, b) => b.localeCompare(a)); + * // => { c: 3, b: 2, a: 1 } + */ +declare function sortKeys>(object: T, compareKeys?: (a: string, b: string) => number): T; +//#endregion +export { sortKeys }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/sortKeys.js b/tools/ui/node_modules/es-toolkit/dist/object/sortKeys.js new file mode 100644 index 0000000000000000000000000000000000000000..6282865b3a5ea2f0030f04463b6981fd5cadd4c5 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/sortKeys.js @@ -0,0 +1,30 @@ +//#region src/object/sortKeys.ts +/** +* Creates a new object with the keys sorted. +* +* The keys are sorted alphabetically by default, but a custom compare function can be provided. +* +* @template T - The type of the object. +* @param {T} object - The object to sort keys from. +* @param {(a: string, b: string) => number} [compareKeys] - A custom compare function for sorting keys. +* @returns {T} A new object with the keys sorted. +* +* @example +* sortKeys({ b: 2, a: 1, c: 3 }); +* // => { a: 1, b: 2, c: 3 } +* +* @example +* sortKeys({ b: 2, a: 1, c: 3 }, (a, b) => b.localeCompare(a)); +* // => { c: 3, b: 2, a: 1 } +*/ +function sortKeys(object, compareKeys) { + const sortedKeys = Object.keys(object).sort(compareKeys); + const result = {}; + for (let i = 0; i < sortedKeys.length; i++) { + const key = sortedKeys[i]; + result[key] = object[key]; + } + return result; +} +//#endregion +exports.sortKeys = sortKeys; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/sortKeys.mjs b/tools/ui/node_modules/es-toolkit/dist/object/sortKeys.mjs new file mode 100644 index 0000000000000000000000000000000000000000..eb8dde593985f286bde3071ac03803d9840fc9af --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/sortKeys.mjs @@ -0,0 +1,30 @@ +//#region src/object/sortKeys.ts +/** +* Creates a new object with the keys sorted. +* +* The keys are sorted alphabetically by default, but a custom compare function can be provided. +* +* @template T - The type of the object. +* @param {T} object - The object to sort keys from. +* @param {(a: string, b: string) => number} [compareKeys] - A custom compare function for sorting keys. +* @returns {T} A new object with the keys sorted. +* +* @example +* sortKeys({ b: 2, a: 1, c: 3 }); +* // => { a: 1, b: 2, c: 3 } +* +* @example +* sortKeys({ b: 2, a: 1, c: 3 }, (a, b) => b.localeCompare(a)); +* // => { c: 3, b: 2, a: 1 } +*/ +function sortKeys(object, compareKeys) { + const sortedKeys = Object.keys(object).sort(compareKeys); + const result = {}; + for (let i = 0; i < sortedKeys.length; i++) { + const key = sortedKeys[i]; + result[key] = object[key]; + } + return result; +} +//#endregion +export { sortKeys }; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/toCamelCaseKeys.d.mts b/tools/ui/node_modules/es-toolkit/dist/object/toCamelCaseKeys.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..73cfe0fc343575abc83ddb51e305691d0eeb9c51 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/toCamelCaseKeys.d.mts @@ -0,0 +1,56 @@ +//#region src/object/toCamelCaseKeys.d.ts +type SnakeToCamel = S extends `${infer H}_${infer T}` ? `${Lowercase}${Capitalize>}` : Lowercase; +type PascalToCamel = S extends `${infer F}${infer R}` ? `${Lowercase}${R}` : S; +/** If it's snake_case, apply the snake_case rule; for uppercase keys, lowercase the entire string; otherwise, just lowercase the first letter (including PascalCase → camelCase). */ +type AnyToCamel = S extends `${string}_${string}` ? SnakeToCamel : S extends Uppercase ? Lowercase : PascalToCamel; +type NonPlainObject = Date | RegExp | Map | Set | WeakMap | WeakSet | Promise | Error | ArrayBuffer | DataView | Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array | ((...args: any[]) => any) | typeof globalThis; +type ToCamelCaseKeys = T extends NonPlainObject ? T : T extends any[] ? Array> : T extends Record ? { [K in keyof T as AnyToCamel>]: ToCamelCaseKeys } : T; +/** + * Creates a new object composed of the properties with keys converted to camelCase. + * + * This function takes an object and returns a new object that includes the same properties, + * but with all keys converted to camelCase format. + * + * @template T - The type of object. + * @param {T} obj - The object to convert keys from. + * @returns {ToCamelCaseKeys} A new object with all keys converted to camelCase. + * + * @example + * // Example with objects + * const obj = { user_id: 1, first_name: 'John' }; + * const result = toCamelCaseKeys(obj); + * // result will be { userId: 1, firstName: 'John' } + * + * // Example with arrays of objects + * const arr = [ + * { user_id: 1, first_name: 'John' }, + * { user_id: 2, first_name: 'Jane' } + * ]; + * const arrResult = toCamelCaseKeys(arr); + * // arrResult will be [{ userId: 1, firstName: 'John' }, { userId: 2, firstName: 'Jane' }] + * + * // Example with nested objects + * const nested = { + * user_data: { + * user_id: 1, + * user_address: { + * street_name: 'Main St', + * zip_code: '12345' + * } + * } + * }; + * const nestedResult = toCamelCaseKeys(nested); + * // nestedResult will be: + * // { + * // userData: { + * // userId: 1, + * // userAddress: { + * // streetName: 'Main St', + * // zipCode: '12345' + * // } + * // } + * // } + */ +declare function toCamelCaseKeys(obj: T): ToCamelCaseKeys; +//#endregion +export { toCamelCaseKeys }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/toCamelCaseKeys.d.ts b/tools/ui/node_modules/es-toolkit/dist/object/toCamelCaseKeys.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..73cfe0fc343575abc83ddb51e305691d0eeb9c51 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/toCamelCaseKeys.d.ts @@ -0,0 +1,56 @@ +//#region src/object/toCamelCaseKeys.d.ts +type SnakeToCamel = S extends `${infer H}_${infer T}` ? `${Lowercase}${Capitalize>}` : Lowercase; +type PascalToCamel = S extends `${infer F}${infer R}` ? `${Lowercase}${R}` : S; +/** If it's snake_case, apply the snake_case rule; for uppercase keys, lowercase the entire string; otherwise, just lowercase the first letter (including PascalCase → camelCase). */ +type AnyToCamel = S extends `${string}_${string}` ? SnakeToCamel : S extends Uppercase ? Lowercase : PascalToCamel; +type NonPlainObject = Date | RegExp | Map | Set | WeakMap | WeakSet | Promise | Error | ArrayBuffer | DataView | Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array | ((...args: any[]) => any) | typeof globalThis; +type ToCamelCaseKeys = T extends NonPlainObject ? T : T extends any[] ? Array> : T extends Record ? { [K in keyof T as AnyToCamel>]: ToCamelCaseKeys } : T; +/** + * Creates a new object composed of the properties with keys converted to camelCase. + * + * This function takes an object and returns a new object that includes the same properties, + * but with all keys converted to camelCase format. + * + * @template T - The type of object. + * @param {T} obj - The object to convert keys from. + * @returns {ToCamelCaseKeys} A new object with all keys converted to camelCase. + * + * @example + * // Example with objects + * const obj = { user_id: 1, first_name: 'John' }; + * const result = toCamelCaseKeys(obj); + * // result will be { userId: 1, firstName: 'John' } + * + * // Example with arrays of objects + * const arr = [ + * { user_id: 1, first_name: 'John' }, + * { user_id: 2, first_name: 'Jane' } + * ]; + * const arrResult = toCamelCaseKeys(arr); + * // arrResult will be [{ userId: 1, firstName: 'John' }, { userId: 2, firstName: 'Jane' }] + * + * // Example with nested objects + * const nested = { + * user_data: { + * user_id: 1, + * user_address: { + * street_name: 'Main St', + * zip_code: '12345' + * } + * } + * }; + * const nestedResult = toCamelCaseKeys(nested); + * // nestedResult will be: + * // { + * // userData: { + * // userId: 1, + * // userAddress: { + * // streetName: 'Main St', + * // zipCode: '12345' + * // } + * // } + * // } + */ +declare function toCamelCaseKeys(obj: T): ToCamelCaseKeys; +//#endregion +export { toCamelCaseKeys }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/toCamelCaseKeys.js b/tools/ui/node_modules/es-toolkit/dist/object/toCamelCaseKeys.js new file mode 100644 index 0000000000000000000000000000000000000000..3866909b7d3257b701855540f8afabd4f554bd95 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/toCamelCaseKeys.js @@ -0,0 +1,66 @@ +const require_isPlainObject = require("../predicate/isPlainObject.js"); +const require_isArray = require("../compat/predicate/isArray.js"); +const require_camelCase = require("../string/camelCase.js"); +//#region src/object/toCamelCaseKeys.ts +/** +* Creates a new object composed of the properties with keys converted to camelCase. +* +* This function takes an object and returns a new object that includes the same properties, +* but with all keys converted to camelCase format. +* +* @template T - The type of object. +* @param {T} obj - The object to convert keys from. +* @returns {ToCamelCaseKeys} A new object with all keys converted to camelCase. +* +* @example +* // Example with objects +* const obj = { user_id: 1, first_name: 'John' }; +* const result = toCamelCaseKeys(obj); +* // result will be { userId: 1, firstName: 'John' } +* +* // Example with arrays of objects +* const arr = [ +* { user_id: 1, first_name: 'John' }, +* { user_id: 2, first_name: 'Jane' } +* ]; +* const arrResult = toCamelCaseKeys(arr); +* // arrResult will be [{ userId: 1, firstName: 'John' }, { userId: 2, firstName: 'Jane' }] +* +* // Example with nested objects +* const nested = { +* user_data: { +* user_id: 1, +* user_address: { +* street_name: 'Main St', +* zip_code: '12345' +* } +* } +* }; +* const nestedResult = toCamelCaseKeys(nested); +* // nestedResult will be: +* // { +* // userData: { +* // userId: 1, +* // userAddress: { +* // streetName: 'Main St', +* // zipCode: '12345' +* // } +* // } +* // } +*/ +function toCamelCaseKeys(obj) { + if (require_isArray.isArray(obj)) return obj.map((item) => toCamelCaseKeys(item)); + if (require_isPlainObject.isPlainObject(obj)) { + const result = {}; + const keys = Object.keys(obj); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const camelKey = require_camelCase.camelCase(key); + result[camelKey] = toCamelCaseKeys(obj[key]); + } + return result; + } + return obj; +} +//#endregion +exports.toCamelCaseKeys = toCamelCaseKeys; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/toCamelCaseKeys.mjs b/tools/ui/node_modules/es-toolkit/dist/object/toCamelCaseKeys.mjs new file mode 100644 index 0000000000000000000000000000000000000000..555d92606d489737310fad0f022593f557c06f98 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/toCamelCaseKeys.mjs @@ -0,0 +1,66 @@ +import { isPlainObject } from "../predicate/isPlainObject.mjs"; +import { isArray } from "../compat/predicate/isArray.mjs"; +import { camelCase } from "../string/camelCase.mjs"; +//#region src/object/toCamelCaseKeys.ts +/** +* Creates a new object composed of the properties with keys converted to camelCase. +* +* This function takes an object and returns a new object that includes the same properties, +* but with all keys converted to camelCase format. +* +* @template T - The type of object. +* @param {T} obj - The object to convert keys from. +* @returns {ToCamelCaseKeys} A new object with all keys converted to camelCase. +* +* @example +* // Example with objects +* const obj = { user_id: 1, first_name: 'John' }; +* const result = toCamelCaseKeys(obj); +* // result will be { userId: 1, firstName: 'John' } +* +* // Example with arrays of objects +* const arr = [ +* { user_id: 1, first_name: 'John' }, +* { user_id: 2, first_name: 'Jane' } +* ]; +* const arrResult = toCamelCaseKeys(arr); +* // arrResult will be [{ userId: 1, firstName: 'John' }, { userId: 2, firstName: 'Jane' }] +* +* // Example with nested objects +* const nested = { +* user_data: { +* user_id: 1, +* user_address: { +* street_name: 'Main St', +* zip_code: '12345' +* } +* } +* }; +* const nestedResult = toCamelCaseKeys(nested); +* // nestedResult will be: +* // { +* // userData: { +* // userId: 1, +* // userAddress: { +* // streetName: 'Main St', +* // zipCode: '12345' +* // } +* // } +* // } +*/ +function toCamelCaseKeys(obj) { + if (isArray(obj)) return obj.map((item) => toCamelCaseKeys(item)); + if (isPlainObject(obj)) { + const result = {}; + const keys = Object.keys(obj); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const camelKey = camelCase(key); + result[camelKey] = toCamelCaseKeys(obj[key]); + } + return result; + } + return obj; +} +//#endregion +export { toCamelCaseKeys }; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/toMerged.d.mts b/tools/ui/node_modules/es-toolkit/dist/object/toMerged.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..be632287d576077ebfb09782d787e1bcbfd20cad --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/toMerged.d.mts @@ -0,0 +1,46 @@ +//#region src/object/toMerged.d.ts +/** + * Merges the properties of the source object into a deep clone of the target object. + * Unlike `merge`, This function does not modify the original target object. + * + * This function performs a deep merge, meaning nested objects and arrays are merged recursively. + * + * - If a property in the source object is an array or object and the corresponding property in the target object is also an array or object, they will be merged. + * - If a property in the source object is undefined, it will not overwrite a defined property in the target object. + * + * Note that this function does not mutate the target object. + * + * @param {T} target - The target object to be cloned and merged into. This object is not modified directly. + * @param {S} source - The source object whose properties will be merged into the cloned target object. + * @returns {T & S} A new object with properties from the source object merged into a deep clone of the target object. + * + * @template T - Type of the target object. + * @template S - Type of the source object. + * + * @example + * const target = { a: 1, b: { x: 1, y: 2 } }; + * const source = { b: { y: 3, z: 4 }, c: 5 }; + * + * const result = toMerged(target, source); + * console.log(result); + * // Output: { a: 1, b: { x: 1, y: 3, z: 4 }, c: 5 } + * + * @example + * const target = { a: [1, 2], b: { x: 1 } }; + * const source = { a: [3], b: { y: 2 } }; + * + * const result = toMerged(target, source); + * console.log(result); + * // Output: { a: [3, 2], b: { x: 1, y: 2 } } + * + * @example + * const target = { a: null }; + * const source = { a: [1, 2, 3] }; + * + * const result = toMerged(target, source); + * console.log(result); + * // Output: { a: [1, 2, 3] } + */ +declare function toMerged, S extends Record>(target: T, source: S): T & S; +//#endregion +export { toMerged }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/toMerged.d.ts b/tools/ui/node_modules/es-toolkit/dist/object/toMerged.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..be632287d576077ebfb09782d787e1bcbfd20cad --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/toMerged.d.ts @@ -0,0 +1,46 @@ +//#region src/object/toMerged.d.ts +/** + * Merges the properties of the source object into a deep clone of the target object. + * Unlike `merge`, This function does not modify the original target object. + * + * This function performs a deep merge, meaning nested objects and arrays are merged recursively. + * + * - If a property in the source object is an array or object and the corresponding property in the target object is also an array or object, they will be merged. + * - If a property in the source object is undefined, it will not overwrite a defined property in the target object. + * + * Note that this function does not mutate the target object. + * + * @param {T} target - The target object to be cloned and merged into. This object is not modified directly. + * @param {S} source - The source object whose properties will be merged into the cloned target object. + * @returns {T & S} A new object with properties from the source object merged into a deep clone of the target object. + * + * @template T - Type of the target object. + * @template S - Type of the source object. + * + * @example + * const target = { a: 1, b: { x: 1, y: 2 } }; + * const source = { b: { y: 3, z: 4 }, c: 5 }; + * + * const result = toMerged(target, source); + * console.log(result); + * // Output: { a: 1, b: { x: 1, y: 3, z: 4 }, c: 5 } + * + * @example + * const target = { a: [1, 2], b: { x: 1 } }; + * const source = { a: [3], b: { y: 2 } }; + * + * const result = toMerged(target, source); + * console.log(result); + * // Output: { a: [3, 2], b: { x: 1, y: 2 } } + * + * @example + * const target = { a: null }; + * const source = { a: [1, 2, 3] }; + * + * const result = toMerged(target, source); + * console.log(result); + * // Output: { a: [1, 2, 3] } + */ +declare function toMerged, S extends Record>(target: T, source: S): T & S; +//#endregion +export { toMerged }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/toMerged.js b/tools/ui/node_modules/es-toolkit/dist/object/toMerged.js new file mode 100644 index 0000000000000000000000000000000000000000..7f4647bed4942b985e6d0beb093ad32186c95ab8 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/toMerged.js @@ -0,0 +1,56 @@ +const require_clone = require("./clone.js"); +const require_isPlainObject = require("../predicate/isPlainObject.js"); +const require_mergeWith = require("./mergeWith.js"); +//#region src/object/toMerged.ts +/** +* Merges the properties of the source object into a deep clone of the target object. +* Unlike `merge`, This function does not modify the original target object. +* +* This function performs a deep merge, meaning nested objects and arrays are merged recursively. +* +* - If a property in the source object is an array or object and the corresponding property in the target object is also an array or object, they will be merged. +* - If a property in the source object is undefined, it will not overwrite a defined property in the target object. +* +* Note that this function does not mutate the target object. +* +* @param {T} target - The target object to be cloned and merged into. This object is not modified directly. +* @param {S} source - The source object whose properties will be merged into the cloned target object. +* @returns {T & S} A new object with properties from the source object merged into a deep clone of the target object. +* +* @template T - Type of the target object. +* @template S - Type of the source object. +* +* @example +* const target = { a: 1, b: { x: 1, y: 2 } }; +* const source = { b: { y: 3, z: 4 }, c: 5 }; +* +* const result = toMerged(target, source); +* console.log(result); +* // Output: { a: 1, b: { x: 1, y: 3, z: 4 }, c: 5 } +* +* @example +* const target = { a: [1, 2], b: { x: 1 } }; +* const source = { a: [3], b: { y: 2 } }; +* +* const result = toMerged(target, source); +* console.log(result); +* // Output: { a: [3, 2], b: { x: 1, y: 2 } } +* +* @example +* const target = { a: null }; +* const source = { a: [1, 2, 3] }; +* +* const result = toMerged(target, source); +* console.log(result); +* // Output: { a: [1, 2, 3] } +*/ +function toMerged(target, source) { + return require_mergeWith.mergeWith(require_clone.clone(target), source, function mergeRecursively(targetValue, sourceValue) { + if (Array.isArray(sourceValue)) if (Array.isArray(targetValue)) return require_mergeWith.mergeWith(require_clone.clone(targetValue), sourceValue, mergeRecursively); + else return require_mergeWith.mergeWith([], sourceValue, mergeRecursively); + else if (require_isPlainObject.isPlainObject(sourceValue)) if (require_isPlainObject.isPlainObject(targetValue)) return require_mergeWith.mergeWith(require_clone.clone(targetValue), sourceValue, mergeRecursively); + else return require_mergeWith.mergeWith({}, sourceValue, mergeRecursively); + }); +} +//#endregion +exports.toMerged = toMerged; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/toMerged.mjs b/tools/ui/node_modules/es-toolkit/dist/object/toMerged.mjs new file mode 100644 index 0000000000000000000000000000000000000000..49563d88115d63a02ecee2e62546adc6dfd40e51 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/toMerged.mjs @@ -0,0 +1,56 @@ +import { clone } from "./clone.mjs"; +import { isPlainObject } from "../predicate/isPlainObject.mjs"; +import { mergeWith } from "./mergeWith.mjs"; +//#region src/object/toMerged.ts +/** +* Merges the properties of the source object into a deep clone of the target object. +* Unlike `merge`, This function does not modify the original target object. +* +* This function performs a deep merge, meaning nested objects and arrays are merged recursively. +* +* - If a property in the source object is an array or object and the corresponding property in the target object is also an array or object, they will be merged. +* - If a property in the source object is undefined, it will not overwrite a defined property in the target object. +* +* Note that this function does not mutate the target object. +* +* @param {T} target - The target object to be cloned and merged into. This object is not modified directly. +* @param {S} source - The source object whose properties will be merged into the cloned target object. +* @returns {T & S} A new object with properties from the source object merged into a deep clone of the target object. +* +* @template T - Type of the target object. +* @template S - Type of the source object. +* +* @example +* const target = { a: 1, b: { x: 1, y: 2 } }; +* const source = { b: { y: 3, z: 4 }, c: 5 }; +* +* const result = toMerged(target, source); +* console.log(result); +* // Output: { a: 1, b: { x: 1, y: 3, z: 4 }, c: 5 } +* +* @example +* const target = { a: [1, 2], b: { x: 1 } }; +* const source = { a: [3], b: { y: 2 } }; +* +* const result = toMerged(target, source); +* console.log(result); +* // Output: { a: [3, 2], b: { x: 1, y: 2 } } +* +* @example +* const target = { a: null }; +* const source = { a: [1, 2, 3] }; +* +* const result = toMerged(target, source); +* console.log(result); +* // Output: { a: [1, 2, 3] } +*/ +function toMerged(target, source) { + return mergeWith(clone(target), source, function mergeRecursively(targetValue, sourceValue) { + if (Array.isArray(sourceValue)) if (Array.isArray(targetValue)) return mergeWith(clone(targetValue), sourceValue, mergeRecursively); + else return mergeWith([], sourceValue, mergeRecursively); + else if (isPlainObject(sourceValue)) if (isPlainObject(targetValue)) return mergeWith(clone(targetValue), sourceValue, mergeRecursively); + else return mergeWith({}, sourceValue, mergeRecursively); + }); +} +//#endregion +export { toMerged }; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/toSnakeCaseKeys.d.mts b/tools/ui/node_modules/es-toolkit/dist/object/toSnakeCaseKeys.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..05afd57007f40a5660e82498ade95af8dcb63275 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/toSnakeCaseKeys.d.mts @@ -0,0 +1,53 @@ +//#region src/object/toSnakeCaseKeys.d.ts +type SnakeCase = S extends Uppercase ? Lowercase : S extends `${infer P1}${infer P2}` ? P2 extends Uncapitalize ? `${Lowercase}${SnakeCase}` : `${Lowercase}_${SnakeCase>}` : Lowercase; +type NonPlainObject = Date | RegExp | Map | Set | WeakMap | WeakSet | Promise | Error | ArrayBuffer | DataView | Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array | ((...args: any[]) => any) | typeof globalThis; +type ToSnakeCaseKeys = T extends NonPlainObject ? T : T extends any[] ? Array> : T extends Record ? { [K in keyof T as SnakeCase]: ToSnakeCaseKeys } : T; +/** + * Creates a new object composed of the properties with keys converted to snake_case. + * + * This function takes an object and returns a new object that includes the same properties, + * but with all keys converted to snake_case format. + * + * @template T - The type of object. + * @param {T} obj - The object to convert keys from. + * @returns {ToSnakeCaseKeys} A new object with all keys converted to snake_case. + * + * @example + * // Example with objects + * const obj = { userId: 1, firstName: 'John' }; + * const result = toSnakeCaseKeys(obj); + * // result will be { user_id: 1, first_name: 'John' } + * + * // Example with arrays of objects + * const arr = [ + * { userId: 1, firstName: 'John' }, + * { userId: 2, firstName: 'Jane' } + * ]; + * const arrResult = toSnakeCaseKeys(arr); + * // arrResult will be [{ user_id: 1, first_name: 'John' }, { user_id: 2, first_name: 'Jane' }] + * + * // Example with nested objects + * const nested = { + * userData: { + * userId: 1, + * userAddress: { + * streetName: 'Main St', + * zipCode: '12345' + * } + * } + * }; + * const nestedResult = toSnakeCaseKeys(nested); + * // nestedResult will be: + * // { + * // user_data: { + * // user_id: 1, + * // user_address: { + * // street_name: 'Main St', + * // zip_code: '12345' + * // } + * // } + * // } + */ +declare function toSnakeCaseKeys(obj: T): ToSnakeCaseKeys; +//#endregion +export { toSnakeCaseKeys }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/toSnakeCaseKeys.d.ts b/tools/ui/node_modules/es-toolkit/dist/object/toSnakeCaseKeys.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..05afd57007f40a5660e82498ade95af8dcb63275 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/toSnakeCaseKeys.d.ts @@ -0,0 +1,53 @@ +//#region src/object/toSnakeCaseKeys.d.ts +type SnakeCase = S extends Uppercase ? Lowercase : S extends `${infer P1}${infer P2}` ? P2 extends Uncapitalize ? `${Lowercase}${SnakeCase}` : `${Lowercase}_${SnakeCase>}` : Lowercase; +type NonPlainObject = Date | RegExp | Map | Set | WeakMap | WeakSet | Promise | Error | ArrayBuffer | DataView | Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array | ((...args: any[]) => any) | typeof globalThis; +type ToSnakeCaseKeys = T extends NonPlainObject ? T : T extends any[] ? Array> : T extends Record ? { [K in keyof T as SnakeCase]: ToSnakeCaseKeys } : T; +/** + * Creates a new object composed of the properties with keys converted to snake_case. + * + * This function takes an object and returns a new object that includes the same properties, + * but with all keys converted to snake_case format. + * + * @template T - The type of object. + * @param {T} obj - The object to convert keys from. + * @returns {ToSnakeCaseKeys} A new object with all keys converted to snake_case. + * + * @example + * // Example with objects + * const obj = { userId: 1, firstName: 'John' }; + * const result = toSnakeCaseKeys(obj); + * // result will be { user_id: 1, first_name: 'John' } + * + * // Example with arrays of objects + * const arr = [ + * { userId: 1, firstName: 'John' }, + * { userId: 2, firstName: 'Jane' } + * ]; + * const arrResult = toSnakeCaseKeys(arr); + * // arrResult will be [{ user_id: 1, first_name: 'John' }, { user_id: 2, first_name: 'Jane' }] + * + * // Example with nested objects + * const nested = { + * userData: { + * userId: 1, + * userAddress: { + * streetName: 'Main St', + * zipCode: '12345' + * } + * } + * }; + * const nestedResult = toSnakeCaseKeys(nested); + * // nestedResult will be: + * // { + * // user_data: { + * // user_id: 1, + * // user_address: { + * // street_name: 'Main St', + * // zip_code: '12345' + * // } + * // } + * // } + */ +declare function toSnakeCaseKeys(obj: T): ToSnakeCaseKeys; +//#endregion +export { toSnakeCaseKeys }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/object/toSnakeCaseKeys.js b/tools/ui/node_modules/es-toolkit/dist/object/toSnakeCaseKeys.js new file mode 100644 index 0000000000000000000000000000000000000000..a97e852859e72c07d2560fee26ad5c9851a8e7c7 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/toSnakeCaseKeys.js @@ -0,0 +1,66 @@ +const require_isArray = require("../compat/predicate/isArray.js"); +const require_isPlainObject = require("../compat/predicate/isPlainObject.js"); +const require_snakeCase = require("../string/snakeCase.js"); +//#region src/object/toSnakeCaseKeys.ts +/** +* Creates a new object composed of the properties with keys converted to snake_case. +* +* This function takes an object and returns a new object that includes the same properties, +* but with all keys converted to snake_case format. +* +* @template T - The type of object. +* @param {T} obj - The object to convert keys from. +* @returns {ToSnakeCaseKeys} A new object with all keys converted to snake_case. +* +* @example +* // Example with objects +* const obj = { userId: 1, firstName: 'John' }; +* const result = toSnakeCaseKeys(obj); +* // result will be { user_id: 1, first_name: 'John' } +* +* // Example with arrays of objects +* const arr = [ +* { userId: 1, firstName: 'John' }, +* { userId: 2, firstName: 'Jane' } +* ]; +* const arrResult = toSnakeCaseKeys(arr); +* // arrResult will be [{ user_id: 1, first_name: 'John' }, { user_id: 2, first_name: 'Jane' }] +* +* // Example with nested objects +* const nested = { +* userData: { +* userId: 1, +* userAddress: { +* streetName: 'Main St', +* zipCode: '12345' +* } +* } +* }; +* const nestedResult = toSnakeCaseKeys(nested); +* // nestedResult will be: +* // { +* // user_data: { +* // user_id: 1, +* // user_address: { +* // street_name: 'Main St', +* // zip_code: '12345' +* // } +* // } +* // } +*/ +function toSnakeCaseKeys(obj) { + if (require_isArray.isArray(obj)) return obj.map((item) => toSnakeCaseKeys(item)); + if (require_isPlainObject.isPlainObject(obj)) { + const result = {}; + const keys = Object.keys(obj); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const snakeKey = require_snakeCase.snakeCase(key); + result[snakeKey] = toSnakeCaseKeys(obj[key]); + } + return result; + } + return obj; +} +//#endregion +exports.toSnakeCaseKeys = toSnakeCaseKeys; diff --git a/tools/ui/node_modules/es-toolkit/dist/object/toSnakeCaseKeys.mjs b/tools/ui/node_modules/es-toolkit/dist/object/toSnakeCaseKeys.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2f6df3a4b35cc56ea488034c21e5af3f3b957666 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/object/toSnakeCaseKeys.mjs @@ -0,0 +1,66 @@ +import { isArray } from "../compat/predicate/isArray.mjs"; +import { isPlainObject } from "../compat/predicate/isPlainObject.mjs"; +import { snakeCase } from "../string/snakeCase.mjs"; +//#region src/object/toSnakeCaseKeys.ts +/** +* Creates a new object composed of the properties with keys converted to snake_case. +* +* This function takes an object and returns a new object that includes the same properties, +* but with all keys converted to snake_case format. +* +* @template T - The type of object. +* @param {T} obj - The object to convert keys from. +* @returns {ToSnakeCaseKeys} A new object with all keys converted to snake_case. +* +* @example +* // Example with objects +* const obj = { userId: 1, firstName: 'John' }; +* const result = toSnakeCaseKeys(obj); +* // result will be { user_id: 1, first_name: 'John' } +* +* // Example with arrays of objects +* const arr = [ +* { userId: 1, firstName: 'John' }, +* { userId: 2, firstName: 'Jane' } +* ]; +* const arrResult = toSnakeCaseKeys(arr); +* // arrResult will be [{ user_id: 1, first_name: 'John' }, { user_id: 2, first_name: 'Jane' }] +* +* // Example with nested objects +* const nested = { +* userData: { +* userId: 1, +* userAddress: { +* streetName: 'Main St', +* zipCode: '12345' +* } +* } +* }; +* const nestedResult = toSnakeCaseKeys(nested); +* // nestedResult will be: +* // { +* // user_data: { +* // user_id: 1, +* // user_address: { +* // street_name: 'Main St', +* // zip_code: '12345' +* // } +* // } +* // } +*/ +function toSnakeCaseKeys(obj) { + if (isArray(obj)) return obj.map((item) => toSnakeCaseKeys(item)); + if (isPlainObject(obj)) { + const result = {}; + const keys = Object.keys(obj); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const snakeKey = snakeCase(key); + result[snakeKey] = toSnakeCaseKeys(obj[key]); + } + return result; + } + return obj; +} +//#endregion +export { toSnakeCaseKeys }; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/index.d.mts b/tools/ui/node_modules/es-toolkit/dist/predicate/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..b4269216b18d48d388c2b2ecb5ee4ebfb9dd4fca --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/index.d.mts @@ -0,0 +1,33 @@ +import { isEqual } from "./isEqual.mjs"; +import { isArrayBuffer } from "./isArrayBuffer.mjs"; +import { isBlob } from "./isBlob.mjs"; +import { isBoolean } from "./isBoolean.mjs"; +import { isBrowser } from "./isBrowser.mjs"; +import { isBuffer } from "./isBuffer.mjs"; +import { isDate } from "./isDate.mjs"; +import { isEmptyObject } from "./isEmptyObject.mjs"; +import { isEqualWith } from "./isEqualWith.mjs"; +import { isError } from "./isError.mjs"; +import { isFile } from "./isFile.mjs"; +import { isFunction } from "./isFunction.mjs"; +import { isJSON } from "./isJSON.mjs"; +import { isJSONArray, isJSONObject, isJSONValue } from "./isJSONValue.mjs"; +import { isLength } from "./isLength.mjs"; +import { isMap } from "./isMap.mjs"; +import { isNil } from "./isNil.mjs"; +import { isNode } from "./isNode.mjs"; +import { isNotNil } from "./isNotNil.mjs"; +import { isNull } from "./isNull.mjs"; +import { isNumber } from "./isNumber.mjs"; +import { isPlainObject } from "./isPlainObject.mjs"; +import { isPrimitive } from "./isPrimitive.mjs"; +import { isPromise } from "./isPromise.mjs"; +import { isRegExp } from "./isRegExp.mjs"; +import { isSet } from "./isSet.mjs"; +import { isString } from "./isString.mjs"; +import { isSymbol } from "./isSymbol.mjs"; +import { isTypedArray } from "./isTypedArray.mjs"; +import { isUndefined } from "./isUndefined.mjs"; +import { isWeakMap } from "./isWeakMap.mjs"; +import { isWeakSet } from "./isWeakSet.mjs"; +export { isArrayBuffer, isBlob, isBoolean, isBrowser, isBuffer, isDate, isEmptyObject, isEqual, isEqualWith, isError, isFile, isFunction, isJSON, isJSONArray, isJSONObject, isJSONValue, isLength, isMap, isNil, isNode, isNotNil, isNull, isNumber, isPlainObject, isPrimitive, isPromise, isRegExp, isSet, isString, isSymbol, isTypedArray, isUndefined, isWeakMap, isWeakSet }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/index.d.ts b/tools/ui/node_modules/es-toolkit/dist/predicate/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0c7c9e3f981ecb0ef3f263002545ea15b2d480b7 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/index.d.ts @@ -0,0 +1,33 @@ +import { isEqual } from "./isEqual.js"; +import { isArrayBuffer } from "./isArrayBuffer.js"; +import { isBlob } from "./isBlob.js"; +import { isBoolean } from "./isBoolean.js"; +import { isBrowser } from "./isBrowser.js"; +import { isBuffer } from "./isBuffer.js"; +import { isDate } from "./isDate.js"; +import { isEmptyObject } from "./isEmptyObject.js"; +import { isEqualWith } from "./isEqualWith.js"; +import { isError } from "./isError.js"; +import { isFile } from "./isFile.js"; +import { isFunction } from "./isFunction.js"; +import { isJSON } from "./isJSON.js"; +import { isJSONArray, isJSONObject, isJSONValue } from "./isJSONValue.js"; +import { isLength } from "./isLength.js"; +import { isMap } from "./isMap.js"; +import { isNil } from "./isNil.js"; +import { isNode } from "./isNode.js"; +import { isNotNil } from "./isNotNil.js"; +import { isNull } from "./isNull.js"; +import { isNumber } from "./isNumber.js"; +import { isPlainObject } from "./isPlainObject.js"; +import { isPrimitive } from "./isPrimitive.js"; +import { isPromise } from "./isPromise.js"; +import { isRegExp } from "./isRegExp.js"; +import { isSet } from "./isSet.js"; +import { isString } from "./isString.js"; +import { isSymbol } from "./isSymbol.js"; +import { isTypedArray } from "./isTypedArray.js"; +import { isUndefined } from "./isUndefined.js"; +import { isWeakMap } from "./isWeakMap.js"; +import { isWeakSet } from "./isWeakSet.js"; +export { isArrayBuffer, isBlob, isBoolean, isBrowser, isBuffer, isDate, isEmptyObject, isEqual, isEqualWith, isError, isFile, isFunction, isJSON, isJSONArray, isJSONObject, isJSONValue, isLength, isMap, isNil, isNode, isNotNil, isNull, isNumber, isPlainObject, isPrimitive, isPromise, isRegExp, isSet, isString, isSymbol, isTypedArray, isUndefined, isWeakMap, isWeakSet }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/index.js b/tools/ui/node_modules/es-toolkit/dist/predicate/index.js new file mode 100644 index 0000000000000000000000000000000000000000..bd820f302561dbd53282f50499e23861f9ac5d6b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/index.js @@ -0,0 +1,67 @@ +Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); +const require_isPrimitive = require("./isPrimitive.js"); +const require_isTypedArray = require("./isTypedArray.js"); +const require_isBuffer = require("./isBuffer.js"); +const require_isPlainObject = require("./isPlainObject.js"); +const require_isArrayBuffer = require("./isArrayBuffer.js"); +const require_isBlob = require("./isBlob.js"); +const require_isBoolean = require("./isBoolean.js"); +const require_isBrowser = require("./isBrowser.js"); +const require_isDate = require("./isDate.js"); +const require_isEmptyObject = require("./isEmptyObject.js"); +const require_isEqualWith = require("./isEqualWith.js"); +const require_isEqual = require("./isEqual.js"); +const require_isError = require("./isError.js"); +const require_isFile = require("./isFile.js"); +const require_isFunction = require("./isFunction.js"); +const require_isJSON = require("./isJSON.js"); +const require_isJSONValue = require("./isJSONValue.js"); +const require_isLength = require("./isLength.js"); +const require_isMap = require("./isMap.js"); +const require_isNil = require("./isNil.js"); +const require_isNode = require("./isNode.js"); +const require_isNotNil = require("./isNotNil.js"); +const require_isNull = require("./isNull.js"); +const require_isNumber = require("./isNumber.js"); +const require_isPromise = require("./isPromise.js"); +const require_isRegExp = require("./isRegExp.js"); +const require_isSet = require("./isSet.js"); +const require_isString = require("./isString.js"); +const require_isSymbol = require("./isSymbol.js"); +const require_isUndefined = require("./isUndefined.js"); +const require_isWeakMap = require("./isWeakMap.js"); +const require_isWeakSet = require("./isWeakSet.js"); +exports.isArrayBuffer = require_isArrayBuffer.isArrayBuffer; +exports.isBlob = require_isBlob.isBlob; +exports.isBoolean = require_isBoolean.isBoolean; +exports.isBrowser = require_isBrowser.isBrowser; +exports.isBuffer = require_isBuffer.isBuffer; +exports.isDate = require_isDate.isDate; +exports.isEmptyObject = require_isEmptyObject.isEmptyObject; +exports.isEqual = require_isEqual.isEqual; +exports.isEqualWith = require_isEqualWith.isEqualWith; +exports.isError = require_isError.isError; +exports.isFile = require_isFile.isFile; +exports.isFunction = require_isFunction.isFunction; +exports.isJSON = require_isJSON.isJSON; +exports.isJSONArray = require_isJSONValue.isJSONArray; +exports.isJSONObject = require_isJSONValue.isJSONObject; +exports.isJSONValue = require_isJSONValue.isJSONValue; +exports.isLength = require_isLength.isLength; +exports.isMap = require_isMap.isMap; +exports.isNil = require_isNil.isNil; +exports.isNode = require_isNode.isNode; +exports.isNotNil = require_isNotNil.isNotNil; +exports.isNull = require_isNull.isNull; +exports.isNumber = require_isNumber.isNumber; +exports.isPlainObject = require_isPlainObject.isPlainObject; +exports.isPrimitive = require_isPrimitive.isPrimitive; +exports.isPromise = require_isPromise.isPromise; +exports.isRegExp = require_isRegExp.isRegExp; +exports.isSet = require_isSet.isSet; +exports.isString = require_isString.isString; +exports.isSymbol = require_isSymbol.isSymbol; +exports.isTypedArray = require_isTypedArray.isTypedArray; +exports.isUndefined = require_isUndefined.isUndefined; +exports.isWeakMap = require_isWeakMap.isWeakMap; +exports.isWeakSet = require_isWeakSet.isWeakSet; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/index.mjs b/tools/ui/node_modules/es-toolkit/dist/predicate/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..72459e7cb18bb7c809e86615df150a659751a9d1 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/index.mjs @@ -0,0 +1,33 @@ +import { isPrimitive } from "./isPrimitive.mjs"; +import { isTypedArray } from "./isTypedArray.mjs"; +import { isBuffer } from "./isBuffer.mjs"; +import { isPlainObject } from "./isPlainObject.mjs"; +import { isArrayBuffer } from "./isArrayBuffer.mjs"; +import { isBlob } from "./isBlob.mjs"; +import { isBoolean } from "./isBoolean.mjs"; +import { isBrowser } from "./isBrowser.mjs"; +import { isDate } from "./isDate.mjs"; +import { isEmptyObject } from "./isEmptyObject.mjs"; +import { isEqualWith } from "./isEqualWith.mjs"; +import { isEqual } from "./isEqual.mjs"; +import { isError } from "./isError.mjs"; +import { isFile } from "./isFile.mjs"; +import { isFunction } from "./isFunction.mjs"; +import { isJSON } from "./isJSON.mjs"; +import { isJSONArray, isJSONObject, isJSONValue } from "./isJSONValue.mjs"; +import { isLength } from "./isLength.mjs"; +import { isMap } from "./isMap.mjs"; +import { isNil } from "./isNil.mjs"; +import { isNode } from "./isNode.mjs"; +import { isNotNil } from "./isNotNil.mjs"; +import { isNull } from "./isNull.mjs"; +import { isNumber } from "./isNumber.mjs"; +import { isPromise } from "./isPromise.mjs"; +import { isRegExp } from "./isRegExp.mjs"; +import { isSet } from "./isSet.mjs"; +import { isString } from "./isString.mjs"; +import { isSymbol } from "./isSymbol.mjs"; +import { isUndefined } from "./isUndefined.mjs"; +import { isWeakMap } from "./isWeakMap.mjs"; +import { isWeakSet } from "./isWeakSet.mjs"; +export { isArrayBuffer, isBlob, isBoolean, isBrowser, isBuffer, isDate, isEmptyObject, isEqual, isEqualWith, isError, isFile, isFunction, isJSON, isJSONArray, isJSONObject, isJSONValue, isLength, isMap, isNil, isNode, isNotNil, isNull, isNumber, isPlainObject, isPrimitive, isPromise, isRegExp, isSet, isString, isSymbol, isTypedArray, isUndefined, isWeakMap, isWeakSet }; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isArrayBuffer.d.mts b/tools/ui/node_modules/es-toolkit/dist/predicate/isArrayBuffer.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..d2495cc041dd98d9145eaeb29137fe7ff7c2beba --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isArrayBuffer.d.mts @@ -0,0 +1,21 @@ +//#region src/predicate/isArrayBuffer.d.ts +/** + * Checks if a given value is `ArrayBuffer`. + * + * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `ArrayBuffer`. + * + * @param {unknown} value The value to check if it is a `ArrayBuffer`. + * @returns {value is ArrayBuffer} Returns `true` if `value` is a `ArrayBuffer`, else `false`. + * + * @example + * const value1 = new ArrayBuffer(); + * const value2 = new Array(); + * const value3 = new Map(); + * + * console.log(isArrayBuffer(value1)); // true + * console.log(isArrayBuffer(value2)); // false + * console.log(isArrayBuffer(value3)); // false + */ +declare function isArrayBuffer(value: unknown): value is ArrayBuffer; +//#endregion +export { isArrayBuffer }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isArrayBuffer.d.ts b/tools/ui/node_modules/es-toolkit/dist/predicate/isArrayBuffer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d2495cc041dd98d9145eaeb29137fe7ff7c2beba --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isArrayBuffer.d.ts @@ -0,0 +1,21 @@ +//#region src/predicate/isArrayBuffer.d.ts +/** + * Checks if a given value is `ArrayBuffer`. + * + * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `ArrayBuffer`. + * + * @param {unknown} value The value to check if it is a `ArrayBuffer`. + * @returns {value is ArrayBuffer} Returns `true` if `value` is a `ArrayBuffer`, else `false`. + * + * @example + * const value1 = new ArrayBuffer(); + * const value2 = new Array(); + * const value3 = new Map(); + * + * console.log(isArrayBuffer(value1)); // true + * console.log(isArrayBuffer(value2)); // false + * console.log(isArrayBuffer(value3)); // false + */ +declare function isArrayBuffer(value: unknown): value is ArrayBuffer; +//#endregion +export { isArrayBuffer }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isArrayBuffer.js b/tools/ui/node_modules/es-toolkit/dist/predicate/isArrayBuffer.js new file mode 100644 index 0000000000000000000000000000000000000000..b8e78967067457e194a65a82b010e94c2958c487 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isArrayBuffer.js @@ -0,0 +1,23 @@ +//#region src/predicate/isArrayBuffer.ts +/** +* Checks if a given value is `ArrayBuffer`. +* +* This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `ArrayBuffer`. +* +* @param {unknown} value The value to check if it is a `ArrayBuffer`. +* @returns {value is ArrayBuffer} Returns `true` if `value` is a `ArrayBuffer`, else `false`. +* +* @example +* const value1 = new ArrayBuffer(); +* const value2 = new Array(); +* const value3 = new Map(); +* +* console.log(isArrayBuffer(value1)); // true +* console.log(isArrayBuffer(value2)); // false +* console.log(isArrayBuffer(value3)); // false +*/ +function isArrayBuffer(value) { + return value instanceof ArrayBuffer; +} +//#endregion +exports.isArrayBuffer = isArrayBuffer; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isArrayBuffer.mjs b/tools/ui/node_modules/es-toolkit/dist/predicate/isArrayBuffer.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0fc9f713d82e18e329958ee9f8635e3532e54871 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isArrayBuffer.mjs @@ -0,0 +1,23 @@ +//#region src/predicate/isArrayBuffer.ts +/** +* Checks if a given value is `ArrayBuffer`. +* +* This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `ArrayBuffer`. +* +* @param {unknown} value The value to check if it is a `ArrayBuffer`. +* @returns {value is ArrayBuffer} Returns `true` if `value` is a `ArrayBuffer`, else `false`. +* +* @example +* const value1 = new ArrayBuffer(); +* const value2 = new Array(); +* const value3 = new Map(); +* +* console.log(isArrayBuffer(value1)); // true +* console.log(isArrayBuffer(value2)); // false +* console.log(isArrayBuffer(value3)); // false +*/ +function isArrayBuffer(value) { + return value instanceof ArrayBuffer; +} +//#endregion +export { isArrayBuffer }; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isBlob.d.mts b/tools/ui/node_modules/es-toolkit/dist/predicate/isBlob.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..2ec8bebf5a5ee45ca2771c2f8c878a35f8181ae6 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isBlob.d.mts @@ -0,0 +1,20 @@ +//#region src/predicate/isBlob.d.ts +/** + * Checks if the given value is a Blob. + * + * This function tests whether the provided value is an instance of `Blob`. + * It returns `true` if the value is an instance of `Blob`, and `false` otherwise. + * + * @param {unknown} x - The value to test if it is a Blob. + * @returns {x is Blob} True if the value is a Blob, false otherwise. + * + * @example + * const value1 = new Blob(); + * const value2 = {}; + * + * console.log(isBlob(value1)); // true + * console.log(isBlob(value2)); // false + */ +declare function isBlob(x: unknown): x is Blob; +//#endregion +export { isBlob }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isBlob.d.ts b/tools/ui/node_modules/es-toolkit/dist/predicate/isBlob.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2ec8bebf5a5ee45ca2771c2f8c878a35f8181ae6 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isBlob.d.ts @@ -0,0 +1,20 @@ +//#region src/predicate/isBlob.d.ts +/** + * Checks if the given value is a Blob. + * + * This function tests whether the provided value is an instance of `Blob`. + * It returns `true` if the value is an instance of `Blob`, and `false` otherwise. + * + * @param {unknown} x - The value to test if it is a Blob. + * @returns {x is Blob} True if the value is a Blob, false otherwise. + * + * @example + * const value1 = new Blob(); + * const value2 = {}; + * + * console.log(isBlob(value1)); // true + * console.log(isBlob(value2)); // false + */ +declare function isBlob(x: unknown): x is Blob; +//#endregion +export { isBlob }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isBlob.js b/tools/ui/node_modules/es-toolkit/dist/predicate/isBlob.js new file mode 100644 index 0000000000000000000000000000000000000000..8b4ebd9458b016f730b26829e6c5f84880f9aabb --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isBlob.js @@ -0,0 +1,23 @@ +//#region src/predicate/isBlob.ts +/** +* Checks if the given value is a Blob. +* +* This function tests whether the provided value is an instance of `Blob`. +* It returns `true` if the value is an instance of `Blob`, and `false` otherwise. +* +* @param {unknown} x - The value to test if it is a Blob. +* @returns {x is Blob} True if the value is a Blob, false otherwise. +* +* @example +* const value1 = new Blob(); +* const value2 = {}; +* +* console.log(isBlob(value1)); // true +* console.log(isBlob(value2)); // false +*/ +function isBlob(x) { + if (typeof Blob === "undefined") return false; + return x instanceof Blob; +} +//#endregion +exports.isBlob = isBlob; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isBlob.mjs b/tools/ui/node_modules/es-toolkit/dist/predicate/isBlob.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c9fa1a5bca02ddd5de4afe10b4749a470bcdc729 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isBlob.mjs @@ -0,0 +1,23 @@ +//#region src/predicate/isBlob.ts +/** +* Checks if the given value is a Blob. +* +* This function tests whether the provided value is an instance of `Blob`. +* It returns `true` if the value is an instance of `Blob`, and `false` otherwise. +* +* @param {unknown} x - The value to test if it is a Blob. +* @returns {x is Blob} True if the value is a Blob, false otherwise. +* +* @example +* const value1 = new Blob(); +* const value2 = {}; +* +* console.log(isBlob(value1)); // true +* console.log(isBlob(value2)); // false +*/ +function isBlob(x) { + if (typeof Blob === "undefined") return false; + return x instanceof Blob; +} +//#endregion +export { isBlob }; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isBoolean.d.mts b/tools/ui/node_modules/es-toolkit/dist/predicate/isBoolean.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..2b911c26c23bc290621305bbe5f93553a44a53d5 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isBoolean.d.mts @@ -0,0 +1,26 @@ +//#region src/predicate/isBoolean.d.ts +/** + * Checks if the given value is boolean. + * + * This function tests whether the provided value is strictly `boolean`. + * It returns `true` if the value is `boolean`, and `false` otherwise. + * + * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `boolean`. + * + * @param {unknown} x - The Value to test if it is boolean. + * @returns {x is boolean} True if the value is boolean, false otherwise. + * + * @example + * + * const value1 = true; + * const value2 = 0; + * const value3 = 'abc'; + * + * console.log(isBoolean(value1)); // true + * console.log(isBoolean(value2)); // false + * console.log(isBoolean(value3)); // false + * + */ +declare function isBoolean(x: unknown): x is boolean; +//#endregion +export { isBoolean }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isBoolean.d.ts b/tools/ui/node_modules/es-toolkit/dist/predicate/isBoolean.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2b911c26c23bc290621305bbe5f93553a44a53d5 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isBoolean.d.ts @@ -0,0 +1,26 @@ +//#region src/predicate/isBoolean.d.ts +/** + * Checks if the given value is boolean. + * + * This function tests whether the provided value is strictly `boolean`. + * It returns `true` if the value is `boolean`, and `false` otherwise. + * + * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `boolean`. + * + * @param {unknown} x - The Value to test if it is boolean. + * @returns {x is boolean} True if the value is boolean, false otherwise. + * + * @example + * + * const value1 = true; + * const value2 = 0; + * const value3 = 'abc'; + * + * console.log(isBoolean(value1)); // true + * console.log(isBoolean(value2)); // false + * console.log(isBoolean(value3)); // false + * + */ +declare function isBoolean(x: unknown): x is boolean; +//#endregion +export { isBoolean }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isBoolean.js b/tools/ui/node_modules/es-toolkit/dist/predicate/isBoolean.js new file mode 100644 index 0000000000000000000000000000000000000000..86c8cca04110719cb66e8966babd92d91f16fd3e --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isBoolean.js @@ -0,0 +1,28 @@ +//#region src/predicate/isBoolean.ts +/** +* Checks if the given value is boolean. +* +* This function tests whether the provided value is strictly `boolean`. +* It returns `true` if the value is `boolean`, and `false` otherwise. +* +* This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `boolean`. +* +* @param {unknown} x - The Value to test if it is boolean. +* @returns {x is boolean} True if the value is boolean, false otherwise. +* +* @example +* +* const value1 = true; +* const value2 = 0; +* const value3 = 'abc'; +* +* console.log(isBoolean(value1)); // true +* console.log(isBoolean(value2)); // false +* console.log(isBoolean(value3)); // false +* +*/ +function isBoolean(x) { + return typeof x === "boolean"; +} +//#endregion +exports.isBoolean = isBoolean; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isBoolean.mjs b/tools/ui/node_modules/es-toolkit/dist/predicate/isBoolean.mjs new file mode 100644 index 0000000000000000000000000000000000000000..446c62899e516b6c85f57d41b6526526a182e20c --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isBoolean.mjs @@ -0,0 +1,28 @@ +//#region src/predicate/isBoolean.ts +/** +* Checks if the given value is boolean. +* +* This function tests whether the provided value is strictly `boolean`. +* It returns `true` if the value is `boolean`, and `false` otherwise. +* +* This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `boolean`. +* +* @param {unknown} x - The Value to test if it is boolean. +* @returns {x is boolean} True if the value is boolean, false otherwise. +* +* @example +* +* const value1 = true; +* const value2 = 0; +* const value3 = 'abc'; +* +* console.log(isBoolean(value1)); // true +* console.log(isBoolean(value2)); // false +* console.log(isBoolean(value3)); // false +* +*/ +function isBoolean(x) { + return typeof x === "boolean"; +} +//#endregion +export { isBoolean }; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isBrowser.d.mts b/tools/ui/node_modules/es-toolkit/dist/predicate/isBrowser.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..018d865bcc908af27e543aa32255e20ccdbaf874 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isBrowser.d.mts @@ -0,0 +1,18 @@ +//#region src/predicate/isBrowser.d.ts +/** + * Checks if the current environment is a browser. + * + * This function checks for the existence of the `window.document` property, + * which only exists in browser environments. + * + * @returns {boolean} `true` if the current environment is a browser, otherwise `false`. + * + * @example + * if (isBrowser()) { + * console.log("This is running in a browser"); + * document.getElementById('app').innerHTML = 'Hello World'; + * } + */ +declare function isBrowser(): boolean; +//#endregion +export { isBrowser }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isBrowser.d.ts b/tools/ui/node_modules/es-toolkit/dist/predicate/isBrowser.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..018d865bcc908af27e543aa32255e20ccdbaf874 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isBrowser.d.ts @@ -0,0 +1,18 @@ +//#region src/predicate/isBrowser.d.ts +/** + * Checks if the current environment is a browser. + * + * This function checks for the existence of the `window.document` property, + * which only exists in browser environments. + * + * @returns {boolean} `true` if the current environment is a browser, otherwise `false`. + * + * @example + * if (isBrowser()) { + * console.log("This is running in a browser"); + * document.getElementById('app').innerHTML = 'Hello World'; + * } + */ +declare function isBrowser(): boolean; +//#endregion +export { isBrowser }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isBrowser.js b/tools/ui/node_modules/es-toolkit/dist/predicate/isBrowser.js new file mode 100644 index 0000000000000000000000000000000000000000..e9e91bbe81cbea05ef5bcf1459df067ed4dec8e8 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isBrowser.js @@ -0,0 +1,20 @@ +//#region src/predicate/isBrowser.ts +/** +* Checks if the current environment is a browser. +* +* This function checks for the existence of the `window.document` property, +* which only exists in browser environments. +* +* @returns {boolean} `true` if the current environment is a browser, otherwise `false`. +* +* @example +* if (isBrowser()) { +* console.log("This is running in a browser"); +* document.getElementById('app').innerHTML = 'Hello World'; +* } +*/ +function isBrowser() { + return typeof window !== "undefined" && window?.document != null; +} +//#endregion +exports.isBrowser = isBrowser; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isBrowser.mjs b/tools/ui/node_modules/es-toolkit/dist/predicate/isBrowser.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6b8f4cfcec85a92d785126d63c8bb8ca461a9911 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isBrowser.mjs @@ -0,0 +1,20 @@ +//#region src/predicate/isBrowser.ts +/** +* Checks if the current environment is a browser. +* +* This function checks for the existence of the `window.document` property, +* which only exists in browser environments. +* +* @returns {boolean} `true` if the current environment is a browser, otherwise `false`. +* +* @example +* if (isBrowser()) { +* console.log("This is running in a browser"); +* document.getElementById('app').innerHTML = 'Hello World'; +* } +*/ +function isBrowser() { + return typeof window !== "undefined" && window?.document != null; +} +//#endregion +export { isBrowser }; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isBuffer.d.mts b/tools/ui/node_modules/es-toolkit/dist/predicate/isBuffer.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..63158447320eb89f98872b4da40d7094585deb2d --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isBuffer.d.mts @@ -0,0 +1,22 @@ +//#region src/predicate/isBuffer.d.ts +/** + * Checks if the given value is a Buffer instance. + * + * This function tests whether the provided value is an instance of Buffer. + * It returns `true` if the value is a Buffer, and `false` otherwise. + * + * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `Buffer`. + * + * @param {unknown} x - The value to check if it is a Buffer. + * @returns {boolean} Returns `true` if `x` is a Buffer, else `false`. + * + * @example + * const buffer = Buffer.from("test"); + * console.log(isBuffer(buffer)); // true + * + * const notBuffer = "not a buffer"; + * console.log(isBuffer(notBuffer)); // false + */ +declare function isBuffer(x: unknown): boolean; +//#endregion +export { isBuffer }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isBuffer.d.ts b/tools/ui/node_modules/es-toolkit/dist/predicate/isBuffer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..63158447320eb89f98872b4da40d7094585deb2d --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isBuffer.d.ts @@ -0,0 +1,22 @@ +//#region src/predicate/isBuffer.d.ts +/** + * Checks if the given value is a Buffer instance. + * + * This function tests whether the provided value is an instance of Buffer. + * It returns `true` if the value is a Buffer, and `false` otherwise. + * + * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `Buffer`. + * + * @param {unknown} x - The value to check if it is a Buffer. + * @returns {boolean} Returns `true` if `x` is a Buffer, else `false`. + * + * @example + * const buffer = Buffer.from("test"); + * console.log(isBuffer(buffer)); // true + * + * const notBuffer = "not a buffer"; + * console.log(isBuffer(notBuffer)); // false + */ +declare function isBuffer(x: unknown): boolean; +//#endregion +export { isBuffer }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isBuffer.js b/tools/ui/node_modules/es-toolkit/dist/predicate/isBuffer.js new file mode 100644 index 0000000000000000000000000000000000000000..5549eb3ac053ddc6be3993b66660e16c9d452650 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isBuffer.js @@ -0,0 +1,25 @@ +const require_globalThis = require("../_internal/globalThis.js"); +//#region src/predicate/isBuffer.ts +/** +* Checks if the given value is a Buffer instance. +* +* This function tests whether the provided value is an instance of Buffer. +* It returns `true` if the value is a Buffer, and `false` otherwise. +* +* This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `Buffer`. +* +* @param {unknown} x - The value to check if it is a Buffer. +* @returns {boolean} Returns `true` if `x` is a Buffer, else `false`. +* +* @example +* const buffer = Buffer.from("test"); +* console.log(isBuffer(buffer)); // true +* +* const notBuffer = "not a buffer"; +* console.log(isBuffer(notBuffer)); // false +*/ +function isBuffer(x) { + return typeof require_globalThis.globalThis_.Buffer !== "undefined" && require_globalThis.globalThis_.Buffer.isBuffer(x); +} +//#endregion +exports.isBuffer = isBuffer; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isBuffer.mjs b/tools/ui/node_modules/es-toolkit/dist/predicate/isBuffer.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5e4885b52e3db0363c8407cf6475b01b84293381 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isBuffer.mjs @@ -0,0 +1,25 @@ +import { globalThis_ } from "../_internal/globalThis.mjs"; +//#region src/predicate/isBuffer.ts +/** +* Checks if the given value is a Buffer instance. +* +* This function tests whether the provided value is an instance of Buffer. +* It returns `true` if the value is a Buffer, and `false` otherwise. +* +* This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `Buffer`. +* +* @param {unknown} x - The value to check if it is a Buffer. +* @returns {boolean} Returns `true` if `x` is a Buffer, else `false`. +* +* @example +* const buffer = Buffer.from("test"); +* console.log(isBuffer(buffer)); // true +* +* const notBuffer = "not a buffer"; +* console.log(isBuffer(notBuffer)); // false +*/ +function isBuffer(x) { + return typeof globalThis_.Buffer !== "undefined" && globalThis_.Buffer.isBuffer(x); +} +//#endregion +export { isBuffer }; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isDate.d.mts b/tools/ui/node_modules/es-toolkit/dist/predicate/isDate.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..c4517f0719d527f118622e38917c6b7e8d191bbd --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isDate.d.mts @@ -0,0 +1,17 @@ +//#region src/predicate/isDate.d.ts +/** + * Checks if `value` is a Date object. + * + * @param {unknown} value The value to check. + * @returns {value is Date} Returns `true` if `value` is a Date object, `false` otherwise. + * + * @example + * const value1 = new Date(); + * const value2 = '2024-01-01'; + * + * console.log(isDate(value1)); // true + * console.log(isDate(value2)); // false + */ +declare function isDate(value: unknown): value is Date; +//#endregion +export { isDate }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isDate.d.ts b/tools/ui/node_modules/es-toolkit/dist/predicate/isDate.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c4517f0719d527f118622e38917c6b7e8d191bbd --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isDate.d.ts @@ -0,0 +1,17 @@ +//#region src/predicate/isDate.d.ts +/** + * Checks if `value` is a Date object. + * + * @param {unknown} value The value to check. + * @returns {value is Date} Returns `true` if `value` is a Date object, `false` otherwise. + * + * @example + * const value1 = new Date(); + * const value2 = '2024-01-01'; + * + * console.log(isDate(value1)); // true + * console.log(isDate(value2)); // false + */ +declare function isDate(value: unknown): value is Date; +//#endregion +export { isDate }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isDate.js b/tools/ui/node_modules/es-toolkit/dist/predicate/isDate.js new file mode 100644 index 0000000000000000000000000000000000000000..0defcf7c51383819b7aad6e07a131d5dff774c47 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isDate.js @@ -0,0 +1,19 @@ +//#region src/predicate/isDate.ts +/** +* Checks if `value` is a Date object. +* +* @param {unknown} value The value to check. +* @returns {value is Date} Returns `true` if `value` is a Date object, `false` otherwise. +* +* @example +* const value1 = new Date(); +* const value2 = '2024-01-01'; +* +* console.log(isDate(value1)); // true +* console.log(isDate(value2)); // false +*/ +function isDate(value) { + return value instanceof Date; +} +//#endregion +exports.isDate = isDate; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isDate.mjs b/tools/ui/node_modules/es-toolkit/dist/predicate/isDate.mjs new file mode 100644 index 0000000000000000000000000000000000000000..01d3602294f0b261f274606af5bf660ce48f6429 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isDate.mjs @@ -0,0 +1,19 @@ +//#region src/predicate/isDate.ts +/** +* Checks if `value` is a Date object. +* +* @param {unknown} value The value to check. +* @returns {value is Date} Returns `true` if `value` is a Date object, `false` otherwise. +* +* @example +* const value1 = new Date(); +* const value2 = '2024-01-01'; +* +* console.log(isDate(value1)); // true +* console.log(isDate(value2)); // false +*/ +function isDate(value) { + return value instanceof Date; +} +//#endregion +export { isDate }; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isEmptyObject.d.mts b/tools/ui/node_modules/es-toolkit/dist/predicate/isEmptyObject.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..1fe6d85f326728b68679779f866444c054145da9 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isEmptyObject.d.mts @@ -0,0 +1,16 @@ +//#region src/predicate/isEmptyObject.d.ts +/** + * Checks if a value is an empty plain object. + * + * @param {unknown} value - The value to check. + * @returns {value is Record} - True if the value is an empty plain object, otherwise false. + * + * @example + * isEmptyObject({}); // true + * isEmptyObject({ a: 1 }); // false + * isEmptyObject([]); // false + * isEmptyObject(null); // false + */ +declare function isEmptyObject(value: unknown): value is Record; +//#endregion +export { isEmptyObject }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isEmptyObject.d.ts b/tools/ui/node_modules/es-toolkit/dist/predicate/isEmptyObject.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1fe6d85f326728b68679779f866444c054145da9 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isEmptyObject.d.ts @@ -0,0 +1,16 @@ +//#region src/predicate/isEmptyObject.d.ts +/** + * Checks if a value is an empty plain object. + * + * @param {unknown} value - The value to check. + * @returns {value is Record} - True if the value is an empty plain object, otherwise false. + * + * @example + * isEmptyObject({}); // true + * isEmptyObject({ a: 1 }); // false + * isEmptyObject([]); // false + * isEmptyObject(null); // false + */ +declare function isEmptyObject(value: unknown): value is Record; +//#endregion +export { isEmptyObject }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isEmptyObject.js b/tools/ui/node_modules/es-toolkit/dist/predicate/isEmptyObject.js new file mode 100644 index 0000000000000000000000000000000000000000..003ef97212fdc985d055c5aeea06e631f6251b7e --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isEmptyObject.js @@ -0,0 +1,19 @@ +const require_isPlainObject = require("./isPlainObject.js"); +//#region src/predicate/isEmptyObject.ts +/** +* Checks if a value is an empty plain object. +* +* @param {unknown} value - The value to check. +* @returns {value is Record} - True if the value is an empty plain object, otherwise false. +* +* @example +* isEmptyObject({}); // true +* isEmptyObject({ a: 1 }); // false +* isEmptyObject([]); // false +* isEmptyObject(null); // false +*/ +function isEmptyObject(value) { + return require_isPlainObject.isPlainObject(value) && Object.keys(value).length === 0; +} +//#endregion +exports.isEmptyObject = isEmptyObject; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isEmptyObject.mjs b/tools/ui/node_modules/es-toolkit/dist/predicate/isEmptyObject.mjs new file mode 100644 index 0000000000000000000000000000000000000000..25eaa2af0f4c9d2b82f8728f9254b1f3d96d70a3 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isEmptyObject.mjs @@ -0,0 +1,19 @@ +import { isPlainObject } from "./isPlainObject.mjs"; +//#region src/predicate/isEmptyObject.ts +/** +* Checks if a value is an empty plain object. +* +* @param {unknown} value - The value to check. +* @returns {value is Record} - True if the value is an empty plain object, otherwise false. +* +* @example +* isEmptyObject({}); // true +* isEmptyObject({ a: 1 }); // false +* isEmptyObject([]); // false +* isEmptyObject(null); // false +*/ +function isEmptyObject(value) { + return isPlainObject(value) && Object.keys(value).length === 0; +} +//#endregion +export { isEmptyObject }; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isEqual.d.mts b/tools/ui/node_modules/es-toolkit/dist/predicate/isEqual.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..943c04299fe795dcafc1eb187ba1bec6fe1e64b2 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isEqual.d.mts @@ -0,0 +1,18 @@ +//#region src/predicate/isEqual.d.ts +/** + * Checks if two values are equal, including support for `Date`, `RegExp`, and deep object comparison. + * + * @param {unknown} a - The first value to compare. + * @param {unknown} b - The second value to compare. + * @returns {boolean} `true` if the values are equal, otherwise `false`. + * + * @example + * isEqual(1, 1); // true + * isEqual({ a: 1 }, { a: 1 }); // true + * isEqual(/abc/g, /abc/g); // true + * isEqual(new Date('2020-01-01'), new Date('2020-01-01')); // true + * isEqual([1, 2, 3], [1, 2, 3]); // true + */ +declare function isEqual(a: any, b: any): boolean; +//#endregion +export { isEqual }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isEqual.d.ts b/tools/ui/node_modules/es-toolkit/dist/predicate/isEqual.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..943c04299fe795dcafc1eb187ba1bec6fe1e64b2 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isEqual.d.ts @@ -0,0 +1,18 @@ +//#region src/predicate/isEqual.d.ts +/** + * Checks if two values are equal, including support for `Date`, `RegExp`, and deep object comparison. + * + * @param {unknown} a - The first value to compare. + * @param {unknown} b - The second value to compare. + * @returns {boolean} `true` if the values are equal, otherwise `false`. + * + * @example + * isEqual(1, 1); // true + * isEqual({ a: 1 }, { a: 1 }); // true + * isEqual(/abc/g, /abc/g); // true + * isEqual(new Date('2020-01-01'), new Date('2020-01-01')); // true + * isEqual([1, 2, 3], [1, 2, 3]); // true + */ +declare function isEqual(a: any, b: any): boolean; +//#endregion +export { isEqual }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isEqual.js b/tools/ui/node_modules/es-toolkit/dist/predicate/isEqual.js new file mode 100644 index 0000000000000000000000000000000000000000..fb20c7f4a4df8fa9b335bd025ab9c89212706569 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isEqual.js @@ -0,0 +1,22 @@ +const require_noop = require("../function/noop.js"); +const require_isEqualWith = require("./isEqualWith.js"); +//#region src/predicate/isEqual.ts +/** +* Checks if two values are equal, including support for `Date`, `RegExp`, and deep object comparison. +* +* @param {unknown} a - The first value to compare. +* @param {unknown} b - The second value to compare. +* @returns {boolean} `true` if the values are equal, otherwise `false`. +* +* @example +* isEqual(1, 1); // true +* isEqual({ a: 1 }, { a: 1 }); // true +* isEqual(/abc/g, /abc/g); // true +* isEqual(new Date('2020-01-01'), new Date('2020-01-01')); // true +* isEqual([1, 2, 3], [1, 2, 3]); // true +*/ +function isEqual(a, b) { + return require_isEqualWith.isEqualWith(a, b, require_noop.noop); +} +//#endregion +exports.isEqual = isEqual; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isEqual.mjs b/tools/ui/node_modules/es-toolkit/dist/predicate/isEqual.mjs new file mode 100644 index 0000000000000000000000000000000000000000..feedcda5cae05b3c04265a61f024fbf2c69f6a4f --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isEqual.mjs @@ -0,0 +1,22 @@ +import { noop } from "../function/noop.mjs"; +import { isEqualWith } from "./isEqualWith.mjs"; +//#region src/predicate/isEqual.ts +/** +* Checks if two values are equal, including support for `Date`, `RegExp`, and deep object comparison. +* +* @param {unknown} a - The first value to compare. +* @param {unknown} b - The second value to compare. +* @returns {boolean} `true` if the values are equal, otherwise `false`. +* +* @example +* isEqual(1, 1); // true +* isEqual({ a: 1 }, { a: 1 }); // true +* isEqual(/abc/g, /abc/g); // true +* isEqual(new Date('2020-01-01'), new Date('2020-01-01')); // true +* isEqual([1, 2, 3], [1, 2, 3]); // true +*/ +function isEqual(a, b) { + return isEqualWith(a, b, noop); +} +//#endregion +export { isEqual }; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isEqualWith.d.mts b/tools/ui/node_modules/es-toolkit/dist/predicate/isEqualWith.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..efab15e1cc3bdf4765af418940b282cd4dc82b2b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isEqualWith.d.mts @@ -0,0 +1,39 @@ +//#region src/predicate/isEqualWith.d.ts +/** + * Compares two values for equality using a custom comparison function. + * + * The custom function allows for fine-tuned control over the comparison process. If it returns a boolean, that result determines the equality. If it returns undefined, the function falls back to the default equality comparison. + * + * This function also uses the custom equality function to compare values inside objects, + * arrays, maps, sets, and other complex structures, ensuring a deep comparison. + * + * This approach provides flexibility in handling complex comparisons while maintaining efficient default behavior for simpler cases. + * + * The custom comparison function can take up to six parameters: + * - `x`: The value from the first object `a`. + * - `y`: The value from the second object `b`. + * - `property`: The property key used to get `x` and `y`. + * - `xParent`: The parent of the first value `x`. + * - `yParent`: The parent of the second value `y`. + * - `stack`: An internal stack (Map) to handle circular references. + * + * @param {unknown} a - The first value to compare. + * @param {unknown} b - The second value to compare. + * @param {(x: any, y: any, property?: PropertyKey, xParent?: any, yParent?: any, stack?: Map) => boolean | void} areValuesEqual - A function to customize the comparison. + * If it returns a boolean, that result will be used. If it returns undefined, + * the default equality comparison will be used. + * @returns {boolean} `true` if the values are equal according to the customizer, otherwise `false`. + * + * @example + * const customizer = (a, b) => { + * if (typeof a === 'string' && typeof b === 'string') { + * return a.toLowerCase() === b.toLowerCase(); + * } + * }; + * isEqualWith('Hello', 'hello', customizer); // true + * isEqualWith({ a: 'Hello' }, { a: 'hello' }, customizer); // true + * isEqualWith([1, 2, 3], [1, 2, 3], customizer); // true + */ +declare function isEqualWith(a: any, b: any, areValuesEqual: (x: any, y: any, property?: PropertyKey, xParent?: any, yParent?: any, stack?: Map) => boolean | void): boolean; +//#endregion +export { isEqualWith }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isEqualWith.d.ts b/tools/ui/node_modules/es-toolkit/dist/predicate/isEqualWith.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..efab15e1cc3bdf4765af418940b282cd4dc82b2b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isEqualWith.d.ts @@ -0,0 +1,39 @@ +//#region src/predicate/isEqualWith.d.ts +/** + * Compares two values for equality using a custom comparison function. + * + * The custom function allows for fine-tuned control over the comparison process. If it returns a boolean, that result determines the equality. If it returns undefined, the function falls back to the default equality comparison. + * + * This function also uses the custom equality function to compare values inside objects, + * arrays, maps, sets, and other complex structures, ensuring a deep comparison. + * + * This approach provides flexibility in handling complex comparisons while maintaining efficient default behavior for simpler cases. + * + * The custom comparison function can take up to six parameters: + * - `x`: The value from the first object `a`. + * - `y`: The value from the second object `b`. + * - `property`: The property key used to get `x` and `y`. + * - `xParent`: The parent of the first value `x`. + * - `yParent`: The parent of the second value `y`. + * - `stack`: An internal stack (Map) to handle circular references. + * + * @param {unknown} a - The first value to compare. + * @param {unknown} b - The second value to compare. + * @param {(x: any, y: any, property?: PropertyKey, xParent?: any, yParent?: any, stack?: Map) => boolean | void} areValuesEqual - A function to customize the comparison. + * If it returns a boolean, that result will be used. If it returns undefined, + * the default equality comparison will be used. + * @returns {boolean} `true` if the values are equal according to the customizer, otherwise `false`. + * + * @example + * const customizer = (a, b) => { + * if (typeof a === 'string' && typeof b === 'string') { + * return a.toLowerCase() === b.toLowerCase(); + * } + * }; + * isEqualWith('Hello', 'hello', customizer); // true + * isEqualWith({ a: 'Hello' }, { a: 'hello' }, customizer); // true + * isEqualWith([1, 2, 3], [1, 2, 3], customizer); // true + */ +declare function isEqualWith(a: any, b: any, areValuesEqual: (x: any, y: any, property?: PropertyKey, xParent?: any, yParent?: any, stack?: Map) => boolean | void): boolean; +//#endregion +export { isEqualWith }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isEqualWith.js b/tools/ui/node_modules/es-toolkit/dist/predicate/isEqualWith.js new file mode 100644 index 0000000000000000000000000000000000000000..ce4aa6f8e12119fc2a37da53772d03880ffcd71d --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isEqualWith.js @@ -0,0 +1,153 @@ +const require_getSymbols = require("../compat/_internal/getSymbols.js"); +const require_getTag = require("../compat/_internal/getTag.js"); +const require_tags = require("../compat/_internal/tags.js"); +const require_isBuffer = require("./isBuffer.js"); +const require_isPlainObject = require("./isPlainObject.js"); +const require_isEqualsSameValueZero = require("../_internal/isEqualsSameValueZero.js"); +require("../compat/util/eq.js"); +//#region src/predicate/isEqualWith.ts +/** +* Compares two values for equality using a custom comparison function. +* +* The custom function allows for fine-tuned control over the comparison process. If it returns a boolean, that result determines the equality. If it returns undefined, the function falls back to the default equality comparison. +* +* This function also uses the custom equality function to compare values inside objects, +* arrays, maps, sets, and other complex structures, ensuring a deep comparison. +* +* This approach provides flexibility in handling complex comparisons while maintaining efficient default behavior for simpler cases. +* +* The custom comparison function can take up to six parameters: +* - `x`: The value from the first object `a`. +* - `y`: The value from the second object `b`. +* - `property`: The property key used to get `x` and `y`. +* - `xParent`: The parent of the first value `x`. +* - `yParent`: The parent of the second value `y`. +* - `stack`: An internal stack (Map) to handle circular references. +* +* @param {unknown} a - The first value to compare. +* @param {unknown} b - The second value to compare. +* @param {(x: any, y: any, property?: PropertyKey, xParent?: any, yParent?: any, stack?: Map) => boolean | void} areValuesEqual - A function to customize the comparison. +* If it returns a boolean, that result will be used. If it returns undefined, +* the default equality comparison will be used. +* @returns {boolean} `true` if the values are equal according to the customizer, otherwise `false`. +* +* @example +* const customizer = (a, b) => { +* if (typeof a === 'string' && typeof b === 'string') { +* return a.toLowerCase() === b.toLowerCase(); +* } +* }; +* isEqualWith('Hello', 'hello', customizer); // true +* isEqualWith({ a: 'Hello' }, { a: 'hello' }, customizer); // true +* isEqualWith([1, 2, 3], [1, 2, 3], customizer); // true +*/ +function isEqualWith(a, b, areValuesEqual) { + return isEqualWithImpl(a, b, void 0, void 0, void 0, void 0, areValuesEqual); +} +function isEqualWithImpl(a, b, property, aParent, bParent, stack, areValuesEqual) { + const result = areValuesEqual(a, b, property, aParent, bParent, stack); + if (result !== void 0) return result; + if (typeof a === typeof b) switch (typeof a) { + case "bigint": + case "string": + case "boolean": + case "symbol": + case "undefined": return a === b; + case "number": return a === b || Object.is(a, b); + case "function": return a === b; + case "object": return areObjectsEqual(a, b, stack, areValuesEqual); + } + return areObjectsEqual(a, b, stack, areValuesEqual); +} +function areObjectsEqual(a, b, stack, areValuesEqual) { + if (Object.is(a, b)) return true; + let aTag = require_getTag.getTag(a); + let bTag = require_getTag.getTag(b); + if (aTag === "[object Arguments]") aTag = require_tags.objectTag; + if (bTag === "[object Arguments]") bTag = require_tags.objectTag; + if (aTag !== bTag) return false; + switch (aTag) { + case require_tags.stringTag: return a.toString() === b.toString(); + case require_tags.numberTag: { + const x = a.valueOf(); + const y = b.valueOf(); + return require_isEqualsSameValueZero.isEqualsSameValueZero(x, y); + } + case require_tags.booleanTag: + case require_tags.dateTag: + case require_tags.symbolTag: return Object.is(a.valueOf(), b.valueOf()); + case require_tags.regexpTag: return a.source === b.source && a.flags === b.flags; + case require_tags.functionTag: return a === b; + } + stack = stack ?? /* @__PURE__ */ new Map(); + const aStack = stack.get(a); + const bStack = stack.get(b); + if (aStack != null && bStack != null) return aStack === b; + stack.set(a, b); + stack.set(b, a); + try { + switch (aTag) { + case require_tags.mapTag: + if (a.size !== b.size) return false; + for (const [key, value] of a.entries()) if (!b.has(key) || !isEqualWithImpl(value, b.get(key), key, a, b, stack, areValuesEqual)) return false; + return true; + case require_tags.setTag: { + if (a.size !== b.size) return false; + const aValues = Array.from(a.values()); + const bValues = Array.from(b.values()); + for (let i = 0; i < aValues.length; i++) { + const aValue = aValues[i]; + const index = bValues.findIndex((bValue) => { + return isEqualWithImpl(aValue, bValue, void 0, a, b, stack, areValuesEqual); + }); + if (index === -1) return false; + bValues.splice(index, 1); + } + return true; + } + case require_tags.arrayTag: + case require_tags.uint8ArrayTag: + case require_tags.uint8ClampedArrayTag: + case require_tags.uint16ArrayTag: + case require_tags.uint32ArrayTag: + case require_tags.bigUint64ArrayTag: + case require_tags.int8ArrayTag: + case require_tags.int16ArrayTag: + case require_tags.int32ArrayTag: + case require_tags.bigInt64ArrayTag: + case require_tags.float32ArrayTag: + case require_tags.float64ArrayTag: + if (require_isBuffer.isBuffer(a) !== require_isBuffer.isBuffer(b)) return false; + if (a.length !== b.length) return false; + for (let i = 0; i < a.length; i++) if (!isEqualWithImpl(a[i], b[i], i, a, b, stack, areValuesEqual)) return false; + return true; + case require_tags.arrayBufferTag: + if (a.byteLength !== b.byteLength) return false; + return areObjectsEqual(new Uint8Array(a), new Uint8Array(b), stack, areValuesEqual); + case require_tags.dataViewTag: + if (a.byteLength !== b.byteLength || a.byteOffset !== b.byteOffset) return false; + return areObjectsEqual(new Uint8Array(a), new Uint8Array(b), stack, areValuesEqual); + case require_tags.errorTag: return a.name === b.name && a.message === b.message; + case require_tags.objectTag: { + if (!(areObjectsEqual(a.constructor, b.constructor, stack, areValuesEqual) || require_isPlainObject.isPlainObject(a) && require_isPlainObject.isPlainObject(b))) return false; + const aKeys = [...Object.keys(a), ...require_getSymbols.getSymbols(a)]; + const bKeys = [...Object.keys(b), ...require_getSymbols.getSymbols(b)]; + if (aKeys.length !== bKeys.length) return false; + for (let i = 0; i < aKeys.length; i++) { + const propKey = aKeys[i]; + const aProp = a[propKey]; + if (!Object.hasOwn(b, propKey)) return false; + const bProp = b[propKey]; + if (!isEqualWithImpl(aProp, bProp, propKey, a, b, stack, areValuesEqual)) return false; + } + return true; + } + default: return false; + } + } finally { + stack.delete(a); + stack.delete(b); + } +} +//#endregion +exports.isEqualWith = isEqualWith; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isEqualWith.mjs b/tools/ui/node_modules/es-toolkit/dist/predicate/isEqualWith.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0e129799772989ae91cfe5d844e525a2493a00c7 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isEqualWith.mjs @@ -0,0 +1,149 @@ +import { getSymbols } from "../compat/_internal/getSymbols.mjs"; +import { getTag } from "../compat/_internal/getTag.mjs"; +import { arrayBufferTag, arrayTag, bigInt64ArrayTag, bigUint64ArrayTag, booleanTag, dataViewTag, dateTag, errorTag, float32ArrayTag, float64ArrayTag, functionTag, int16ArrayTag, int32ArrayTag, int8ArrayTag, mapTag, numberTag, objectTag, regexpTag, setTag, stringTag, symbolTag, uint16ArrayTag, uint32ArrayTag, uint8ArrayTag, uint8ClampedArrayTag } from "../compat/_internal/tags.mjs"; +import { isBuffer } from "./isBuffer.mjs"; +import { isPlainObject } from "./isPlainObject.mjs"; +import { isEqualsSameValueZero } from "../_internal/isEqualsSameValueZero.mjs"; +import "../compat/util/eq.mjs"; +//#region src/predicate/isEqualWith.ts +/** +* Compares two values for equality using a custom comparison function. +* +* The custom function allows for fine-tuned control over the comparison process. If it returns a boolean, that result determines the equality. If it returns undefined, the function falls back to the default equality comparison. +* +* This function also uses the custom equality function to compare values inside objects, +* arrays, maps, sets, and other complex structures, ensuring a deep comparison. +* +* This approach provides flexibility in handling complex comparisons while maintaining efficient default behavior for simpler cases. +* +* The custom comparison function can take up to six parameters: +* - `x`: The value from the first object `a`. +* - `y`: The value from the second object `b`. +* - `property`: The property key used to get `x` and `y`. +* - `xParent`: The parent of the first value `x`. +* - `yParent`: The parent of the second value `y`. +* - `stack`: An internal stack (Map) to handle circular references. +* +* @param {unknown} a - The first value to compare. +* @param {unknown} b - The second value to compare. +* @param {(x: any, y: any, property?: PropertyKey, xParent?: any, yParent?: any, stack?: Map) => boolean | void} areValuesEqual - A function to customize the comparison. +* If it returns a boolean, that result will be used. If it returns undefined, +* the default equality comparison will be used. +* @returns {boolean} `true` if the values are equal according to the customizer, otherwise `false`. +* +* @example +* const customizer = (a, b) => { +* if (typeof a === 'string' && typeof b === 'string') { +* return a.toLowerCase() === b.toLowerCase(); +* } +* }; +* isEqualWith('Hello', 'hello', customizer); // true +* isEqualWith({ a: 'Hello' }, { a: 'hello' }, customizer); // true +* isEqualWith([1, 2, 3], [1, 2, 3], customizer); // true +*/ +function isEqualWith(a, b, areValuesEqual) { + return isEqualWithImpl(a, b, void 0, void 0, void 0, void 0, areValuesEqual); +} +function isEqualWithImpl(a, b, property, aParent, bParent, stack, areValuesEqual) { + const result = areValuesEqual(a, b, property, aParent, bParent, stack); + if (result !== void 0) return result; + if (typeof a === typeof b) switch (typeof a) { + case "bigint": + case "string": + case "boolean": + case "symbol": + case "undefined": return a === b; + case "number": return a === b || Object.is(a, b); + case "function": return a === b; + case "object": return areObjectsEqual(a, b, stack, areValuesEqual); + } + return areObjectsEqual(a, b, stack, areValuesEqual); +} +function areObjectsEqual(a, b, stack, areValuesEqual) { + if (Object.is(a, b)) return true; + let aTag = getTag(a); + let bTag = getTag(b); + if (aTag === "[object Arguments]") aTag = objectTag; + if (bTag === "[object Arguments]") bTag = objectTag; + if (aTag !== bTag) return false; + switch (aTag) { + case stringTag: return a.toString() === b.toString(); + case numberTag: return isEqualsSameValueZero(a.valueOf(), b.valueOf()); + case booleanTag: + case dateTag: + case symbolTag: return Object.is(a.valueOf(), b.valueOf()); + case regexpTag: return a.source === b.source && a.flags === b.flags; + case functionTag: return a === b; + } + stack = stack ?? /* @__PURE__ */ new Map(); + const aStack = stack.get(a); + const bStack = stack.get(b); + if (aStack != null && bStack != null) return aStack === b; + stack.set(a, b); + stack.set(b, a); + try { + switch (aTag) { + case mapTag: + if (a.size !== b.size) return false; + for (const [key, value] of a.entries()) if (!b.has(key) || !isEqualWithImpl(value, b.get(key), key, a, b, stack, areValuesEqual)) return false; + return true; + case setTag: { + if (a.size !== b.size) return false; + const aValues = Array.from(a.values()); + const bValues = Array.from(b.values()); + for (let i = 0; i < aValues.length; i++) { + const aValue = aValues[i]; + const index = bValues.findIndex((bValue) => { + return isEqualWithImpl(aValue, bValue, void 0, a, b, stack, areValuesEqual); + }); + if (index === -1) return false; + bValues.splice(index, 1); + } + return true; + } + case arrayTag: + case uint8ArrayTag: + case uint8ClampedArrayTag: + case uint16ArrayTag: + case uint32ArrayTag: + case bigUint64ArrayTag: + case int8ArrayTag: + case int16ArrayTag: + case int32ArrayTag: + case bigInt64ArrayTag: + case float32ArrayTag: + case float64ArrayTag: + if (isBuffer(a) !== isBuffer(b)) return false; + if (a.length !== b.length) return false; + for (let i = 0; i < a.length; i++) if (!isEqualWithImpl(a[i], b[i], i, a, b, stack, areValuesEqual)) return false; + return true; + case arrayBufferTag: + if (a.byteLength !== b.byteLength) return false; + return areObjectsEqual(new Uint8Array(a), new Uint8Array(b), stack, areValuesEqual); + case dataViewTag: + if (a.byteLength !== b.byteLength || a.byteOffset !== b.byteOffset) return false; + return areObjectsEqual(new Uint8Array(a), new Uint8Array(b), stack, areValuesEqual); + case errorTag: return a.name === b.name && a.message === b.message; + case objectTag: { + if (!(areObjectsEqual(a.constructor, b.constructor, stack, areValuesEqual) || isPlainObject(a) && isPlainObject(b))) return false; + const aKeys = [...Object.keys(a), ...getSymbols(a)]; + const bKeys = [...Object.keys(b), ...getSymbols(b)]; + if (aKeys.length !== bKeys.length) return false; + for (let i = 0; i < aKeys.length; i++) { + const propKey = aKeys[i]; + const aProp = a[propKey]; + if (!Object.hasOwn(b, propKey)) return false; + const bProp = b[propKey]; + if (!isEqualWithImpl(aProp, bProp, propKey, a, b, stack, areValuesEqual)) return false; + } + return true; + } + default: return false; + } + } finally { + stack.delete(a); + stack.delete(b); + } +} +//#endregion +export { isEqualWith }; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isError.d.mts b/tools/ui/node_modules/es-toolkit/dist/predicate/isError.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..4dd0f32e2e925fce7f18d9463adf280a0c0b118a --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isError.d.mts @@ -0,0 +1,17 @@ +//#region src/predicate/isError.d.ts +/** + * Checks if `value` is an Error object. + * + * @param {unknown} value The value to check. + * @returns {value is Error} Returns `true` if `value` is an Error object, `false` otherwise. + * + * @example + * ```typescript + * console.log(isError(new Error())); // true + * console.log(isError('Error')); // false + * console.log(isError({ name: 'Error', message: '' })); // false + * ``` + */ +declare function isError(value: unknown): value is Error; +//#endregion +export { isError }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isError.d.ts b/tools/ui/node_modules/es-toolkit/dist/predicate/isError.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4dd0f32e2e925fce7f18d9463adf280a0c0b118a --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isError.d.ts @@ -0,0 +1,17 @@ +//#region src/predicate/isError.d.ts +/** + * Checks if `value` is an Error object. + * + * @param {unknown} value The value to check. + * @returns {value is Error} Returns `true` if `value` is an Error object, `false` otherwise. + * + * @example + * ```typescript + * console.log(isError(new Error())); // true + * console.log(isError('Error')); // false + * console.log(isError({ name: 'Error', message: '' })); // false + * ``` + */ +declare function isError(value: unknown): value is Error; +//#endregion +export { isError }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isError.js b/tools/ui/node_modules/es-toolkit/dist/predicate/isError.js new file mode 100644 index 0000000000000000000000000000000000000000..b12e293b5bbf2b6a131d26be3f32bd017edc21d9 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isError.js @@ -0,0 +1,19 @@ +//#region src/predicate/isError.ts +/** +* Checks if `value` is an Error object. +* +* @param {unknown} value The value to check. +* @returns {value is Error} Returns `true` if `value` is an Error object, `false` otherwise. +* +* @example +* ```typescript +* console.log(isError(new Error())); // true +* console.log(isError('Error')); // false +* console.log(isError({ name: 'Error', message: '' })); // false +* ``` +*/ +function isError(value) { + return value instanceof Error; +} +//#endregion +exports.isError = isError; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isError.mjs b/tools/ui/node_modules/es-toolkit/dist/predicate/isError.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c80e4a8735cc308bfac0c973cb7a61478c1052cd --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isError.mjs @@ -0,0 +1,19 @@ +//#region src/predicate/isError.ts +/** +* Checks if `value` is an Error object. +* +* @param {unknown} value The value to check. +* @returns {value is Error} Returns `true` if `value` is an Error object, `false` otherwise. +* +* @example +* ```typescript +* console.log(isError(new Error())); // true +* console.log(isError('Error')); // false +* console.log(isError({ name: 'Error', message: '' })); // false +* ``` +*/ +function isError(value) { + return value instanceof Error; +} +//#endregion +export { isError }; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isFile.d.mts b/tools/ui/node_modules/es-toolkit/dist/predicate/isFile.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..16f0ad8f86646f9836b3d80310bba43f504e05ab --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isFile.d.mts @@ -0,0 +1,22 @@ +//#region src/predicate/isFile.d.ts +/** + * Checks if the given value is a File. + * + * This function tests whether the provided value is an instance of `File`. + * It returns `true` if the value is an instance of `File`, and `false` otherwise. + * + * @param {unknown} x - The value to test if it is a File. + * @returns {x is File} True if the value is a File, false otherwise. + * + * @example + * const value1 = new File(["content"], "example.txt"); + * const value2 = {}; + * const value3 = new Blob(["content"], { type: "text/plain" }); + * + * console.log(isFile(value1)); // true + * console.log(isFile(value2)); // false + * console.log(isFile(value3)); // false + */ +declare function isFile(x: unknown): x is File; +//#endregion +export { isFile }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isFile.d.ts b/tools/ui/node_modules/es-toolkit/dist/predicate/isFile.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..16f0ad8f86646f9836b3d80310bba43f504e05ab --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isFile.d.ts @@ -0,0 +1,22 @@ +//#region src/predicate/isFile.d.ts +/** + * Checks if the given value is a File. + * + * This function tests whether the provided value is an instance of `File`. + * It returns `true` if the value is an instance of `File`, and `false` otherwise. + * + * @param {unknown} x - The value to test if it is a File. + * @returns {x is File} True if the value is a File, false otherwise. + * + * @example + * const value1 = new File(["content"], "example.txt"); + * const value2 = {}; + * const value3 = new Blob(["content"], { type: "text/plain" }); + * + * console.log(isFile(value1)); // true + * console.log(isFile(value2)); // false + * console.log(isFile(value3)); // false + */ +declare function isFile(x: unknown): x is File; +//#endregion +export { isFile }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isFile.js b/tools/ui/node_modules/es-toolkit/dist/predicate/isFile.js new file mode 100644 index 0000000000000000000000000000000000000000..003a2bef47f40f7634b03690d4da7123e6acc00e --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isFile.js @@ -0,0 +1,26 @@ +const require_isBlob = require("./isBlob.js"); +//#region src/predicate/isFile.ts +/** +* Checks if the given value is a File. +* +* This function tests whether the provided value is an instance of `File`. +* It returns `true` if the value is an instance of `File`, and `false` otherwise. +* +* @param {unknown} x - The value to test if it is a File. +* @returns {x is File} True if the value is a File, false otherwise. +* +* @example +* const value1 = new File(["content"], "example.txt"); +* const value2 = {}; +* const value3 = new Blob(["content"], { type: "text/plain" }); +* +* console.log(isFile(value1)); // true +* console.log(isFile(value2)); // false +* console.log(isFile(value3)); // false +*/ +function isFile(x) { + if (typeof File === "undefined") return false; + return require_isBlob.isBlob(x) && x instanceof File; +} +//#endregion +exports.isFile = isFile; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isFile.mjs b/tools/ui/node_modules/es-toolkit/dist/predicate/isFile.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e9fc85a35de1fc2c41da9fd51a7bf5da5a223c70 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isFile.mjs @@ -0,0 +1,26 @@ +import { isBlob } from "./isBlob.mjs"; +//#region src/predicate/isFile.ts +/** +* Checks if the given value is a File. +* +* This function tests whether the provided value is an instance of `File`. +* It returns `true` if the value is an instance of `File`, and `false` otherwise. +* +* @param {unknown} x - The value to test if it is a File. +* @returns {x is File} True if the value is a File, false otherwise. +* +* @example +* const value1 = new File(["content"], "example.txt"); +* const value2 = {}; +* const value3 = new Blob(["content"], { type: "text/plain" }); +* +* console.log(isFile(value1)); // true +* console.log(isFile(value2)); // false +* console.log(isFile(value3)); // false +*/ +function isFile(x) { + if (typeof File === "undefined") return false; + return isBlob(x) && x instanceof File; +} +//#endregion +export { isFile }; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isFunction.d.mts b/tools/ui/node_modules/es-toolkit/dist/predicate/isFunction.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..20611e164d45a44e834cfe61e01839c030950aa5 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isFunction.d.mts @@ -0,0 +1,17 @@ +//#region src/predicate/isFunction.d.ts +/** + * Checks if `value` is a function. + * + * @param {any} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * + * @example + * isFunction(Array.prototype.slice); // true + * isFunction(async function () {}); // true + * isFunction(function* () {}); // true + * isFunction(Proxy); // true + * isFunction(Int8Array); // true + */ +declare function isFunction(value: any): value is (...args: any[]) => any; +//#endregion +export { isFunction }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isFunction.d.ts b/tools/ui/node_modules/es-toolkit/dist/predicate/isFunction.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..20611e164d45a44e834cfe61e01839c030950aa5 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isFunction.d.ts @@ -0,0 +1,17 @@ +//#region src/predicate/isFunction.d.ts +/** + * Checks if `value` is a function. + * + * @param {any} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * + * @example + * isFunction(Array.prototype.slice); // true + * isFunction(async function () {}); // true + * isFunction(function* () {}); // true + * isFunction(Proxy); // true + * isFunction(Int8Array); // true + */ +declare function isFunction(value: any): value is (...args: any[]) => any; +//#endregion +export { isFunction }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isFunction.js b/tools/ui/node_modules/es-toolkit/dist/predicate/isFunction.js new file mode 100644 index 0000000000000000000000000000000000000000..95cd348bbe81002dccfb0eca20c9d8812251b220 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isFunction.js @@ -0,0 +1,19 @@ +//#region src/predicate/isFunction.ts +/** +* Checks if `value` is a function. +* +* @param {any} value The value to check. +* @returns {boolean} Returns `true` if `value` is a function, else `false`. +* +* @example +* isFunction(Array.prototype.slice); // true +* isFunction(async function () {}); // true +* isFunction(function* () {}); // true +* isFunction(Proxy); // true +* isFunction(Int8Array); // true +*/ +function isFunction(value) { + return typeof value === "function"; +} +//#endregion +exports.isFunction = isFunction; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isFunction.mjs b/tools/ui/node_modules/es-toolkit/dist/predicate/isFunction.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2e9a020a68bef1e2f282ad4e1bf6a0edefb3fbc7 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isFunction.mjs @@ -0,0 +1,19 @@ +//#region src/predicate/isFunction.ts +/** +* Checks if `value` is a function. +* +* @param {any} value The value to check. +* @returns {boolean} Returns `true` if `value` is a function, else `false`. +* +* @example +* isFunction(Array.prototype.slice); // true +* isFunction(async function () {}); // true +* isFunction(function* () {}); // true +* isFunction(Proxy); // true +* isFunction(Int8Array); // true +*/ +function isFunction(value) { + return typeof value === "function"; +} +//#endregion +export { isFunction }; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isJSON.d.mts b/tools/ui/node_modules/es-toolkit/dist/predicate/isJSON.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..fe30576c9886aeace0356381de56bf3c85b12835 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isJSON.d.mts @@ -0,0 +1,32 @@ +//#region src/predicate/isJSON.d.ts +/** + * Checks if a given value is a valid JSON string. + * + * A valid JSON string is one that can be successfully parsed using `JSON.parse()`. According to JSON + * specifications, valid JSON can represent: + * - Objects (with string keys and valid JSON values) + * - Arrays (containing valid JSON values) + * - Strings + * - Numbers + * - Booleans + * - null + * + * String values like `"null"`, `"true"`, `"false"`, and numeric strings (e.g., `"42"`) are considered + * valid JSON and will return true. + * + * This function serves as a type guard in TypeScript, narrowing the type of the argument to `string`. + * + * @param {unknown} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid JSON string, else `false`. + * + * @example + * isJSON('{"name":"John","age":30}'); // true + * isJSON('[1,2,3]'); // true + * isJSON('true'); // true + * isJSON('invalid json'); // false + * isJSON({ name: 'John' }); // false (not a string) + * isJSON(null); // false (not a string) + */ +declare function isJSON(value: unknown): value is string; +//#endregion +export { isJSON }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isJSON.d.ts b/tools/ui/node_modules/es-toolkit/dist/predicate/isJSON.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fe30576c9886aeace0356381de56bf3c85b12835 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isJSON.d.ts @@ -0,0 +1,32 @@ +//#region src/predicate/isJSON.d.ts +/** + * Checks if a given value is a valid JSON string. + * + * A valid JSON string is one that can be successfully parsed using `JSON.parse()`. According to JSON + * specifications, valid JSON can represent: + * - Objects (with string keys and valid JSON values) + * - Arrays (containing valid JSON values) + * - Strings + * - Numbers + * - Booleans + * - null + * + * String values like `"null"`, `"true"`, `"false"`, and numeric strings (e.g., `"42"`) are considered + * valid JSON and will return true. + * + * This function serves as a type guard in TypeScript, narrowing the type of the argument to `string`. + * + * @param {unknown} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid JSON string, else `false`. + * + * @example + * isJSON('{"name":"John","age":30}'); // true + * isJSON('[1,2,3]'); // true + * isJSON('true'); // true + * isJSON('invalid json'); // false + * isJSON({ name: 'John' }); // false (not a string) + * isJSON(null); // false (not a string) + */ +declare function isJSON(value: unknown): value is string; +//#endregion +export { isJSON }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isJSON.js b/tools/ui/node_modules/es-toolkit/dist/predicate/isJSON.js new file mode 100644 index 0000000000000000000000000000000000000000..cfdd9e31530044f130883d4e61d0cbf9507441af --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isJSON.js @@ -0,0 +1,40 @@ +//#region src/predicate/isJSON.ts +/** +* Checks if a given value is a valid JSON string. +* +* A valid JSON string is one that can be successfully parsed using `JSON.parse()`. According to JSON +* specifications, valid JSON can represent: +* - Objects (with string keys and valid JSON values) +* - Arrays (containing valid JSON values) +* - Strings +* - Numbers +* - Booleans +* - null +* +* String values like `"null"`, `"true"`, `"false"`, and numeric strings (e.g., `"42"`) are considered +* valid JSON and will return true. +* +* This function serves as a type guard in TypeScript, narrowing the type of the argument to `string`. +* +* @param {unknown} value The value to check. +* @returns {boolean} Returns `true` if `value` is a valid JSON string, else `false`. +* +* @example +* isJSON('{"name":"John","age":30}'); // true +* isJSON('[1,2,3]'); // true +* isJSON('true'); // true +* isJSON('invalid json'); // false +* isJSON({ name: 'John' }); // false (not a string) +* isJSON(null); // false (not a string) +*/ +function isJSON(value) { + if (typeof value !== "string") return false; + try { + JSON.parse(value); + return true; + } catch { + return false; + } +} +//#endregion +exports.isJSON = isJSON; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isJSON.mjs b/tools/ui/node_modules/es-toolkit/dist/predicate/isJSON.mjs new file mode 100644 index 0000000000000000000000000000000000000000..15169b780f7f69ad140c3888224ed903f32ea3c1 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isJSON.mjs @@ -0,0 +1,40 @@ +//#region src/predicate/isJSON.ts +/** +* Checks if a given value is a valid JSON string. +* +* A valid JSON string is one that can be successfully parsed using `JSON.parse()`. According to JSON +* specifications, valid JSON can represent: +* - Objects (with string keys and valid JSON values) +* - Arrays (containing valid JSON values) +* - Strings +* - Numbers +* - Booleans +* - null +* +* String values like `"null"`, `"true"`, `"false"`, and numeric strings (e.g., `"42"`) are considered +* valid JSON and will return true. +* +* This function serves as a type guard in TypeScript, narrowing the type of the argument to `string`. +* +* @param {unknown} value The value to check. +* @returns {boolean} Returns `true` if `value` is a valid JSON string, else `false`. +* +* @example +* isJSON('{"name":"John","age":30}'); // true +* isJSON('[1,2,3]'); // true +* isJSON('true'); // true +* isJSON('invalid json'); // false +* isJSON({ name: 'John' }); // false (not a string) +* isJSON(null); // false (not a string) +*/ +function isJSON(value) { + if (typeof value !== "string") return false; + try { + JSON.parse(value); + return true; + } catch { + return false; + } +} +//#endregion +export { isJSON }; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isJSONValue.d.mts b/tools/ui/node_modules/es-toolkit/dist/predicate/isJSONValue.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..97769cdd039d8121b9dd761b8e126d59fe369ef7 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isJSONValue.d.mts @@ -0,0 +1,57 @@ +//#region src/predicate/isJSONValue.d.ts +/** + * Checks if a given value is a valid JSON value. + * + * A valid JSON value can be: + * - null + * - a JSON object (an object with string keys and valid JSON values) + * - a JSON array (an array of valid JSON values) + * - a string + * - a number + * - a boolean + * + * @param {unknown} value - The value to check. + * @returns {boolean} - True if the value is a valid JSON value, otherwise false. + * + * @example + * console.log(isJSONValue(null)); // true + * console.log(isJSONValue({ key: "value" })); // true + * console.log(isJSONValue([1, 2, 3])); // true + * console.log(isJSONValue("Hello")); // true + * console.log(isJSONValue(42)); // true + * console.log(isJSONValue(true)); // true + * console.log(isJSONValue(undefined)); // false + * console.log(isJSONValue(() => {})); // false + */ +declare function isJSONValue(value: unknown): value is Record | any[] | string | number | boolean | null; +/** + * Checks if a given value is a valid JSON array. + * + * A valid JSON array is defined as an array where all items are valid JSON values. + * + * @param {unknown} value - The value to check. + * @returns {value is any[]} - True if the value is a valid JSON array, otherwise false. + * + * @example + * console.log(isJSONArray([1, 2, 3])); // true + * console.log(isJSONArray(["string", null, true])); // true + * console.log(isJSONArray([1, 2, () => {}])); // false + * console.log(isJSONArray("not an array")); // false + */ +declare function isJSONArray(value: unknown): value is any[]; +/** + * Checks if a value is a JSON object. + * + * A valid JSON object is defined as an object with string keys and valid JSON values. + * + * @param {unknown} obj The value to check. + * @returns {obj is Record} True if `obj` is a JSON object, false otherwise. + * + * @example + * isJSONObject({ nested: { boolean: true, array: [1, 2, 3], string: 'test', null: null } }); // true + * isJSONObject({ regexp: /test/ }); // false + * isJSONObject(123); // false + */ +declare function isJSONObject(obj: unknown): obj is Record; +//#endregion +export { isJSONArray, isJSONObject, isJSONValue }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isJSONValue.d.ts b/tools/ui/node_modules/es-toolkit/dist/predicate/isJSONValue.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..97769cdd039d8121b9dd761b8e126d59fe369ef7 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isJSONValue.d.ts @@ -0,0 +1,57 @@ +//#region src/predicate/isJSONValue.d.ts +/** + * Checks if a given value is a valid JSON value. + * + * A valid JSON value can be: + * - null + * - a JSON object (an object with string keys and valid JSON values) + * - a JSON array (an array of valid JSON values) + * - a string + * - a number + * - a boolean + * + * @param {unknown} value - The value to check. + * @returns {boolean} - True if the value is a valid JSON value, otherwise false. + * + * @example + * console.log(isJSONValue(null)); // true + * console.log(isJSONValue({ key: "value" })); // true + * console.log(isJSONValue([1, 2, 3])); // true + * console.log(isJSONValue("Hello")); // true + * console.log(isJSONValue(42)); // true + * console.log(isJSONValue(true)); // true + * console.log(isJSONValue(undefined)); // false + * console.log(isJSONValue(() => {})); // false + */ +declare function isJSONValue(value: unknown): value is Record | any[] | string | number | boolean | null; +/** + * Checks if a given value is a valid JSON array. + * + * A valid JSON array is defined as an array where all items are valid JSON values. + * + * @param {unknown} value - The value to check. + * @returns {value is any[]} - True if the value is a valid JSON array, otherwise false. + * + * @example + * console.log(isJSONArray([1, 2, 3])); // true + * console.log(isJSONArray(["string", null, true])); // true + * console.log(isJSONArray([1, 2, () => {}])); // false + * console.log(isJSONArray("not an array")); // false + */ +declare function isJSONArray(value: unknown): value is any[]; +/** + * Checks if a value is a JSON object. + * + * A valid JSON object is defined as an object with string keys and valid JSON values. + * + * @param {unknown} obj The value to check. + * @returns {obj is Record} True if `obj` is a JSON object, false otherwise. + * + * @example + * isJSONObject({ nested: { boolean: true, array: [1, 2, 3], string: 'test', null: null } }); // true + * isJSONObject({ regexp: /test/ }); // false + * isJSONObject(123); // false + */ +declare function isJSONObject(obj: unknown): obj is Record; +//#endregion +export { isJSONArray, isJSONObject, isJSONValue }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isJSONValue.js b/tools/ui/node_modules/es-toolkit/dist/predicate/isJSONValue.js new file mode 100644 index 0000000000000000000000000000000000000000..3f235532022b0143662b8da7754919451d586bb5 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isJSONValue.js @@ -0,0 +1,85 @@ +const require_isPlainObject = require("./isPlainObject.js"); +//#region src/predicate/isJSONValue.ts +/** +* The functions isJSONValue, isJSONArray, and isJSONObject are grouped in this file +* to prevent any circular dependency issues. +*/ +/** +* Checks if a given value is a valid JSON value. +* +* A valid JSON value can be: +* - null +* - a JSON object (an object with string keys and valid JSON values) +* - a JSON array (an array of valid JSON values) +* - a string +* - a number +* - a boolean +* +* @param {unknown} value - The value to check. +* @returns {boolean} - True if the value is a valid JSON value, otherwise false. +* +* @example +* console.log(isJSONValue(null)); // true +* console.log(isJSONValue({ key: "value" })); // true +* console.log(isJSONValue([1, 2, 3])); // true +* console.log(isJSONValue("Hello")); // true +* console.log(isJSONValue(42)); // true +* console.log(isJSONValue(true)); // true +* console.log(isJSONValue(undefined)); // false +* console.log(isJSONValue(() => {})); // false +*/ +function isJSONValue(value) { + switch (typeof value) { + case "object": return value === null || isJSONArray(value) || isJSONObject(value); + case "string": + case "number": + case "boolean": return true; + default: return false; + } +} +/** +* Checks if a given value is a valid JSON array. +* +* A valid JSON array is defined as an array where all items are valid JSON values. +* +* @param {unknown} value - The value to check. +* @returns {value is any[]} - True if the value is a valid JSON array, otherwise false. +* +* @example +* console.log(isJSONArray([1, 2, 3])); // true +* console.log(isJSONArray(["string", null, true])); // true +* console.log(isJSONArray([1, 2, () => {}])); // false +* console.log(isJSONArray("not an array")); // false +*/ +function isJSONArray(value) { + if (!Array.isArray(value)) return false; + return value.every((item) => isJSONValue(item)); +} +/** +* Checks if a value is a JSON object. +* +* A valid JSON object is defined as an object with string keys and valid JSON values. +* +* @param {unknown} obj The value to check. +* @returns {obj is Record} True if `obj` is a JSON object, false otherwise. +* +* @example +* isJSONObject({ nested: { boolean: true, array: [1, 2, 3], string: 'test', null: null } }); // true +* isJSONObject({ regexp: /test/ }); // false +* isJSONObject(123); // false +*/ +function isJSONObject(obj) { + if (!require_isPlainObject.isPlainObject(obj)) return false; + const keys = Reflect.ownKeys(obj); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const value = obj[key]; + if (typeof key !== "string") return false; + if (!isJSONValue(value)) return false; + } + return true; +} +//#endregion +exports.isJSONArray = isJSONArray; +exports.isJSONObject = isJSONObject; +exports.isJSONValue = isJSONValue; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isJSONValue.mjs b/tools/ui/node_modules/es-toolkit/dist/predicate/isJSONValue.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e5a23947d7892964b2ce05ce02a8cf752cf5fd66 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isJSONValue.mjs @@ -0,0 +1,83 @@ +import { isPlainObject } from "./isPlainObject.mjs"; +//#region src/predicate/isJSONValue.ts +/** +* The functions isJSONValue, isJSONArray, and isJSONObject are grouped in this file +* to prevent any circular dependency issues. +*/ +/** +* Checks if a given value is a valid JSON value. +* +* A valid JSON value can be: +* - null +* - a JSON object (an object with string keys and valid JSON values) +* - a JSON array (an array of valid JSON values) +* - a string +* - a number +* - a boolean +* +* @param {unknown} value - The value to check. +* @returns {boolean} - True if the value is a valid JSON value, otherwise false. +* +* @example +* console.log(isJSONValue(null)); // true +* console.log(isJSONValue({ key: "value" })); // true +* console.log(isJSONValue([1, 2, 3])); // true +* console.log(isJSONValue("Hello")); // true +* console.log(isJSONValue(42)); // true +* console.log(isJSONValue(true)); // true +* console.log(isJSONValue(undefined)); // false +* console.log(isJSONValue(() => {})); // false +*/ +function isJSONValue(value) { + switch (typeof value) { + case "object": return value === null || isJSONArray(value) || isJSONObject(value); + case "string": + case "number": + case "boolean": return true; + default: return false; + } +} +/** +* Checks if a given value is a valid JSON array. +* +* A valid JSON array is defined as an array where all items are valid JSON values. +* +* @param {unknown} value - The value to check. +* @returns {value is any[]} - True if the value is a valid JSON array, otherwise false. +* +* @example +* console.log(isJSONArray([1, 2, 3])); // true +* console.log(isJSONArray(["string", null, true])); // true +* console.log(isJSONArray([1, 2, () => {}])); // false +* console.log(isJSONArray("not an array")); // false +*/ +function isJSONArray(value) { + if (!Array.isArray(value)) return false; + return value.every((item) => isJSONValue(item)); +} +/** +* Checks if a value is a JSON object. +* +* A valid JSON object is defined as an object with string keys and valid JSON values. +* +* @param {unknown} obj The value to check. +* @returns {obj is Record} True if `obj` is a JSON object, false otherwise. +* +* @example +* isJSONObject({ nested: { boolean: true, array: [1, 2, 3], string: 'test', null: null } }); // true +* isJSONObject({ regexp: /test/ }); // false +* isJSONObject(123); // false +*/ +function isJSONObject(obj) { + if (!isPlainObject(obj)) return false; + const keys = Reflect.ownKeys(obj); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const value = obj[key]; + if (typeof key !== "string") return false; + if (!isJSONValue(value)) return false; + } + return true; +} +//#endregion +export { isJSONArray, isJSONObject, isJSONValue }; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isLength.d.mts b/tools/ui/node_modules/es-toolkit/dist/predicate/isLength.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..bdf7e3112ddf49567146a404ba8f1d3422ebecb9 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isLength.d.mts @@ -0,0 +1,25 @@ +//#region src/predicate/isLength.d.ts +/** + * Checks if a given value is a valid length. + * + * A valid length is of type `number`, is a non-negative integer, and is less than or equal to + * JavaScript's maximum safe integer (`Number.MAX_SAFE_INTEGER`). + * It returns `true` if the value is a valid length, and `false` otherwise. + * + * This function can also serve as a type predicate in TypeScript, narrowing the type of the + * argument to a valid length (`number`). + * + * @param {any} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * + * @example + * isLength(0); // true + * isLength(42); // true + * isLength(-1); // false + * isLength(1.5); // false + * isLength(Number.MAX_SAFE_INTEGER); // true + * isLength(Number.MAX_SAFE_INTEGER + 1); // false + */ +declare function isLength(value?: any): boolean; +//#endregion +export { isLength }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isLength.d.ts b/tools/ui/node_modules/es-toolkit/dist/predicate/isLength.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bdf7e3112ddf49567146a404ba8f1d3422ebecb9 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isLength.d.ts @@ -0,0 +1,25 @@ +//#region src/predicate/isLength.d.ts +/** + * Checks if a given value is a valid length. + * + * A valid length is of type `number`, is a non-negative integer, and is less than or equal to + * JavaScript's maximum safe integer (`Number.MAX_SAFE_INTEGER`). + * It returns `true` if the value is a valid length, and `false` otherwise. + * + * This function can also serve as a type predicate in TypeScript, narrowing the type of the + * argument to a valid length (`number`). + * + * @param {any} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * + * @example + * isLength(0); // true + * isLength(42); // true + * isLength(-1); // false + * isLength(1.5); // false + * isLength(Number.MAX_SAFE_INTEGER); // true + * isLength(Number.MAX_SAFE_INTEGER + 1); // false + */ +declare function isLength(value?: any): boolean; +//#endregion +export { isLength }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isLength.js b/tools/ui/node_modules/es-toolkit/dist/predicate/isLength.js new file mode 100644 index 0000000000000000000000000000000000000000..e6b4d102a8016e0e048d5183024a2410684314b5 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isLength.js @@ -0,0 +1,27 @@ +//#region src/predicate/isLength.ts +/** +* Checks if a given value is a valid length. +* +* A valid length is of type `number`, is a non-negative integer, and is less than or equal to +* JavaScript's maximum safe integer (`Number.MAX_SAFE_INTEGER`). +* It returns `true` if the value is a valid length, and `false` otherwise. +* +* This function can also serve as a type predicate in TypeScript, narrowing the type of the +* argument to a valid length (`number`). +* +* @param {any} value The value to check. +* @returns {boolean} Returns `true` if `value` is a valid length, else `false`. +* +* @example +* isLength(0); // true +* isLength(42); // true +* isLength(-1); // false +* isLength(1.5); // false +* isLength(Number.MAX_SAFE_INTEGER); // true +* isLength(Number.MAX_SAFE_INTEGER + 1); // false +*/ +function isLength(value) { + return Number.isSafeInteger(value) && value >= 0; +} +//#endregion +exports.isLength = isLength; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isLength.mjs b/tools/ui/node_modules/es-toolkit/dist/predicate/isLength.mjs new file mode 100644 index 0000000000000000000000000000000000000000..49d69ad704946a8840e92e4c464e1a3bb7da99fa --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isLength.mjs @@ -0,0 +1,27 @@ +//#region src/predicate/isLength.ts +/** +* Checks if a given value is a valid length. +* +* A valid length is of type `number`, is a non-negative integer, and is less than or equal to +* JavaScript's maximum safe integer (`Number.MAX_SAFE_INTEGER`). +* It returns `true` if the value is a valid length, and `false` otherwise. +* +* This function can also serve as a type predicate in TypeScript, narrowing the type of the +* argument to a valid length (`number`). +* +* @param {any} value The value to check. +* @returns {boolean} Returns `true` if `value` is a valid length, else `false`. +* +* @example +* isLength(0); // true +* isLength(42); // true +* isLength(-1); // false +* isLength(1.5); // false +* isLength(Number.MAX_SAFE_INTEGER); // true +* isLength(Number.MAX_SAFE_INTEGER + 1); // false +*/ +function isLength(value) { + return Number.isSafeInteger(value) && value >= 0; +} +//#endregion +export { isLength }; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isMap.d.mts b/tools/ui/node_modules/es-toolkit/dist/predicate/isMap.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..572e4761fc2c7d614b98e2093d11d138aedca060 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isMap.d.mts @@ -0,0 +1,21 @@ +//#region src/predicate/isMap.d.ts +/** + * Checks if a given value is `Map`. + * + * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `Map`. + * + * @param {unknown} value The value to check if it is a `Map`. + * @returns {value is Map} Returns `true` if `value` is a `Map`, else `false`. + * + * @example + * const value1 = new Map(); + * const value2 = new Set(); + * const value3 = new WeakMap(); + * + * console.log(isMap(value1)); // true + * console.log(isMap(value2)); // false + * console.log(isMap(value3)); // false + */ +declare function isMap(value: unknown): value is Map; +//#endregion +export { isMap }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isMap.d.ts b/tools/ui/node_modules/es-toolkit/dist/predicate/isMap.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..572e4761fc2c7d614b98e2093d11d138aedca060 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isMap.d.ts @@ -0,0 +1,21 @@ +//#region src/predicate/isMap.d.ts +/** + * Checks if a given value is `Map`. + * + * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `Map`. + * + * @param {unknown} value The value to check if it is a `Map`. + * @returns {value is Map} Returns `true` if `value` is a `Map`, else `false`. + * + * @example + * const value1 = new Map(); + * const value2 = new Set(); + * const value3 = new WeakMap(); + * + * console.log(isMap(value1)); // true + * console.log(isMap(value2)); // false + * console.log(isMap(value3)); // false + */ +declare function isMap(value: unknown): value is Map; +//#endregion +export { isMap }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isMap.js b/tools/ui/node_modules/es-toolkit/dist/predicate/isMap.js new file mode 100644 index 0000000000000000000000000000000000000000..5ef6412c5f61e62a99e6d64417c6a30b66b636d9 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isMap.js @@ -0,0 +1,23 @@ +//#region src/predicate/isMap.ts +/** +* Checks if a given value is `Map`. +* +* This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `Map`. +* +* @param {unknown} value The value to check if it is a `Map`. +* @returns {value is Map} Returns `true` if `value` is a `Map`, else `false`. +* +* @example +* const value1 = new Map(); +* const value2 = new Set(); +* const value3 = new WeakMap(); +* +* console.log(isMap(value1)); // true +* console.log(isMap(value2)); // false +* console.log(isMap(value3)); // false +*/ +function isMap(value) { + return value instanceof Map; +} +//#endregion +exports.isMap = isMap; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isMap.mjs b/tools/ui/node_modules/es-toolkit/dist/predicate/isMap.mjs new file mode 100644 index 0000000000000000000000000000000000000000..408db04b6e02c1d90dd3a3c8b57fa9f16f2f092c --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isMap.mjs @@ -0,0 +1,23 @@ +//#region src/predicate/isMap.ts +/** +* Checks if a given value is `Map`. +* +* This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `Map`. +* +* @param {unknown} value The value to check if it is a `Map`. +* @returns {value is Map} Returns `true` if `value` is a `Map`, else `false`. +* +* @example +* const value1 = new Map(); +* const value2 = new Set(); +* const value3 = new WeakMap(); +* +* console.log(isMap(value1)); // true +* console.log(isMap(value2)); // false +* console.log(isMap(value3)); // false +*/ +function isMap(value) { + return value instanceof Map; +} +//#endregion +export { isMap }; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isNil.d.mts b/tools/ui/node_modules/es-toolkit/dist/predicate/isNil.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..67383b9d7fa3d838b8157543cc3938643f1dfda8 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isNil.d.mts @@ -0,0 +1,23 @@ +//#region src/predicate/isNil.d.ts +/** + * Checks if a given value is null or undefined. + * + * This function tests whether the provided value is either `null` or `undefined`. + * It returns `true` if the value is `null` or `undefined`, and `false` otherwise. + * + * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `null` or `undefined`. + * + * @param {unknown} x - The value to test for null or undefined. + * @returns {boolean} `true` if the value is null or undefined, `false` otherwise. + * + * @example + * const value1 = null; + * const value2 = undefined; + * const value3 = 42; + * const result1 = isNil(value1); // true + * const result2 = isNil(value2); // true + * const result3 = isNil(value3); // false + */ +declare function isNil(x: unknown): x is null | undefined; +//#endregion +export { isNil }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isNil.d.ts b/tools/ui/node_modules/es-toolkit/dist/predicate/isNil.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..67383b9d7fa3d838b8157543cc3938643f1dfda8 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isNil.d.ts @@ -0,0 +1,23 @@ +//#region src/predicate/isNil.d.ts +/** + * Checks if a given value is null or undefined. + * + * This function tests whether the provided value is either `null` or `undefined`. + * It returns `true` if the value is `null` or `undefined`, and `false` otherwise. + * + * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `null` or `undefined`. + * + * @param {unknown} x - The value to test for null or undefined. + * @returns {boolean} `true` if the value is null or undefined, `false` otherwise. + * + * @example + * const value1 = null; + * const value2 = undefined; + * const value3 = 42; + * const result1 = isNil(value1); // true + * const result2 = isNil(value2); // true + * const result3 = isNil(value3); // false + */ +declare function isNil(x: unknown): x is null | undefined; +//#endregion +export { isNil }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isNil.js b/tools/ui/node_modules/es-toolkit/dist/predicate/isNil.js new file mode 100644 index 0000000000000000000000000000000000000000..bf23838d9075b24e677a0a697c4e8bdd6d1077e5 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isNil.js @@ -0,0 +1,25 @@ +//#region src/predicate/isNil.ts +/** +* Checks if a given value is null or undefined. +* +* This function tests whether the provided value is either `null` or `undefined`. +* It returns `true` if the value is `null` or `undefined`, and `false` otherwise. +* +* This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `null` or `undefined`. +* +* @param {unknown} x - The value to test for null or undefined. +* @returns {boolean} `true` if the value is null or undefined, `false` otherwise. +* +* @example +* const value1 = null; +* const value2 = undefined; +* const value3 = 42; +* const result1 = isNil(value1); // true +* const result2 = isNil(value2); // true +* const result3 = isNil(value3); // false +*/ +function isNil(x) { + return x == null; +} +//#endregion +exports.isNil = isNil; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isNil.mjs b/tools/ui/node_modules/es-toolkit/dist/predicate/isNil.mjs new file mode 100644 index 0000000000000000000000000000000000000000..055edb74ebf52d8c7ae5e0653eaa940406527a30 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isNil.mjs @@ -0,0 +1,25 @@ +//#region src/predicate/isNil.ts +/** +* Checks if a given value is null or undefined. +* +* This function tests whether the provided value is either `null` or `undefined`. +* It returns `true` if the value is `null` or `undefined`, and `false` otherwise. +* +* This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `null` or `undefined`. +* +* @param {unknown} x - The value to test for null or undefined. +* @returns {boolean} `true` if the value is null or undefined, `false` otherwise. +* +* @example +* const value1 = null; +* const value2 = undefined; +* const value3 = 42; +* const result1 = isNil(value1); // true +* const result2 = isNil(value2); // true +* const result3 = isNil(value3); // false +*/ +function isNil(x) { + return x == null; +} +//#endregion +export { isNil }; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isNode.d.mts b/tools/ui/node_modules/es-toolkit/dist/predicate/isNode.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..ecd3a8b6aad7c536b9f19dcd7e6c09332f166255 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isNode.d.mts @@ -0,0 +1,18 @@ +//#region src/predicate/isNode.d.ts +/** + * Checks if the current environment is Node.js. + * + * This function checks for the existence of the `process.versions.node` property, + * which only exists in Node.js environments. + * + * @returns {boolean} `true` if the current environment is Node.js, otherwise `false`. + * + * @example + * if (isNode()) { + * console.log('This is running in Node.js'); + * const fs = import('node:fs'); + * } + */ +declare function isNode(): boolean; +//#endregion +export { isNode }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isNode.d.ts b/tools/ui/node_modules/es-toolkit/dist/predicate/isNode.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ecd3a8b6aad7c536b9f19dcd7e6c09332f166255 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isNode.d.ts @@ -0,0 +1,18 @@ +//#region src/predicate/isNode.d.ts +/** + * Checks if the current environment is Node.js. + * + * This function checks for the existence of the `process.versions.node` property, + * which only exists in Node.js environments. + * + * @returns {boolean} `true` if the current environment is Node.js, otherwise `false`. + * + * @example + * if (isNode()) { + * console.log('This is running in Node.js'); + * const fs = import('node:fs'); + * } + */ +declare function isNode(): boolean; +//#endregion +export { isNode }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isNode.js b/tools/ui/node_modules/es-toolkit/dist/predicate/isNode.js new file mode 100644 index 0000000000000000000000000000000000000000..97ca20de6f3b5027911d8eb4511e256932940306 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isNode.js @@ -0,0 +1,20 @@ +//#region src/predicate/isNode.ts +/** +* Checks if the current environment is Node.js. +* +* This function checks for the existence of the `process.versions.node` property, +* which only exists in Node.js environments. +* +* @returns {boolean} `true` if the current environment is Node.js, otherwise `false`. +* +* @example +* if (isNode()) { +* console.log('This is running in Node.js'); +* const fs = import('node:fs'); +* } +*/ +function isNode() { + return typeof process !== "undefined" && process?.versions?.node != null; +} +//#endregion +exports.isNode = isNode; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isNode.mjs b/tools/ui/node_modules/es-toolkit/dist/predicate/isNode.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3b8ebe0d24003aaa7219872e2d88378e35c35ddb --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isNode.mjs @@ -0,0 +1,20 @@ +//#region src/predicate/isNode.ts +/** +* Checks if the current environment is Node.js. +* +* This function checks for the existence of the `process.versions.node` property, +* which only exists in Node.js environments. +* +* @returns {boolean} `true` if the current environment is Node.js, otherwise `false`. +* +* @example +* if (isNode()) { +* console.log('This is running in Node.js'); +* const fs = import('node:fs'); +* } +*/ +function isNode() { + return typeof process !== "undefined" && process?.versions?.node != null; +} +//#endregion +export { isNode }; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isNotNil.d.mts b/tools/ui/node_modules/es-toolkit/dist/predicate/isNotNil.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..33084636dde0e3773b42b82d5ca59b5623e30507 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isNotNil.d.mts @@ -0,0 +1,20 @@ +//#region src/predicate/isNotNil.d.ts +/** + * Checks if the given value is not null nor undefined. + * + * The main use of this function is to be used with TypeScript as a type predicate. + * + * @template T - The type of value. + * @param {T | null | undefined} x - The value to test if it is not null nor undefined. + * @returns {x is T} True if the value is not null nor undefined, false otherwise. + * + * @example + * // Here the type of `arr` is (number | undefined)[] + * const arr = [1, undefined, 3]; + * // Here the type of `result` is number[] + * const result = arr.filter(isNotNil); + * // result will be [1, 3] + */ +declare function isNotNil(x: T | null | undefined): x is T; +//#endregion +export { isNotNil }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isNotNil.d.ts b/tools/ui/node_modules/es-toolkit/dist/predicate/isNotNil.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..33084636dde0e3773b42b82d5ca59b5623e30507 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isNotNil.d.ts @@ -0,0 +1,20 @@ +//#region src/predicate/isNotNil.d.ts +/** + * Checks if the given value is not null nor undefined. + * + * The main use of this function is to be used with TypeScript as a type predicate. + * + * @template T - The type of value. + * @param {T | null | undefined} x - The value to test if it is not null nor undefined. + * @returns {x is T} True if the value is not null nor undefined, false otherwise. + * + * @example + * // Here the type of `arr` is (number | undefined)[] + * const arr = [1, undefined, 3]; + * // Here the type of `result` is number[] + * const result = arr.filter(isNotNil); + * // result will be [1, 3] + */ +declare function isNotNil(x: T | null | undefined): x is T; +//#endregion +export { isNotNil }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isNotNil.js b/tools/ui/node_modules/es-toolkit/dist/predicate/isNotNil.js new file mode 100644 index 0000000000000000000000000000000000000000..1a7c236a266e32bb497d135e6a855714342e36f4 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isNotNil.js @@ -0,0 +1,22 @@ +//#region src/predicate/isNotNil.ts +/** +* Checks if the given value is not null nor undefined. +* +* The main use of this function is to be used with TypeScript as a type predicate. +* +* @template T - The type of value. +* @param {T | null | undefined} x - The value to test if it is not null nor undefined. +* @returns {x is T} True if the value is not null nor undefined, false otherwise. +* +* @example +* // Here the type of `arr` is (number | undefined)[] +* const arr = [1, undefined, 3]; +* // Here the type of `result` is number[] +* const result = arr.filter(isNotNil); +* // result will be [1, 3] +*/ +function isNotNil(x) { + return x != null; +} +//#endregion +exports.isNotNil = isNotNil; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isNotNil.mjs b/tools/ui/node_modules/es-toolkit/dist/predicate/isNotNil.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b616ddec7bce953a924def7f3987cb0d6705c928 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isNotNil.mjs @@ -0,0 +1,22 @@ +//#region src/predicate/isNotNil.ts +/** +* Checks if the given value is not null nor undefined. +* +* The main use of this function is to be used with TypeScript as a type predicate. +* +* @template T - The type of value. +* @param {T | null | undefined} x - The value to test if it is not null nor undefined. +* @returns {x is T} True if the value is not null nor undefined, false otherwise. +* +* @example +* // Here the type of `arr` is (number | undefined)[] +* const arr = [1, undefined, 3]; +* // Here the type of `result` is number[] +* const result = arr.filter(isNotNil); +* // result will be [1, 3] +*/ +function isNotNil(x) { + return x != null; +} +//#endregion +export { isNotNil }; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isNull.d.mts b/tools/ui/node_modules/es-toolkit/dist/predicate/isNull.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..fe585993adb92a2af1c2126847bcd10cd4cdab8b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isNull.d.mts @@ -0,0 +1,24 @@ +//#region src/predicate/isNull.d.ts +/** + * Checks if the given value is null. + * + * This function tests whether the provided value is strictly equal to `null`. + * It returns `true` if the value is `null`, and `false` otherwise. + * + * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `null`. + * + * @param {unknown} x - The value to test if it is null. + * @returns {x is null} True if the value is null, false otherwise. + * + * @example + * const value1 = null; + * const value2 = undefined; + * const value3 = 42; + * + * console.log(isNull(value1)); // true + * console.log(isNull(value2)); // false + * console.log(isNull(value3)); // false + */ +declare function isNull(x: unknown): x is null; +//#endregion +export { isNull }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isNull.d.ts b/tools/ui/node_modules/es-toolkit/dist/predicate/isNull.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fe585993adb92a2af1c2126847bcd10cd4cdab8b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isNull.d.ts @@ -0,0 +1,24 @@ +//#region src/predicate/isNull.d.ts +/** + * Checks if the given value is null. + * + * This function tests whether the provided value is strictly equal to `null`. + * It returns `true` if the value is `null`, and `false` otherwise. + * + * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `null`. + * + * @param {unknown} x - The value to test if it is null. + * @returns {x is null} True if the value is null, false otherwise. + * + * @example + * const value1 = null; + * const value2 = undefined; + * const value3 = 42; + * + * console.log(isNull(value1)); // true + * console.log(isNull(value2)); // false + * console.log(isNull(value3)); // false + */ +declare function isNull(x: unknown): x is null; +//#endregion +export { isNull }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isNull.js b/tools/ui/node_modules/es-toolkit/dist/predicate/isNull.js new file mode 100644 index 0000000000000000000000000000000000000000..95afc0e045cabbfe7c160593e5fc28aaa64b7dab --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isNull.js @@ -0,0 +1,26 @@ +//#region src/predicate/isNull.ts +/** +* Checks if the given value is null. +* +* This function tests whether the provided value is strictly equal to `null`. +* It returns `true` if the value is `null`, and `false` otherwise. +* +* This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `null`. +* +* @param {unknown} x - The value to test if it is null. +* @returns {x is null} True if the value is null, false otherwise. +* +* @example +* const value1 = null; +* const value2 = undefined; +* const value3 = 42; +* +* console.log(isNull(value1)); // true +* console.log(isNull(value2)); // false +* console.log(isNull(value3)); // false +*/ +function isNull(x) { + return x === null; +} +//#endregion +exports.isNull = isNull; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isNull.mjs b/tools/ui/node_modules/es-toolkit/dist/predicate/isNull.mjs new file mode 100644 index 0000000000000000000000000000000000000000..621e27d29b39092ff4dcb95ee0dfd81b2c707acf --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isNull.mjs @@ -0,0 +1,26 @@ +//#region src/predicate/isNull.ts +/** +* Checks if the given value is null. +* +* This function tests whether the provided value is strictly equal to `null`. +* It returns `true` if the value is `null`, and `false` otherwise. +* +* This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `null`. +* +* @param {unknown} x - The value to test if it is null. +* @returns {x is null} True if the value is null, false otherwise. +* +* @example +* const value1 = null; +* const value2 = undefined; +* const value3 = 42; +* +* console.log(isNull(value1)); // true +* console.log(isNull(value2)); // false +* console.log(isNull(value3)); // false +*/ +function isNull(x) { + return x === null; +} +//#endregion +export { isNull }; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isNumber.d.mts b/tools/ui/node_modules/es-toolkit/dist/predicate/isNumber.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..c22e47f87c41188c3e96a3e7d0ad23a3ca436ab4 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isNumber.d.mts @@ -0,0 +1,26 @@ +//#region src/predicate/isNumber.d.ts +/** + * Checks if the given value is a number. + * + * This function tests whether the provided value is strictly a `number`. + * It returns `true` if the value is a `number`, and `false` otherwise. + * + * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `number`. + * + * @param {unknown} x - The value to test if it is a number. + * @returns {x is number} True if the value is a number, false otherwise. + * + * @example + * + * const value1 = 123; + * const value2 = 'abc'; + * const value3 = true; + * + * console.log(isNumber(value1)); // true + * console.log(isNumber(value2)); // false + * console.log(isNumber(value3)); // false + * + */ +declare function isNumber(x: unknown): x is number; +//#endregion +export { isNumber }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isNumber.d.ts b/tools/ui/node_modules/es-toolkit/dist/predicate/isNumber.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c22e47f87c41188c3e96a3e7d0ad23a3ca436ab4 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isNumber.d.ts @@ -0,0 +1,26 @@ +//#region src/predicate/isNumber.d.ts +/** + * Checks if the given value is a number. + * + * This function tests whether the provided value is strictly a `number`. + * It returns `true` if the value is a `number`, and `false` otherwise. + * + * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `number`. + * + * @param {unknown} x - The value to test if it is a number. + * @returns {x is number} True if the value is a number, false otherwise. + * + * @example + * + * const value1 = 123; + * const value2 = 'abc'; + * const value3 = true; + * + * console.log(isNumber(value1)); // true + * console.log(isNumber(value2)); // false + * console.log(isNumber(value3)); // false + * + */ +declare function isNumber(x: unknown): x is number; +//#endregion +export { isNumber }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isNumber.js b/tools/ui/node_modules/es-toolkit/dist/predicate/isNumber.js new file mode 100644 index 0000000000000000000000000000000000000000..3d6d49c5ef14cb92e7ff1f8857921f0627b8377a --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isNumber.js @@ -0,0 +1,28 @@ +//#region src/predicate/isNumber.ts +/** +* Checks if the given value is a number. +* +* This function tests whether the provided value is strictly a `number`. +* It returns `true` if the value is a `number`, and `false` otherwise. +* +* This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `number`. +* +* @param {unknown} x - The value to test if it is a number. +* @returns {x is number} True if the value is a number, false otherwise. +* +* @example +* +* const value1 = 123; +* const value2 = 'abc'; +* const value3 = true; +* +* console.log(isNumber(value1)); // true +* console.log(isNumber(value2)); // false +* console.log(isNumber(value3)); // false +* +*/ +function isNumber(x) { + return typeof x === "number" || x instanceof Number; +} +//#endregion +exports.isNumber = isNumber; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isNumber.mjs b/tools/ui/node_modules/es-toolkit/dist/predicate/isNumber.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5d53cb3badac34c4c8b3f3d4a43109b7447ac84f --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isNumber.mjs @@ -0,0 +1,28 @@ +//#region src/predicate/isNumber.ts +/** +* Checks if the given value is a number. +* +* This function tests whether the provided value is strictly a `number`. +* It returns `true` if the value is a `number`, and `false` otherwise. +* +* This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `number`. +* +* @param {unknown} x - The value to test if it is a number. +* @returns {x is number} True if the value is a number, false otherwise. +* +* @example +* +* const value1 = 123; +* const value2 = 'abc'; +* const value3 = true; +* +* console.log(isNumber(value1)); // true +* console.log(isNumber(value2)); // false +* console.log(isNumber(value3)); // false +* +*/ +function isNumber(x) { + return typeof x === "number" || x instanceof Number; +} +//#endregion +export { isNumber }; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isPlainObject.d.mts b/tools/ui/node_modules/es-toolkit/dist/predicate/isPlainObject.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..88ea40e036cdaf3337a064e8b6acfe7ad379c592 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isPlainObject.d.mts @@ -0,0 +1,46 @@ +//#region src/predicate/isPlainObject.d.ts +/** + * Checks if a given value is a plain object. + * + * @param {object} value - The value to check. + * @returns {value is Record} - True if the value is a plain object, otherwise false. + * + * @example + * ```typescript + * // ✅👇 True + * + * isPlainObject({ }); // ✅ + * isPlainObject({ key: 'value' }); // ✅ + * isPlainObject({ key: new Date() }); // ✅ + * isPlainObject(new Object()); // ✅ + * isPlainObject(Object.create(null)); // ✅ + * isPlainObject({ nested: { key: true} }); // ✅ + * isPlainObject(new Proxy({}, {})); // ✅ + * isPlainObject({ [Symbol('tag')]: 'A' }); // ✅ + * + * // ✅👇 (cross-realms, node context, workers, ...) + * const runInNewContext = await import('node:vm').then( + * (mod) => mod.runInNewContext + * ); + * isPlainObject(runInNewContext('({})')); // ✅ + * + * // ❌👇 False + * + * class Test { }; + * isPlainObject(new Test()) // ❌ + * isPlainObject(10); // ❌ + * isPlainObject(null); // ❌ + * isPlainObject('hello'); // ❌ + * isPlainObject([]); // ❌ + * isPlainObject(new Date()); // ❌ + * isPlainObject(new Uint8Array([1])); // ❌ + * isPlainObject(Buffer.from('ABC')); // ❌ + * isPlainObject(Promise.resolve({})); // ❌ + * isPlainObject(Object.create({})); // ❌ + * isPlainObject(new (class Cls {})); // ❌ + * isPlainObject(globalThis); // ❌, + * ``` + */ +declare function isPlainObject(value: unknown): value is Record; +//#endregion +export { isPlainObject }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isPlainObject.d.ts b/tools/ui/node_modules/es-toolkit/dist/predicate/isPlainObject.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..88ea40e036cdaf3337a064e8b6acfe7ad379c592 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isPlainObject.d.ts @@ -0,0 +1,46 @@ +//#region src/predicate/isPlainObject.d.ts +/** + * Checks if a given value is a plain object. + * + * @param {object} value - The value to check. + * @returns {value is Record} - True if the value is a plain object, otherwise false. + * + * @example + * ```typescript + * // ✅👇 True + * + * isPlainObject({ }); // ✅ + * isPlainObject({ key: 'value' }); // ✅ + * isPlainObject({ key: new Date() }); // ✅ + * isPlainObject(new Object()); // ✅ + * isPlainObject(Object.create(null)); // ✅ + * isPlainObject({ nested: { key: true} }); // ✅ + * isPlainObject(new Proxy({}, {})); // ✅ + * isPlainObject({ [Symbol('tag')]: 'A' }); // ✅ + * + * // ✅👇 (cross-realms, node context, workers, ...) + * const runInNewContext = await import('node:vm').then( + * (mod) => mod.runInNewContext + * ); + * isPlainObject(runInNewContext('({})')); // ✅ + * + * // ❌👇 False + * + * class Test { }; + * isPlainObject(new Test()) // ❌ + * isPlainObject(10); // ❌ + * isPlainObject(null); // ❌ + * isPlainObject('hello'); // ❌ + * isPlainObject([]); // ❌ + * isPlainObject(new Date()); // ❌ + * isPlainObject(new Uint8Array([1])); // ❌ + * isPlainObject(Buffer.from('ABC')); // ❌ + * isPlainObject(Promise.resolve({})); // ❌ + * isPlainObject(Object.create({})); // ❌ + * isPlainObject(new (class Cls {})); // ❌ + * isPlainObject(globalThis); // ❌, + * ``` + */ +declare function isPlainObject(value: unknown): value is Record; +//#endregion +export { isPlainObject }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isPlainObject.js b/tools/ui/node_modules/es-toolkit/dist/predicate/isPlainObject.js new file mode 100644 index 0000000000000000000000000000000000000000..083cb7b366b9a0b4a699f6b79e7162797a159fe7 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isPlainObject.js @@ -0,0 +1,51 @@ +//#region src/predicate/isPlainObject.ts +/** +* Checks if a given value is a plain object. +* +* @param {object} value - The value to check. +* @returns {value is Record} - True if the value is a plain object, otherwise false. +* +* @example +* ```typescript +* // ✅👇 True +* +* isPlainObject({ }); // ✅ +* isPlainObject({ key: 'value' }); // ✅ +* isPlainObject({ key: new Date() }); // ✅ +* isPlainObject(new Object()); // ✅ +* isPlainObject(Object.create(null)); // ✅ +* isPlainObject({ nested: { key: true} }); // ✅ +* isPlainObject(new Proxy({}, {})); // ✅ +* isPlainObject({ [Symbol('tag')]: 'A' }); // ✅ +* +* // ✅👇 (cross-realms, node context, workers, ...) +* const runInNewContext = await import('node:vm').then( +* (mod) => mod.runInNewContext +* ); +* isPlainObject(runInNewContext('({})')); // ✅ +* +* // ❌👇 False +* +* class Test { }; +* isPlainObject(new Test()) // ❌ +* isPlainObject(10); // ❌ +* isPlainObject(null); // ❌ +* isPlainObject('hello'); // ❌ +* isPlainObject([]); // ❌ +* isPlainObject(new Date()); // ❌ +* isPlainObject(new Uint8Array([1])); // ❌ +* isPlainObject(Buffer.from('ABC')); // ❌ +* isPlainObject(Promise.resolve({})); // ❌ +* isPlainObject(Object.create({})); // ❌ +* isPlainObject(new (class Cls {})); // ❌ +* isPlainObject(globalThis); // ❌, +* ``` +*/ +function isPlainObject(value) { + if (!value || typeof value !== "object") return false; + const proto = Object.getPrototypeOf(value); + if (!(proto === null || proto === Object.prototype || Object.getPrototypeOf(proto) === null)) return false; + return Object.prototype.toString.call(value) === "[object Object]"; +} +//#endregion +exports.isPlainObject = isPlainObject; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isPlainObject.mjs b/tools/ui/node_modules/es-toolkit/dist/predicate/isPlainObject.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e24dae916b004688ee8c4c294e11519499174852 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isPlainObject.mjs @@ -0,0 +1,51 @@ +//#region src/predicate/isPlainObject.ts +/** +* Checks if a given value is a plain object. +* +* @param {object} value - The value to check. +* @returns {value is Record} - True if the value is a plain object, otherwise false. +* +* @example +* ```typescript +* // ✅👇 True +* +* isPlainObject({ }); // ✅ +* isPlainObject({ key: 'value' }); // ✅ +* isPlainObject({ key: new Date() }); // ✅ +* isPlainObject(new Object()); // ✅ +* isPlainObject(Object.create(null)); // ✅ +* isPlainObject({ nested: { key: true} }); // ✅ +* isPlainObject(new Proxy({}, {})); // ✅ +* isPlainObject({ [Symbol('tag')]: 'A' }); // ✅ +* +* // ✅👇 (cross-realms, node context, workers, ...) +* const runInNewContext = await import('node:vm').then( +* (mod) => mod.runInNewContext +* ); +* isPlainObject(runInNewContext('({})')); // ✅ +* +* // ❌👇 False +* +* class Test { }; +* isPlainObject(new Test()) // ❌ +* isPlainObject(10); // ❌ +* isPlainObject(null); // ❌ +* isPlainObject('hello'); // ❌ +* isPlainObject([]); // ❌ +* isPlainObject(new Date()); // ❌ +* isPlainObject(new Uint8Array([1])); // ❌ +* isPlainObject(Buffer.from('ABC')); // ❌ +* isPlainObject(Promise.resolve({})); // ❌ +* isPlainObject(Object.create({})); // ❌ +* isPlainObject(new (class Cls {})); // ❌ +* isPlainObject(globalThis); // ❌, +* ``` +*/ +function isPlainObject(value) { + if (!value || typeof value !== "object") return false; + const proto = Object.getPrototypeOf(value); + if (!(proto === null || proto === Object.prototype || Object.getPrototypeOf(proto) === null)) return false; + return Object.prototype.toString.call(value) === "[object Object]"; +} +//#endregion +export { isPlainObject }; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isPrimitive.d.mts b/tools/ui/node_modules/es-toolkit/dist/predicate/isPrimitive.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..722b9f4296626cae6bb2d857a406d169734bf0f3 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isPrimitive.d.mts @@ -0,0 +1,32 @@ +//#region src/predicate/isPrimitive.d.ts +/** + * Checks whether a value is a JavaScript primitive. + * JavaScript primitives include null, undefined, strings, numbers, booleans, symbols, and bigints. + * + * @param {unknown} value The value to check. + * @returns {value is + * null + * | undefined + * | string + * | number + * | boolean + * | symbol + * | bigint} Returns true if `value` is a primitive, false otherwise. + * + * @example + * isPrimitive(null); // true + * isPrimitive(undefined); // true + * isPrimitive('123'); // true + * isPrimitive(false); // true + * isPrimitive(true); // true + * isPrimitive(Symbol('a')); // true + * isPrimitive(123n); // true + * isPrimitive({}); // false + * isPrimitive(new Date()); // false + * isPrimitive(new Map()); // false + * isPrimitive(new Set()); // false + * isPrimitive([1, 2, 3]); // false + */ +declare function isPrimitive(value: unknown): value is null | undefined | string | number | boolean | symbol | bigint; +//#endregion +export { isPrimitive }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isPrimitive.d.ts b/tools/ui/node_modules/es-toolkit/dist/predicate/isPrimitive.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..722b9f4296626cae6bb2d857a406d169734bf0f3 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isPrimitive.d.ts @@ -0,0 +1,32 @@ +//#region src/predicate/isPrimitive.d.ts +/** + * Checks whether a value is a JavaScript primitive. + * JavaScript primitives include null, undefined, strings, numbers, booleans, symbols, and bigints. + * + * @param {unknown} value The value to check. + * @returns {value is + * null + * | undefined + * | string + * | number + * | boolean + * | symbol + * | bigint} Returns true if `value` is a primitive, false otherwise. + * + * @example + * isPrimitive(null); // true + * isPrimitive(undefined); // true + * isPrimitive('123'); // true + * isPrimitive(false); // true + * isPrimitive(true); // true + * isPrimitive(Symbol('a')); // true + * isPrimitive(123n); // true + * isPrimitive({}); // false + * isPrimitive(new Date()); // false + * isPrimitive(new Map()); // false + * isPrimitive(new Set()); // false + * isPrimitive([1, 2, 3]); // false + */ +declare function isPrimitive(value: unknown): value is null | undefined | string | number | boolean | symbol | bigint; +//#endregion +export { isPrimitive }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isPrimitive.js b/tools/ui/node_modules/es-toolkit/dist/predicate/isPrimitive.js new file mode 100644 index 0000000000000000000000000000000000000000..998aaefdb0cc72cab38c07952e2515777d814bfc --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isPrimitive.js @@ -0,0 +1,34 @@ +//#region src/predicate/isPrimitive.ts +/** +* Checks whether a value is a JavaScript primitive. +* JavaScript primitives include null, undefined, strings, numbers, booleans, symbols, and bigints. +* +* @param {unknown} value The value to check. +* @returns {value is +* null +* | undefined +* | string +* | number +* | boolean +* | symbol +* | bigint} Returns true if `value` is a primitive, false otherwise. +* +* @example +* isPrimitive(null); // true +* isPrimitive(undefined); // true +* isPrimitive('123'); // true +* isPrimitive(false); // true +* isPrimitive(true); // true +* isPrimitive(Symbol('a')); // true +* isPrimitive(123n); // true +* isPrimitive({}); // false +* isPrimitive(new Date()); // false +* isPrimitive(new Map()); // false +* isPrimitive(new Set()); // false +* isPrimitive([1, 2, 3]); // false +*/ +function isPrimitive(value) { + return value == null || typeof value !== "object" && typeof value !== "function"; +} +//#endregion +exports.isPrimitive = isPrimitive; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isPrimitive.mjs b/tools/ui/node_modules/es-toolkit/dist/predicate/isPrimitive.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a1ec0effeac5cdec8eed2fe0bd486fdf191a3fdc --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isPrimitive.mjs @@ -0,0 +1,34 @@ +//#region src/predicate/isPrimitive.ts +/** +* Checks whether a value is a JavaScript primitive. +* JavaScript primitives include null, undefined, strings, numbers, booleans, symbols, and bigints. +* +* @param {unknown} value The value to check. +* @returns {value is +* null +* | undefined +* | string +* | number +* | boolean +* | symbol +* | bigint} Returns true if `value` is a primitive, false otherwise. +* +* @example +* isPrimitive(null); // true +* isPrimitive(undefined); // true +* isPrimitive('123'); // true +* isPrimitive(false); // true +* isPrimitive(true); // true +* isPrimitive(Symbol('a')); // true +* isPrimitive(123n); // true +* isPrimitive({}); // false +* isPrimitive(new Date()); // false +* isPrimitive(new Map()); // false +* isPrimitive(new Set()); // false +* isPrimitive([1, 2, 3]); // false +*/ +function isPrimitive(value) { + return value == null || typeof value !== "object" && typeof value !== "function"; +} +//#endregion +export { isPrimitive }; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isPromise.d.mts b/tools/ui/node_modules/es-toolkit/dist/predicate/isPromise.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..2fb34cb70ff498890cb9af72da5a27c09e28846b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isPromise.d.mts @@ -0,0 +1,21 @@ +//#region src/predicate/isPromise.d.ts +/** + * Checks if a given value is `Promise`. + * + * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `Promise`. + * + * @param {unknown} value The value to check if it is a `Promise`. + * @returns {value is Promise} Returns `true` if `value` is a `Promise`, else `false`. + * + * @example + * const value1 = new Promise((resolve) => resolve()); + * const value2 = {}; + * const value3 = 123; + * + * console.log(isPromise(value1)); // true + * console.log(isPromise(value2)); // false + * console.log(isPromise(value3)); // false + */ +declare function isPromise(value: unknown): value is Promise; +//#endregion +export { isPromise }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isPromise.d.ts b/tools/ui/node_modules/es-toolkit/dist/predicate/isPromise.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2fb34cb70ff498890cb9af72da5a27c09e28846b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isPromise.d.ts @@ -0,0 +1,21 @@ +//#region src/predicate/isPromise.d.ts +/** + * Checks if a given value is `Promise`. + * + * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `Promise`. + * + * @param {unknown} value The value to check if it is a `Promise`. + * @returns {value is Promise} Returns `true` if `value` is a `Promise`, else `false`. + * + * @example + * const value1 = new Promise((resolve) => resolve()); + * const value2 = {}; + * const value3 = 123; + * + * console.log(isPromise(value1)); // true + * console.log(isPromise(value2)); // false + * console.log(isPromise(value3)); // false + */ +declare function isPromise(value: unknown): value is Promise; +//#endregion +export { isPromise }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isPromise.js b/tools/ui/node_modules/es-toolkit/dist/predicate/isPromise.js new file mode 100644 index 0000000000000000000000000000000000000000..f31f29713ab5f61db12105fc66c6b6de9287d8c4 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isPromise.js @@ -0,0 +1,23 @@ +//#region src/predicate/isPromise.ts +/** +* Checks if a given value is `Promise`. +* +* This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `Promise`. +* +* @param {unknown} value The value to check if it is a `Promise`. +* @returns {value is Promise} Returns `true` if `value` is a `Promise`, else `false`. +* +* @example +* const value1 = new Promise((resolve) => resolve()); +* const value2 = {}; +* const value3 = 123; +* +* console.log(isPromise(value1)); // true +* console.log(isPromise(value2)); // false +* console.log(isPromise(value3)); // false +*/ +function isPromise(value) { + return value instanceof Promise; +} +//#endregion +exports.isPromise = isPromise; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isPromise.mjs b/tools/ui/node_modules/es-toolkit/dist/predicate/isPromise.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c1c65063b94e31c633c304f368753a9bac037ba5 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isPromise.mjs @@ -0,0 +1,23 @@ +//#region src/predicate/isPromise.ts +/** +* Checks if a given value is `Promise`. +* +* This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `Promise`. +* +* @param {unknown} value The value to check if it is a `Promise`. +* @returns {value is Promise} Returns `true` if `value` is a `Promise`, else `false`. +* +* @example +* const value1 = new Promise((resolve) => resolve()); +* const value2 = {}; +* const value3 = 123; +* +* console.log(isPromise(value1)); // true +* console.log(isPromise(value2)); // false +* console.log(isPromise(value3)); // false +*/ +function isPromise(value) { + return value instanceof Promise; +} +//#endregion +export { isPromise }; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isRegExp.d.mts b/tools/ui/node_modules/es-toolkit/dist/predicate/isRegExp.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..0fbdff797488caf58aeea230e164f7a8f5d3e4c6 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isRegExp.d.mts @@ -0,0 +1,17 @@ +//#region src/predicate/isRegExp.d.ts +/** + * Checks if `value` is a RegExp. + * + * @param {unknown} value The value to check. + * @returns {value is RegExp} Returns `true` if `value` is a RegExp, `false` otherwise. + * + * @example + * const value1 = /abc/; + * const value2 = '/abc/'; + * + * console.log(isRegExp(value1)); // true + * console.log(isRegExp(value2)); // false + */ +declare function isRegExp(value: unknown): value is RegExp; +//#endregion +export { isRegExp }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isRegExp.d.ts b/tools/ui/node_modules/es-toolkit/dist/predicate/isRegExp.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0fbdff797488caf58aeea230e164f7a8f5d3e4c6 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isRegExp.d.ts @@ -0,0 +1,17 @@ +//#region src/predicate/isRegExp.d.ts +/** + * Checks if `value` is a RegExp. + * + * @param {unknown} value The value to check. + * @returns {value is RegExp} Returns `true` if `value` is a RegExp, `false` otherwise. + * + * @example + * const value1 = /abc/; + * const value2 = '/abc/'; + * + * console.log(isRegExp(value1)); // true + * console.log(isRegExp(value2)); // false + */ +declare function isRegExp(value: unknown): value is RegExp; +//#endregion +export { isRegExp }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isRegExp.js b/tools/ui/node_modules/es-toolkit/dist/predicate/isRegExp.js new file mode 100644 index 0000000000000000000000000000000000000000..7467d55bcefe1ac1c35a362dc3b79d1d3d70d96e --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isRegExp.js @@ -0,0 +1,19 @@ +//#region src/predicate/isRegExp.ts +/** +* Checks if `value` is a RegExp. +* +* @param {unknown} value The value to check. +* @returns {value is RegExp} Returns `true` if `value` is a RegExp, `false` otherwise. +* +* @example +* const value1 = /abc/; +* const value2 = '/abc/'; +* +* console.log(isRegExp(value1)); // true +* console.log(isRegExp(value2)); // false +*/ +function isRegExp(value) { + return value instanceof RegExp; +} +//#endregion +exports.isRegExp = isRegExp; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isRegExp.mjs b/tools/ui/node_modules/es-toolkit/dist/predicate/isRegExp.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4d29a74634939e43a5dd39f26e3480e3d830615d --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isRegExp.mjs @@ -0,0 +1,19 @@ +//#region src/predicate/isRegExp.ts +/** +* Checks if `value` is a RegExp. +* +* @param {unknown} value The value to check. +* @returns {value is RegExp} Returns `true` if `value` is a RegExp, `false` otherwise. +* +* @example +* const value1 = /abc/; +* const value2 = '/abc/'; +* +* console.log(isRegExp(value1)); // true +* console.log(isRegExp(value2)); // false +*/ +function isRegExp(value) { + return value instanceof RegExp; +} +//#endregion +export { isRegExp }; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isSet.d.mts b/tools/ui/node_modules/es-toolkit/dist/predicate/isSet.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..644423492bad51b9236005ed1329127cc90b2ad0 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isSet.d.mts @@ -0,0 +1,21 @@ +//#region src/predicate/isSet.d.ts +/** + * Checks if a given value is `Set`. + * + * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `Set`. + * + * @param {unknown} value The value to check if it is a `Set`. + * @returns {value is Set} Returns `true` if `value` is a `Set`, else `false`. + * + * @example + * const value1 = new Set(); + * const value2 = new Map(); + * const value3 = new WeakSet(); + * + * console.log(isSet(value1)); // true + * console.log(isSet(value2)); // false + * console.log(isSet(value3)); // false + */ +declare function isSet(value: unknown): value is Set; +//#endregion +export { isSet }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isSet.d.ts b/tools/ui/node_modules/es-toolkit/dist/predicate/isSet.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..644423492bad51b9236005ed1329127cc90b2ad0 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isSet.d.ts @@ -0,0 +1,21 @@ +//#region src/predicate/isSet.d.ts +/** + * Checks if a given value is `Set`. + * + * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `Set`. + * + * @param {unknown} value The value to check if it is a `Set`. + * @returns {value is Set} Returns `true` if `value` is a `Set`, else `false`. + * + * @example + * const value1 = new Set(); + * const value2 = new Map(); + * const value3 = new WeakSet(); + * + * console.log(isSet(value1)); // true + * console.log(isSet(value2)); // false + * console.log(isSet(value3)); // false + */ +declare function isSet(value: unknown): value is Set; +//#endregion +export { isSet }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isSet.js b/tools/ui/node_modules/es-toolkit/dist/predicate/isSet.js new file mode 100644 index 0000000000000000000000000000000000000000..de9e01a80b41b1e12e7046480112a10d04210377 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isSet.js @@ -0,0 +1,23 @@ +//#region src/predicate/isSet.ts +/** +* Checks if a given value is `Set`. +* +* This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `Set`. +* +* @param {unknown} value The value to check if it is a `Set`. +* @returns {value is Set} Returns `true` if `value` is a `Set`, else `false`. +* +* @example +* const value1 = new Set(); +* const value2 = new Map(); +* const value3 = new WeakSet(); +* +* console.log(isSet(value1)); // true +* console.log(isSet(value2)); // false +* console.log(isSet(value3)); // false +*/ +function isSet(value) { + return value instanceof Set; +} +//#endregion +exports.isSet = isSet; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isSet.mjs b/tools/ui/node_modules/es-toolkit/dist/predicate/isSet.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8584b54894ac33c270f9e827f79301322f5e90d0 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isSet.mjs @@ -0,0 +1,23 @@ +//#region src/predicate/isSet.ts +/** +* Checks if a given value is `Set`. +* +* This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `Set`. +* +* @param {unknown} value The value to check if it is a `Set`. +* @returns {value is Set} Returns `true` if `value` is a `Set`, else `false`. +* +* @example +* const value1 = new Set(); +* const value2 = new Map(); +* const value3 = new WeakSet(); +* +* console.log(isSet(value1)); // true +* console.log(isSet(value2)); // false +* console.log(isSet(value3)); // false +*/ +function isSet(value) { + return value instanceof Set; +} +//#endregion +export { isSet }; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isString.d.mts b/tools/ui/node_modules/es-toolkit/dist/predicate/isString.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..333f099054de155e6b32a07371a96601db55c6b6 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isString.d.mts @@ -0,0 +1,21 @@ +//#region src/predicate/isString.d.ts +/** + * Checks if a given value is string. + * + * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `string`. + * + * @param {unknown} value The value to check if it is string. + * @returns {value is string} Returns `true` if `value` is a string, else `false`. + * + * @example + * const value1 = 'abc'; + * const value2 = 123; + * const value3 = true; + * + * console.log(isString(value1)); // true + * console.log(isString(value2)); // false + * console.log(isString(value3)); // false + */ +declare function isString(value: unknown): value is string; +//#endregion +export { isString }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isString.d.ts b/tools/ui/node_modules/es-toolkit/dist/predicate/isString.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..333f099054de155e6b32a07371a96601db55c6b6 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isString.d.ts @@ -0,0 +1,21 @@ +//#region src/predicate/isString.d.ts +/** + * Checks if a given value is string. + * + * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `string`. + * + * @param {unknown} value The value to check if it is string. + * @returns {value is string} Returns `true` if `value` is a string, else `false`. + * + * @example + * const value1 = 'abc'; + * const value2 = 123; + * const value3 = true; + * + * console.log(isString(value1)); // true + * console.log(isString(value2)); // false + * console.log(isString(value3)); // false + */ +declare function isString(value: unknown): value is string; +//#endregion +export { isString }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isString.js b/tools/ui/node_modules/es-toolkit/dist/predicate/isString.js new file mode 100644 index 0000000000000000000000000000000000000000..a9f9b70dcf8754ddd2beb8ca766d9299e23042cf --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isString.js @@ -0,0 +1,23 @@ +//#region src/predicate/isString.ts +/** +* Checks if a given value is string. +* +* This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `string`. +* +* @param {unknown} value The value to check if it is string. +* @returns {value is string} Returns `true` if `value` is a string, else `false`. +* +* @example +* const value1 = 'abc'; +* const value2 = 123; +* const value3 = true; +* +* console.log(isString(value1)); // true +* console.log(isString(value2)); // false +* console.log(isString(value3)); // false +*/ +function isString(value) { + return typeof value === "string"; +} +//#endregion +exports.isString = isString; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isString.mjs b/tools/ui/node_modules/es-toolkit/dist/predicate/isString.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b23ed510419b21117f30e47aea1fc485fe5790a0 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isString.mjs @@ -0,0 +1,23 @@ +//#region src/predicate/isString.ts +/** +* Checks if a given value is string. +* +* This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `string`. +* +* @param {unknown} value The value to check if it is string. +* @returns {value is string} Returns `true` if `value` is a string, else `false`. +* +* @example +* const value1 = 'abc'; +* const value2 = 123; +* const value3 = true; +* +* console.log(isString(value1)); // true +* console.log(isString(value2)); // false +* console.log(isString(value3)); // false +*/ +function isString(value) { + return typeof value === "string"; +} +//#endregion +export { isString }; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isSymbol.d.mts b/tools/ui/node_modules/es-toolkit/dist/predicate/isSymbol.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..8428a8d65b723ae055eb82243f2276ad0e762f0e --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isSymbol.d.mts @@ -0,0 +1,27 @@ +//#region src/predicate/isSymbol.d.ts +/** + * Check whether a value is a symbol. + * + * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `symbol`. + * + * @param {unknown} value The value to check. + * @returns {value is symbol} Returns `true` if `value` is a symbol, else `false`. + * + * @example + * import { isSymbol } from 'es-toolkit/predicate'; + * + * isSymbol(Symbol('a')); // true + * isSymbol(Symbol.for('a')); // true + * isSymbol(Symbol.iterator); // true + * + * isSymbol(null); // false + * isSymbol(undefined); // false + * isSymbol('123'); // false + * isSymbol(false); // false + * isSymbol(123n); // false + * isSymbol({}); // false + * isSymbol([1, 2, 3]); // false + */ +declare function isSymbol(value: unknown): value is symbol; +//#endregion +export { isSymbol }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isSymbol.d.ts b/tools/ui/node_modules/es-toolkit/dist/predicate/isSymbol.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8428a8d65b723ae055eb82243f2276ad0e762f0e --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isSymbol.d.ts @@ -0,0 +1,27 @@ +//#region src/predicate/isSymbol.d.ts +/** + * Check whether a value is a symbol. + * + * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `symbol`. + * + * @param {unknown} value The value to check. + * @returns {value is symbol} Returns `true` if `value` is a symbol, else `false`. + * + * @example + * import { isSymbol } from 'es-toolkit/predicate'; + * + * isSymbol(Symbol('a')); // true + * isSymbol(Symbol.for('a')); // true + * isSymbol(Symbol.iterator); // true + * + * isSymbol(null); // false + * isSymbol(undefined); // false + * isSymbol('123'); // false + * isSymbol(false); // false + * isSymbol(123n); // false + * isSymbol({}); // false + * isSymbol([1, 2, 3]); // false + */ +declare function isSymbol(value: unknown): value is symbol; +//#endregion +export { isSymbol }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isSymbol.js b/tools/ui/node_modules/es-toolkit/dist/predicate/isSymbol.js new file mode 100644 index 0000000000000000000000000000000000000000..863d68fd83395bf17196d054f69ee7c5ee8a9d76 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isSymbol.js @@ -0,0 +1,29 @@ +//#region src/predicate/isSymbol.ts +/** +* Check whether a value is a symbol. +* +* This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `symbol`. +* +* @param {unknown} value The value to check. +* @returns {value is symbol} Returns `true` if `value` is a symbol, else `false`. +* +* @example +* import { isSymbol } from 'es-toolkit/predicate'; +* +* isSymbol(Symbol('a')); // true +* isSymbol(Symbol.for('a')); // true +* isSymbol(Symbol.iterator); // true +* +* isSymbol(null); // false +* isSymbol(undefined); // false +* isSymbol('123'); // false +* isSymbol(false); // false +* isSymbol(123n); // false +* isSymbol({}); // false +* isSymbol([1, 2, 3]); // false +*/ +function isSymbol(value) { + return typeof value === "symbol"; +} +//#endregion +exports.isSymbol = isSymbol; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isSymbol.mjs b/tools/ui/node_modules/es-toolkit/dist/predicate/isSymbol.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5b6d4da7b193d283a0a51b238a81b11a688e6d96 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isSymbol.mjs @@ -0,0 +1,29 @@ +//#region src/predicate/isSymbol.ts +/** +* Check whether a value is a symbol. +* +* This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `symbol`. +* +* @param {unknown} value The value to check. +* @returns {value is symbol} Returns `true` if `value` is a symbol, else `false`. +* +* @example +* import { isSymbol } from 'es-toolkit/predicate'; +* +* isSymbol(Symbol('a')); // true +* isSymbol(Symbol.for('a')); // true +* isSymbol(Symbol.iterator); // true +* +* isSymbol(null); // false +* isSymbol(undefined); // false +* isSymbol('123'); // false +* isSymbol(false); // false +* isSymbol(123n); // false +* isSymbol({}); // false +* isSymbol([1, 2, 3]); // false +*/ +function isSymbol(value) { + return typeof value === "symbol"; +} +//#endregion +export { isSymbol }; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isTypedArray.d.mts b/tools/ui/node_modules/es-toolkit/dist/predicate/isTypedArray.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..23740eae0a8cb264e2bb4cb1b885226022f44c83 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isTypedArray.d.mts @@ -0,0 +1,30 @@ +//#region src/predicate/isTypedArray.d.ts +/** + * Checks if a value is a TypedArray. + * @param {unknown} x The value to check. + * @returns {x is + * Uint8Array + * | Uint8ClampedArray + * | Uint16Array + * | Uint32Array + * | BigUint64Array + * | Int8Array + * | Int16Array + * | Int32Array + * | BigInt64Array + * | Float32Array + * | Float64Array} Returns true if `x` is a TypedArray, false otherwise. + * + * @example + * const arr = new Uint8Array([1, 2, 3]); + * isTypedArray(arr); // true + * + * const regularArray = [1, 2, 3]; + * isTypedArray(regularArray); // false + * + * const buffer = new ArrayBuffer(16); + * isTypedArray(buffer); // false + */ +declare function isTypedArray(x: unknown): x is Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | BigUint64Array | Int8Array | Int16Array | Int32Array | BigInt64Array | Float32Array | Float64Array; +//#endregion +export { isTypedArray }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isTypedArray.d.ts b/tools/ui/node_modules/es-toolkit/dist/predicate/isTypedArray.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..23740eae0a8cb264e2bb4cb1b885226022f44c83 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isTypedArray.d.ts @@ -0,0 +1,30 @@ +//#region src/predicate/isTypedArray.d.ts +/** + * Checks if a value is a TypedArray. + * @param {unknown} x The value to check. + * @returns {x is + * Uint8Array + * | Uint8ClampedArray + * | Uint16Array + * | Uint32Array + * | BigUint64Array + * | Int8Array + * | Int16Array + * | Int32Array + * | BigInt64Array + * | Float32Array + * | Float64Array} Returns true if `x` is a TypedArray, false otherwise. + * + * @example + * const arr = new Uint8Array([1, 2, 3]); + * isTypedArray(arr); // true + * + * const regularArray = [1, 2, 3]; + * isTypedArray(regularArray); // false + * + * const buffer = new ArrayBuffer(16); + * isTypedArray(buffer); // false + */ +declare function isTypedArray(x: unknown): x is Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | BigUint64Array | Int8Array | Int16Array | Int32Array | BigInt64Array | Float32Array | Float64Array; +//#endregion +export { isTypedArray }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isTypedArray.js b/tools/ui/node_modules/es-toolkit/dist/predicate/isTypedArray.js new file mode 100644 index 0000000000000000000000000000000000000000..1b369a18d80515d52de7591f26ff56321b122c99 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isTypedArray.js @@ -0,0 +1,32 @@ +//#region src/predicate/isTypedArray.ts +/** +* Checks if a value is a TypedArray. +* @param {unknown} x The value to check. +* @returns {x is +* Uint8Array +* | Uint8ClampedArray +* | Uint16Array +* | Uint32Array +* | BigUint64Array +* | Int8Array +* | Int16Array +* | Int32Array +* | BigInt64Array +* | Float32Array +* | Float64Array} Returns true if `x` is a TypedArray, false otherwise. +* +* @example +* const arr = new Uint8Array([1, 2, 3]); +* isTypedArray(arr); // true +* +* const regularArray = [1, 2, 3]; +* isTypedArray(regularArray); // false +* +* const buffer = new ArrayBuffer(16); +* isTypedArray(buffer); // false +*/ +function isTypedArray(x) { + return ArrayBuffer.isView(x) && !(x instanceof DataView); +} +//#endregion +exports.isTypedArray = isTypedArray; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isTypedArray.mjs b/tools/ui/node_modules/es-toolkit/dist/predicate/isTypedArray.mjs new file mode 100644 index 0000000000000000000000000000000000000000..291fcbfe93348f360ba3e2f4cce2031393a6d6e0 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isTypedArray.mjs @@ -0,0 +1,32 @@ +//#region src/predicate/isTypedArray.ts +/** +* Checks if a value is a TypedArray. +* @param {unknown} x The value to check. +* @returns {x is +* Uint8Array +* | Uint8ClampedArray +* | Uint16Array +* | Uint32Array +* | BigUint64Array +* | Int8Array +* | Int16Array +* | Int32Array +* | BigInt64Array +* | Float32Array +* | Float64Array} Returns true if `x` is a TypedArray, false otherwise. +* +* @example +* const arr = new Uint8Array([1, 2, 3]); +* isTypedArray(arr); // true +* +* const regularArray = [1, 2, 3]; +* isTypedArray(regularArray); // false +* +* const buffer = new ArrayBuffer(16); +* isTypedArray(buffer); // false +*/ +function isTypedArray(x) { + return ArrayBuffer.isView(x) && !(x instanceof DataView); +} +//#endregion +export { isTypedArray }; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isUndefined.d.mts b/tools/ui/node_modules/es-toolkit/dist/predicate/isUndefined.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..cc821fb9f2bbcfc178d6ce64fc54e7b851c1fc60 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isUndefined.d.mts @@ -0,0 +1,24 @@ +//#region src/predicate/isUndefined.d.ts +/** + * Checks if the given value is undefined. + * + * This function tests whether the provided value is strictly equal to `undefined`. + * It returns `true` if the value is `undefined`, and `false` otherwise. + * + * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `undefined`. + * + * @param {unknown} x - The value to test if it is undefined. + * @returns {x is undefined} true if the value is undefined, false otherwise. + * + * @example + * const value1 = undefined; + * const value2 = null; + * const value3 = 42; + * + * console.log(isUndefined(value1)); // true + * console.log(isUndefined(value2)); // false + * console.log(isUndefined(value3)); // false + */ +declare function isUndefined(x: any): x is undefined; +//#endregion +export { isUndefined }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isUndefined.d.ts b/tools/ui/node_modules/es-toolkit/dist/predicate/isUndefined.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cc821fb9f2bbcfc178d6ce64fc54e7b851c1fc60 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isUndefined.d.ts @@ -0,0 +1,24 @@ +//#region src/predicate/isUndefined.d.ts +/** + * Checks if the given value is undefined. + * + * This function tests whether the provided value is strictly equal to `undefined`. + * It returns `true` if the value is `undefined`, and `false` otherwise. + * + * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `undefined`. + * + * @param {unknown} x - The value to test if it is undefined. + * @returns {x is undefined} true if the value is undefined, false otherwise. + * + * @example + * const value1 = undefined; + * const value2 = null; + * const value3 = 42; + * + * console.log(isUndefined(value1)); // true + * console.log(isUndefined(value2)); // false + * console.log(isUndefined(value3)); // false + */ +declare function isUndefined(x: any): x is undefined; +//#endregion +export { isUndefined }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isUndefined.js b/tools/ui/node_modules/es-toolkit/dist/predicate/isUndefined.js new file mode 100644 index 0000000000000000000000000000000000000000..1a596952ecc01b36e4c92a8c68552583d22b2cbd --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isUndefined.js @@ -0,0 +1,26 @@ +//#region src/predicate/isUndefined.ts +/** +* Checks if the given value is undefined. +* +* This function tests whether the provided value is strictly equal to `undefined`. +* It returns `true` if the value is `undefined`, and `false` otherwise. +* +* This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `undefined`. +* +* @param {unknown} x - The value to test if it is undefined. +* @returns {x is undefined} true if the value is undefined, false otherwise. +* +* @example +* const value1 = undefined; +* const value2 = null; +* const value3 = 42; +* +* console.log(isUndefined(value1)); // true +* console.log(isUndefined(value2)); // false +* console.log(isUndefined(value3)); // false +*/ +function isUndefined(x) { + return x === void 0; +} +//#endregion +exports.isUndefined = isUndefined; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isUndefined.mjs b/tools/ui/node_modules/es-toolkit/dist/predicate/isUndefined.mjs new file mode 100644 index 0000000000000000000000000000000000000000..090723f4e34bebc2e2aef89cbaca5afc1e7740ce --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isUndefined.mjs @@ -0,0 +1,26 @@ +//#region src/predicate/isUndefined.ts +/** +* Checks if the given value is undefined. +* +* This function tests whether the provided value is strictly equal to `undefined`. +* It returns `true` if the value is `undefined`, and `false` otherwise. +* +* This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `undefined`. +* +* @param {unknown} x - The value to test if it is undefined. +* @returns {x is undefined} true if the value is undefined, false otherwise. +* +* @example +* const value1 = undefined; +* const value2 = null; +* const value3 = 42; +* +* console.log(isUndefined(value1)); // true +* console.log(isUndefined(value2)); // false +* console.log(isUndefined(value3)); // false +*/ +function isUndefined(x) { + return x === void 0; +} +//#endregion +export { isUndefined }; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isWeakMap.d.mts b/tools/ui/node_modules/es-toolkit/dist/predicate/isWeakMap.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..a7fddf7e93e747db38ae9d9fd7df6fd53022cf17 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isWeakMap.d.mts @@ -0,0 +1,24 @@ +//#region src/predicate/isWeakMap.d.ts +/** + * Checks if the given value is a `WeakMap`. + * + * This function tests whether the provided value is an instance of `WeakMap`. + * It returns `true` if the value is a `WeakMap`, and `false` otherwise. + * + * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `WeakMap`. + * + * @param {unknown} value - The value to test if it is a `WeakMap`. + * @returns {value is WeakMap} true if the value is a `WeakMap`, false otherwise. + * + * @example + * const value1 = new WeakMap(); + * const value2 = new Map(); + * const value3 = new Set(); + * + * console.log(isWeakMap(value1)); // true + * console.log(isWeakMap(value2)); // false + * console.log(isWeakMap(value3)); // false + */ +declare function isWeakMap(value: unknown): value is WeakMap; +//#endregion +export { isWeakMap }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isWeakMap.d.ts b/tools/ui/node_modules/es-toolkit/dist/predicate/isWeakMap.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a7fddf7e93e747db38ae9d9fd7df6fd53022cf17 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isWeakMap.d.ts @@ -0,0 +1,24 @@ +//#region src/predicate/isWeakMap.d.ts +/** + * Checks if the given value is a `WeakMap`. + * + * This function tests whether the provided value is an instance of `WeakMap`. + * It returns `true` if the value is a `WeakMap`, and `false` otherwise. + * + * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `WeakMap`. + * + * @param {unknown} value - The value to test if it is a `WeakMap`. + * @returns {value is WeakMap} true if the value is a `WeakMap`, false otherwise. + * + * @example + * const value1 = new WeakMap(); + * const value2 = new Map(); + * const value3 = new Set(); + * + * console.log(isWeakMap(value1)); // true + * console.log(isWeakMap(value2)); // false + * console.log(isWeakMap(value3)); // false + */ +declare function isWeakMap(value: unknown): value is WeakMap; +//#endregion +export { isWeakMap }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isWeakMap.js b/tools/ui/node_modules/es-toolkit/dist/predicate/isWeakMap.js new file mode 100644 index 0000000000000000000000000000000000000000..a3e4f728215a1cc0a9df1eadd22c63f260d7b491 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isWeakMap.js @@ -0,0 +1,26 @@ +//#region src/predicate/isWeakMap.ts +/** +* Checks if the given value is a `WeakMap`. +* +* This function tests whether the provided value is an instance of `WeakMap`. +* It returns `true` if the value is a `WeakMap`, and `false` otherwise. +* +* This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `WeakMap`. +* +* @param {unknown} value - The value to test if it is a `WeakMap`. +* @returns {value is WeakMap} true if the value is a `WeakMap`, false otherwise. +* +* @example +* const value1 = new WeakMap(); +* const value2 = new Map(); +* const value3 = new Set(); +* +* console.log(isWeakMap(value1)); // true +* console.log(isWeakMap(value2)); // false +* console.log(isWeakMap(value3)); // false +*/ +function isWeakMap(value) { + return value instanceof WeakMap; +} +//#endregion +exports.isWeakMap = isWeakMap; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isWeakMap.mjs b/tools/ui/node_modules/es-toolkit/dist/predicate/isWeakMap.mjs new file mode 100644 index 0000000000000000000000000000000000000000..fd785f3df564a2e20d256e9e5642f8bae2dd48a9 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isWeakMap.mjs @@ -0,0 +1,26 @@ +//#region src/predicate/isWeakMap.ts +/** +* Checks if the given value is a `WeakMap`. +* +* This function tests whether the provided value is an instance of `WeakMap`. +* It returns `true` if the value is a `WeakMap`, and `false` otherwise. +* +* This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `WeakMap`. +* +* @param {unknown} value - The value to test if it is a `WeakMap`. +* @returns {value is WeakMap} true if the value is a `WeakMap`, false otherwise. +* +* @example +* const value1 = new WeakMap(); +* const value2 = new Map(); +* const value3 = new Set(); +* +* console.log(isWeakMap(value1)); // true +* console.log(isWeakMap(value2)); // false +* console.log(isWeakMap(value3)); // false +*/ +function isWeakMap(value) { + return value instanceof WeakMap; +} +//#endregion +export { isWeakMap }; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isWeakSet.d.mts b/tools/ui/node_modules/es-toolkit/dist/predicate/isWeakSet.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..94d7142985cc0f335446e4e5c40fd85dd50bb23f --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isWeakSet.d.mts @@ -0,0 +1,24 @@ +//#region src/predicate/isWeakSet.d.ts +/** + * Checks if the given value is a `WeakSet`. + * + * This function tests whether the provided value is an instance of `WeakSet`. + * It returns `true` if the value is a `WeakSet`, and `false` otherwise. + * + * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `WeakSet`. + * + * @param {unknown} value - The value to test if it is a `WeakSet`. + * @returns {value is WeakSet} true if the value is a `WeakSet`, false otherwise. + * + * @example + * const value1 = new WeakSet(); + * const value2 = new Map(); + * const value3 = new Set(); + * + * console.log(isWeakSet(value1)); // true + * console.log(isWeakSet(value2)); // false + * console.log(isWeakSet(value3)); // false + */ +declare function isWeakSet(value: unknown): value is WeakSet; +//#endregion +export { isWeakSet }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isWeakSet.d.ts b/tools/ui/node_modules/es-toolkit/dist/predicate/isWeakSet.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..94d7142985cc0f335446e4e5c40fd85dd50bb23f --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isWeakSet.d.ts @@ -0,0 +1,24 @@ +//#region src/predicate/isWeakSet.d.ts +/** + * Checks if the given value is a `WeakSet`. + * + * This function tests whether the provided value is an instance of `WeakSet`. + * It returns `true` if the value is a `WeakSet`, and `false` otherwise. + * + * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `WeakSet`. + * + * @param {unknown} value - The value to test if it is a `WeakSet`. + * @returns {value is WeakSet} true if the value is a `WeakSet`, false otherwise. + * + * @example + * const value1 = new WeakSet(); + * const value2 = new Map(); + * const value3 = new Set(); + * + * console.log(isWeakSet(value1)); // true + * console.log(isWeakSet(value2)); // false + * console.log(isWeakSet(value3)); // false + */ +declare function isWeakSet(value: unknown): value is WeakSet; +//#endregion +export { isWeakSet }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isWeakSet.js b/tools/ui/node_modules/es-toolkit/dist/predicate/isWeakSet.js new file mode 100644 index 0000000000000000000000000000000000000000..8ee647f14712e3620f6639745f544e84c4fed2f3 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isWeakSet.js @@ -0,0 +1,26 @@ +//#region src/predicate/isWeakSet.ts +/** +* Checks if the given value is a `WeakSet`. +* +* This function tests whether the provided value is an instance of `WeakSet`. +* It returns `true` if the value is a `WeakSet`, and `false` otherwise. +* +* This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `WeakSet`. +* +* @param {unknown} value - The value to test if it is a `WeakSet`. +* @returns {value is WeakSet} true if the value is a `WeakSet`, false otherwise. +* +* @example +* const value1 = new WeakSet(); +* const value2 = new Map(); +* const value3 = new Set(); +* +* console.log(isWeakSet(value1)); // true +* console.log(isWeakSet(value2)); // false +* console.log(isWeakSet(value3)); // false +*/ +function isWeakSet(value) { + return value instanceof WeakSet; +} +//#endregion +exports.isWeakSet = isWeakSet; diff --git a/tools/ui/node_modules/es-toolkit/dist/predicate/isWeakSet.mjs b/tools/ui/node_modules/es-toolkit/dist/predicate/isWeakSet.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e98608b4ba05b557fa0070e7f6dac3f0a7d78991 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/predicate/isWeakSet.mjs @@ -0,0 +1,26 @@ +//#region src/predicate/isWeakSet.ts +/** +* Checks if the given value is a `WeakSet`. +* +* This function tests whether the provided value is an instance of `WeakSet`. +* It returns `true` if the value is a `WeakSet`, and `false` otherwise. +* +* This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `WeakSet`. +* +* @param {unknown} value - The value to test if it is a `WeakSet`. +* @returns {value is WeakSet} true if the value is a `WeakSet`, false otherwise. +* +* @example +* const value1 = new WeakSet(); +* const value2 = new Map(); +* const value3 = new Set(); +* +* console.log(isWeakSet(value1)); // true +* console.log(isWeakSet(value2)); // false +* console.log(isWeakSet(value3)); // false +*/ +function isWeakSet(value) { + return value instanceof WeakSet; +} +//#endregion +export { isWeakSet }; diff --git a/tools/ui/node_modules/es-toolkit/dist/promise/allKeyed.d.mts b/tools/ui/node_modules/es-toolkit/dist/promise/allKeyed.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..6e4461ab49e85571f7f9f65bf249faec18761ab7 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/promise/allKeyed.d.mts @@ -0,0 +1,31 @@ +//#region src/promise/allKeyed.d.ts +/** + * Resolves an object of promises concurrently, returning an object with the same keys and resolved values. + * + * Similar to `Promise.all`, but accepts an object of promises instead of an array, + * preserving the keys in the result. This makes it easy to destructure the resolved values + * by name instead of relying on positional indices. + * + * Based on the [TC39 `Promise.allKeyed` proposal](https://github.com/tc39/proposal-await-dictionary). + * + * @template T - A record type where each value is a promise or a value. + * @param {T} tasks - An object whose values are promises (or plain values) to resolve concurrently. + * @returns {Promise<{ [K in keyof T]: Awaited }>} A promise that resolves to an object with the same keys and resolved values. + * + * @example + * const { user, posts } = await allKeyed({ + * user: fetchUser(), + * posts: fetchPosts(), + * }); + * + * @example + * // Plain values are also supported + * const result = await allKeyed({ + * a: Promise.resolve(1), + * b: 2, + * }); + * // { a: 1, b: 2 } + */ +declare function allKeyed>(tasks: T): Promise<{ [K in keyof T]: Awaited }>; +//#endregion +export { allKeyed }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/promise/allKeyed.d.ts b/tools/ui/node_modules/es-toolkit/dist/promise/allKeyed.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6e4461ab49e85571f7f9f65bf249faec18761ab7 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/promise/allKeyed.d.ts @@ -0,0 +1,31 @@ +//#region src/promise/allKeyed.d.ts +/** + * Resolves an object of promises concurrently, returning an object with the same keys and resolved values. + * + * Similar to `Promise.all`, but accepts an object of promises instead of an array, + * preserving the keys in the result. This makes it easy to destructure the resolved values + * by name instead of relying on positional indices. + * + * Based on the [TC39 `Promise.allKeyed` proposal](https://github.com/tc39/proposal-await-dictionary). + * + * @template T - A record type where each value is a promise or a value. + * @param {T} tasks - An object whose values are promises (or plain values) to resolve concurrently. + * @returns {Promise<{ [K in keyof T]: Awaited }>} A promise that resolves to an object with the same keys and resolved values. + * + * @example + * const { user, posts } = await allKeyed({ + * user: fetchUser(), + * posts: fetchPosts(), + * }); + * + * @example + * // Plain values are also supported + * const result = await allKeyed({ + * a: Promise.resolve(1), + * b: 2, + * }); + * // { a: 1, b: 2 } + */ +declare function allKeyed>(tasks: T): Promise<{ [K in keyof T]: Awaited }>; +//#endregion +export { allKeyed }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/promise/allKeyed.js b/tools/ui/node_modules/es-toolkit/dist/promise/allKeyed.js new file mode 100644 index 0000000000000000000000000000000000000000..315fcda78d56ebba67f7798eb4a404f6f8729214 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/promise/allKeyed.js @@ -0,0 +1,37 @@ +//#region src/promise/allKeyed.ts +/** +* Resolves an object of promises concurrently, returning an object with the same keys and resolved values. +* +* Similar to `Promise.all`, but accepts an object of promises instead of an array, +* preserving the keys in the result. This makes it easy to destructure the resolved values +* by name instead of relying on positional indices. +* +* Based on the [TC39 `Promise.allKeyed` proposal](https://github.com/tc39/proposal-await-dictionary). +* +* @template T - A record type where each value is a promise or a value. +* @param {T} tasks - An object whose values are promises (or plain values) to resolve concurrently. +* @returns {Promise<{ [K in keyof T]: Awaited }>} A promise that resolves to an object with the same keys and resolved values. +* +* @example +* const { user, posts } = await allKeyed({ +* user: fetchUser(), +* posts: fetchPosts(), +* }); +* +* @example +* // Plain values are also supported +* const result = await allKeyed({ +* a: Promise.resolve(1), +* b: 2, +* }); +* // { a: 1, b: 2 } +*/ +async function allKeyed(tasks) { + const keys = Object.keys(tasks); + const values = await Promise.all(keys.map((key) => tasks[key])); + const result = {}; + for (let i = 0; i < keys.length; i++) result[keys[i]] = values[i]; + return result; +} +//#endregion +exports.allKeyed = allKeyed; diff --git a/tools/ui/node_modules/es-toolkit/dist/promise/allKeyed.mjs b/tools/ui/node_modules/es-toolkit/dist/promise/allKeyed.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c38cf787ef290ded767846551f6c637e756e3da2 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/promise/allKeyed.mjs @@ -0,0 +1,37 @@ +//#region src/promise/allKeyed.ts +/** +* Resolves an object of promises concurrently, returning an object with the same keys and resolved values. +* +* Similar to `Promise.all`, but accepts an object of promises instead of an array, +* preserving the keys in the result. This makes it easy to destructure the resolved values +* by name instead of relying on positional indices. +* +* Based on the [TC39 `Promise.allKeyed` proposal](https://github.com/tc39/proposal-await-dictionary). +* +* @template T - A record type where each value is a promise or a value. +* @param {T} tasks - An object whose values are promises (or plain values) to resolve concurrently. +* @returns {Promise<{ [K in keyof T]: Awaited }>} A promise that resolves to an object with the same keys and resolved values. +* +* @example +* const { user, posts } = await allKeyed({ +* user: fetchUser(), +* posts: fetchPosts(), +* }); +* +* @example +* // Plain values are also supported +* const result = await allKeyed({ +* a: Promise.resolve(1), +* b: 2, +* }); +* // { a: 1, b: 2 } +*/ +async function allKeyed(tasks) { + const keys = Object.keys(tasks); + const values = await Promise.all(keys.map((key) => tasks[key])); + const result = {}; + for (let i = 0; i < keys.length; i++) result[keys[i]] = values[i]; + return result; +} +//#endregion +export { allKeyed }; diff --git a/tools/ui/node_modules/es-toolkit/dist/promise/delay.d.mts b/tools/ui/node_modules/es-toolkit/dist/promise/delay.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..3bf185ec06e3fb0ef3c43e264ce849be6a2afa41 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/promise/delay.d.mts @@ -0,0 +1,41 @@ +//#region src/promise/delay.d.ts +interface DelayOptions { + signal?: AbortSignal; +} +/** + * Delays the execution of code for a specified number of milliseconds. + * + * This function returns a Promise that resolves after the specified delay, allowing you to use it + * with async/await to pause execution. + * + * @param {number} ms - The number of milliseconds to delay. + * @param {DelayOptions} options - The options object. + * @param {AbortSignal} options.signal - An optional AbortSignal to cancel the delay. + * @returns {Promise} A Promise that resolves after the specified delay. + * + * @example + * async function foo() { + * console.log('Start'); + * await delay(1000); // Delays execution for 1 second + * console.log('End'); + * } + * + * foo(); + * + * // With AbortSignal + * const controller = new AbortController(); + * const { signal } = controller; + * + * setTimeout(() => controller.abort(), 50); // Will cancel the delay after 50ms + * try { + * await delay(100, { signal }); + * } catch (error) { + * console.error(error); // Will log 'AbortError' + * } + * } + */ +declare function delay(ms: number, { + signal +}?: DelayOptions): Promise; +//#endregion +export { delay }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/promise/delay.d.ts b/tools/ui/node_modules/es-toolkit/dist/promise/delay.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3bf185ec06e3fb0ef3c43e264ce849be6a2afa41 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/promise/delay.d.ts @@ -0,0 +1,41 @@ +//#region src/promise/delay.d.ts +interface DelayOptions { + signal?: AbortSignal; +} +/** + * Delays the execution of code for a specified number of milliseconds. + * + * This function returns a Promise that resolves after the specified delay, allowing you to use it + * with async/await to pause execution. + * + * @param {number} ms - The number of milliseconds to delay. + * @param {DelayOptions} options - The options object. + * @param {AbortSignal} options.signal - An optional AbortSignal to cancel the delay. + * @returns {Promise} A Promise that resolves after the specified delay. + * + * @example + * async function foo() { + * console.log('Start'); + * await delay(1000); // Delays execution for 1 second + * console.log('End'); + * } + * + * foo(); + * + * // With AbortSignal + * const controller = new AbortController(); + * const { signal } = controller; + * + * setTimeout(() => controller.abort(), 50); // Will cancel the delay after 50ms + * try { + * await delay(100, { signal }); + * } catch (error) { + * console.error(error); // Will log 'AbortError' + * } + * } + */ +declare function delay(ms: number, { + signal +}?: DelayOptions): Promise; +//#endregion +export { delay }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/promise/delay.js b/tools/ui/node_modules/es-toolkit/dist/promise/delay.js new file mode 100644 index 0000000000000000000000000000000000000000..ddab68218579e6a5dae95aa5c82a028ef699b606 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/promise/delay.js @@ -0,0 +1,53 @@ +const require_AbortError = require("../error/AbortError.js"); +//#region src/promise/delay.ts +/** +* Delays the execution of code for a specified number of milliseconds. +* +* This function returns a Promise that resolves after the specified delay, allowing you to use it +* with async/await to pause execution. +* +* @param {number} ms - The number of milliseconds to delay. +* @param {DelayOptions} options - The options object. +* @param {AbortSignal} options.signal - An optional AbortSignal to cancel the delay. +* @returns {Promise} A Promise that resolves after the specified delay. +* +* @example +* async function foo() { +* console.log('Start'); +* await delay(1000); // Delays execution for 1 second +* console.log('End'); +* } +* +* foo(); +* +* // With AbortSignal +* const controller = new AbortController(); +* const { signal } = controller; +* +* setTimeout(() => controller.abort(), 50); // Will cancel the delay after 50ms +* try { +* await delay(100, { signal }); +* } catch (error) { +* console.error(error); // Will log 'AbortError' +* } +* } +*/ +function delay(ms, { signal } = {}) { + return new Promise((resolve, reject) => { + const abortError = () => { + reject(new require_AbortError.AbortError()); + }; + const abortHandler = () => { + clearTimeout(timeoutId); + abortError(); + }; + if (signal?.aborted) return abortError(); + const timeoutId = setTimeout(() => { + signal?.removeEventListener("abort", abortHandler); + resolve(); + }, ms); + signal?.addEventListener("abort", abortHandler, { once: true }); + }); +} +//#endregion +exports.delay = delay; diff --git a/tools/ui/node_modules/es-toolkit/dist/promise/delay.mjs b/tools/ui/node_modules/es-toolkit/dist/promise/delay.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b6a8d4a7df2a3b91621169aff4cccc3d9a7d9a06 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/promise/delay.mjs @@ -0,0 +1,53 @@ +import { AbortError } from "../error/AbortError.mjs"; +//#region src/promise/delay.ts +/** +* Delays the execution of code for a specified number of milliseconds. +* +* This function returns a Promise that resolves after the specified delay, allowing you to use it +* with async/await to pause execution. +* +* @param {number} ms - The number of milliseconds to delay. +* @param {DelayOptions} options - The options object. +* @param {AbortSignal} options.signal - An optional AbortSignal to cancel the delay. +* @returns {Promise} A Promise that resolves after the specified delay. +* +* @example +* async function foo() { +* console.log('Start'); +* await delay(1000); // Delays execution for 1 second +* console.log('End'); +* } +* +* foo(); +* +* // With AbortSignal +* const controller = new AbortController(); +* const { signal } = controller; +* +* setTimeout(() => controller.abort(), 50); // Will cancel the delay after 50ms +* try { +* await delay(100, { signal }); +* } catch (error) { +* console.error(error); // Will log 'AbortError' +* } +* } +*/ +function delay(ms, { signal } = {}) { + return new Promise((resolve, reject) => { + const abortError = () => { + reject(new AbortError()); + }; + const abortHandler = () => { + clearTimeout(timeoutId); + abortError(); + }; + if (signal?.aborted) return abortError(); + const timeoutId = setTimeout(() => { + signal?.removeEventListener("abort", abortHandler); + resolve(); + }, ms); + signal?.addEventListener("abort", abortHandler, { once: true }); + }); +} +//#endregion +export { delay }; diff --git a/tools/ui/node_modules/es-toolkit/dist/promise/index.d.mts b/tools/ui/node_modules/es-toolkit/dist/promise/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..2bf76258f8df9fe17475f9f5985215c323bff0e6 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/promise/index.d.mts @@ -0,0 +1,7 @@ +import { allKeyed } from "./allKeyed.mjs"; +import { delay } from "./delay.mjs"; +import { Mutex } from "./mutex.mjs"; +import { Semaphore } from "./semaphore.mjs"; +import { timeout } from "./timeout.mjs"; +import { withTimeout } from "./withTimeout.mjs"; +export { Mutex, Semaphore, allKeyed, delay, timeout, withTimeout }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/promise/index.d.ts b/tools/ui/node_modules/es-toolkit/dist/promise/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..489d776f85f115ac105fc746d21124ac25e2fa49 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/promise/index.d.ts @@ -0,0 +1,7 @@ +import { allKeyed } from "./allKeyed.js"; +import { delay } from "./delay.js"; +import { Mutex } from "./mutex.js"; +import { Semaphore } from "./semaphore.js"; +import { timeout } from "./timeout.js"; +import { withTimeout } from "./withTimeout.js"; +export { Mutex, Semaphore, allKeyed, delay, timeout, withTimeout }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/promise/index.js b/tools/ui/node_modules/es-toolkit/dist/promise/index.js new file mode 100644 index 0000000000000000000000000000000000000000..be9545087d647bd4b8eb01548024a4b8c2c60f3f --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/promise/index.js @@ -0,0 +1,13 @@ +Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); +const require_semaphore = require("./semaphore.js"); +const require_delay = require("./delay.js"); +const require_allKeyed = require("./allKeyed.js"); +const require_mutex = require("./mutex.js"); +const require_timeout = require("./timeout.js"); +const require_withTimeout = require("./withTimeout.js"); +exports.Mutex = require_mutex.Mutex; +exports.Semaphore = require_semaphore.Semaphore; +exports.allKeyed = require_allKeyed.allKeyed; +exports.delay = require_delay.delay; +exports.timeout = require_timeout.timeout; +exports.withTimeout = require_withTimeout.withTimeout; diff --git a/tools/ui/node_modules/es-toolkit/dist/promise/index.mjs b/tools/ui/node_modules/es-toolkit/dist/promise/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..512061bff72abbdfb62e70e4bbf386f10daaa3e6 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/promise/index.mjs @@ -0,0 +1,7 @@ +import { Semaphore } from "./semaphore.mjs"; +import { delay } from "./delay.mjs"; +import { allKeyed } from "./allKeyed.mjs"; +import { Mutex } from "./mutex.mjs"; +import { timeout } from "./timeout.mjs"; +import { withTimeout } from "./withTimeout.mjs"; +export { Mutex, Semaphore, allKeyed, delay, timeout, withTimeout }; diff --git a/tools/ui/node_modules/es-toolkit/dist/promise/mutex.d.mts b/tools/ui/node_modules/es-toolkit/dist/promise/mutex.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..68de943131eeb999dff77e9013bf89c7fc8d47ee --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/promise/mutex.d.mts @@ -0,0 +1,65 @@ +//#region src/promise/mutex.d.ts +/** + * A Mutex (mutual exclusion lock) for async functions. + * It allows only one async task to access a critical section at a time. + * + * @example + * const mutex = new Mutex(); + * + * async function criticalSection() { + * await mutex.acquire(); + * try { + * // This code section cannot be executed simultaneously + * } finally { + * mutex.release(); + * } + * } + * + * criticalSection(); + * criticalSection(); // This call will wait until the first call releases the mutex. + */ +declare class Mutex { + private semaphore; + /** + * Checks if the mutex is currently locked. + * @returns {boolean} True if the mutex is locked, false otherwise. + * + * @example + * const mutex = new Mutex(); + * console.log(mutex.isLocked); // false + * await mutex.acquire(); + * console.log(mutex.isLocked); // true + * mutex.release(); + * console.log(mutex.isLocked); // false + */ + get isLocked(): boolean; + /** + * Acquires the mutex, blocking if necessary until it is available. + * @returns {Promise} A promise that resolves when the mutex is acquired. + * + * @example + * const mutex = new Mutex(); + * await mutex.acquire(); + * try { + * // This code section cannot be executed simultaneously + * } finally { + * mutex.release(); + * } + */ + acquire(): Promise; + /** + * Releases the mutex, allowing another waiting task to proceed. + * + * @example + * const mutex = new Mutex(); + * await mutex.acquire(); + * try { + * // This code section cannot be executed simultaneously + * } finally { + * mutex.release(); // Allows another waiting task to proceed. + * } + */ + release(): void; +} +//#endregion +export { Mutex }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/promise/mutex.d.ts b/tools/ui/node_modules/es-toolkit/dist/promise/mutex.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..68de943131eeb999dff77e9013bf89c7fc8d47ee --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/promise/mutex.d.ts @@ -0,0 +1,65 @@ +//#region src/promise/mutex.d.ts +/** + * A Mutex (mutual exclusion lock) for async functions. + * It allows only one async task to access a critical section at a time. + * + * @example + * const mutex = new Mutex(); + * + * async function criticalSection() { + * await mutex.acquire(); + * try { + * // This code section cannot be executed simultaneously + * } finally { + * mutex.release(); + * } + * } + * + * criticalSection(); + * criticalSection(); // This call will wait until the first call releases the mutex. + */ +declare class Mutex { + private semaphore; + /** + * Checks if the mutex is currently locked. + * @returns {boolean} True if the mutex is locked, false otherwise. + * + * @example + * const mutex = new Mutex(); + * console.log(mutex.isLocked); // false + * await mutex.acquire(); + * console.log(mutex.isLocked); // true + * mutex.release(); + * console.log(mutex.isLocked); // false + */ + get isLocked(): boolean; + /** + * Acquires the mutex, blocking if necessary until it is available. + * @returns {Promise} A promise that resolves when the mutex is acquired. + * + * @example + * const mutex = new Mutex(); + * await mutex.acquire(); + * try { + * // This code section cannot be executed simultaneously + * } finally { + * mutex.release(); + * } + */ + acquire(): Promise; + /** + * Releases the mutex, allowing another waiting task to proceed. + * + * @example + * const mutex = new Mutex(); + * await mutex.acquire(); + * try { + * // This code section cannot be executed simultaneously + * } finally { + * mutex.release(); // Allows another waiting task to proceed. + * } + */ + release(): void; +} +//#endregion +export { Mutex }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/promise/mutex.js b/tools/ui/node_modules/es-toolkit/dist/promise/mutex.js new file mode 100644 index 0000000000000000000000000000000000000000..ffbf3dbc7e8c9c6ef7e3d70461908575cc12d93c --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/promise/mutex.js @@ -0,0 +1,72 @@ +const require_semaphore = require("./semaphore.js"); +//#region src/promise/mutex.ts +/** +* A Mutex (mutual exclusion lock) for async functions. +* It allows only one async task to access a critical section at a time. +* +* @example +* const mutex = new Mutex(); +* +* async function criticalSection() { +* await mutex.acquire(); +* try { +* // This code section cannot be executed simultaneously +* } finally { +* mutex.release(); +* } +* } +* +* criticalSection(); +* criticalSection(); // This call will wait until the first call releases the mutex. +*/ +var Mutex = class { + semaphore = new require_semaphore.Semaphore(1); + /** + * Checks if the mutex is currently locked. + * @returns {boolean} True if the mutex is locked, false otherwise. + * + * @example + * const mutex = new Mutex(); + * console.log(mutex.isLocked); // false + * await mutex.acquire(); + * console.log(mutex.isLocked); // true + * mutex.release(); + * console.log(mutex.isLocked); // false + */ + get isLocked() { + return this.semaphore.available === 0; + } + /** + * Acquires the mutex, blocking if necessary until it is available. + * @returns {Promise} A promise that resolves when the mutex is acquired. + * + * @example + * const mutex = new Mutex(); + * await mutex.acquire(); + * try { + * // This code section cannot be executed simultaneously + * } finally { + * mutex.release(); + * } + */ + async acquire() { + return this.semaphore.acquire(); + } + /** + * Releases the mutex, allowing another waiting task to proceed. + * + * @example + * const mutex = new Mutex(); + * await mutex.acquire(); + * try { + * // This code section cannot be executed simultaneously + * } finally { + * mutex.release(); // Allows another waiting task to proceed. + * } + */ + release() { + this.semaphore.release(); + } +}; +//#endregion +exports.Mutex = Mutex; diff --git a/tools/ui/node_modules/es-toolkit/dist/promise/mutex.mjs b/tools/ui/node_modules/es-toolkit/dist/promise/mutex.mjs new file mode 100644 index 0000000000000000000000000000000000000000..12d2b53275a324dacd52e6816fe8467db27d2975 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/promise/mutex.mjs @@ -0,0 +1,72 @@ +import { Semaphore } from "./semaphore.mjs"; +//#region src/promise/mutex.ts +/** +* A Mutex (mutual exclusion lock) for async functions. +* It allows only one async task to access a critical section at a time. +* +* @example +* const mutex = new Mutex(); +* +* async function criticalSection() { +* await mutex.acquire(); +* try { +* // This code section cannot be executed simultaneously +* } finally { +* mutex.release(); +* } +* } +* +* criticalSection(); +* criticalSection(); // This call will wait until the first call releases the mutex. +*/ +var Mutex = class { + semaphore = new Semaphore(1); + /** + * Checks if the mutex is currently locked. + * @returns {boolean} True if the mutex is locked, false otherwise. + * + * @example + * const mutex = new Mutex(); + * console.log(mutex.isLocked); // false + * await mutex.acquire(); + * console.log(mutex.isLocked); // true + * mutex.release(); + * console.log(mutex.isLocked); // false + */ + get isLocked() { + return this.semaphore.available === 0; + } + /** + * Acquires the mutex, blocking if necessary until it is available. + * @returns {Promise} A promise that resolves when the mutex is acquired. + * + * @example + * const mutex = new Mutex(); + * await mutex.acquire(); + * try { + * // This code section cannot be executed simultaneously + * } finally { + * mutex.release(); + * } + */ + async acquire() { + return this.semaphore.acquire(); + } + /** + * Releases the mutex, allowing another waiting task to proceed. + * + * @example + * const mutex = new Mutex(); + * await mutex.acquire(); + * try { + * // This code section cannot be executed simultaneously + * } finally { + * mutex.release(); // Allows another waiting task to proceed. + * } + */ + release() { + this.semaphore.release(); + } +}; +//#endregion +export { Mutex }; diff --git a/tools/ui/node_modules/es-toolkit/dist/promise/semaphore.d.mts b/tools/ui/node_modules/es-toolkit/dist/promise/semaphore.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..46580601b168859b0ab86b0519c3936a2703b0c2 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/promise/semaphore.d.mts @@ -0,0 +1,82 @@ +//#region src/promise/semaphore.d.ts +/** + * A counting semaphore for async functions that manages available permits. + * Semaphores are mainly used to limit the number of concurrent async tasks. + * + * Each `acquire` operation takes a permit or waits until one is available. + * Each `release` operation adds a permit, potentially allowing a waiting task to proceed. + * + * The semaphore ensures fairness by maintaining a FIFO (First In, First Out) order for acquirers. + * + * @example + * const sema = new Semaphore(2); + * + * async function task() { + * await sema.acquire(); + * try { + * // This code can only be executed by two tasks at the same time + * } finally { + * sema.release(); + * } + * } + * + * task(); + * task(); + * task(); // This task will wait until one of the previous tasks releases the semaphore. + */ +declare class Semaphore { + /** + * The maximum number of concurrent operations allowed. + * @type {number} + */ + capacity: number; + /** + * The number of available permits. + * @type {number} + */ + available: number; + private deferredTasks; + /** + * Creates an instance of Semaphore. + * @param {number} capacity - The maximum number of concurrent operations allowed. + * + * @example + * const sema = new Semaphore(3); // Allows up to 3 concurrent operations. + */ + constructor(capacity: number); + /** + * Acquires a semaphore, blocking if necessary until one is available. + * @returns {Promise} A promise that resolves when the semaphore is acquired. + * + * @example + * const sema = new Semaphore(1); + * + * async function criticalSection() { + * await sema.acquire(); + * try { + * // This code section cannot be executed simultaneously + * } finally { + * sema.release(); + * } + * } + */ + acquire(): Promise; + /** + * Releases a semaphore, allowing one more operation to proceed. + * + * @example + * const sema = new Semaphore(1); + * + * async function task() { + * await sema.acquire(); + * try { + * // This code can only be executed by two tasks at the same time + * } finally { + * sema.release(); // Allows another waiting task to proceed. + * } + * } + */ + release(): void; +} +//#endregion +export { Semaphore }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/promise/semaphore.d.ts b/tools/ui/node_modules/es-toolkit/dist/promise/semaphore.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..46580601b168859b0ab86b0519c3936a2703b0c2 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/promise/semaphore.d.ts @@ -0,0 +1,82 @@ +//#region src/promise/semaphore.d.ts +/** + * A counting semaphore for async functions that manages available permits. + * Semaphores are mainly used to limit the number of concurrent async tasks. + * + * Each `acquire` operation takes a permit or waits until one is available. + * Each `release` operation adds a permit, potentially allowing a waiting task to proceed. + * + * The semaphore ensures fairness by maintaining a FIFO (First In, First Out) order for acquirers. + * + * @example + * const sema = new Semaphore(2); + * + * async function task() { + * await sema.acquire(); + * try { + * // This code can only be executed by two tasks at the same time + * } finally { + * sema.release(); + * } + * } + * + * task(); + * task(); + * task(); // This task will wait until one of the previous tasks releases the semaphore. + */ +declare class Semaphore { + /** + * The maximum number of concurrent operations allowed. + * @type {number} + */ + capacity: number; + /** + * The number of available permits. + * @type {number} + */ + available: number; + private deferredTasks; + /** + * Creates an instance of Semaphore. + * @param {number} capacity - The maximum number of concurrent operations allowed. + * + * @example + * const sema = new Semaphore(3); // Allows up to 3 concurrent operations. + */ + constructor(capacity: number); + /** + * Acquires a semaphore, blocking if necessary until one is available. + * @returns {Promise} A promise that resolves when the semaphore is acquired. + * + * @example + * const sema = new Semaphore(1); + * + * async function criticalSection() { + * await sema.acquire(); + * try { + * // This code section cannot be executed simultaneously + * } finally { + * sema.release(); + * } + * } + */ + acquire(): Promise; + /** + * Releases a semaphore, allowing one more operation to proceed. + * + * @example + * const sema = new Semaphore(1); + * + * async function task() { + * await sema.acquire(); + * try { + * // This code can only be executed by two tasks at the same time + * } finally { + * sema.release(); // Allows another waiting task to proceed. + * } + * } + */ + release(): void; +} +//#endregion +export { Semaphore }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/promise/semaphore.js b/tools/ui/node_modules/es-toolkit/dist/promise/semaphore.js new file mode 100644 index 0000000000000000000000000000000000000000..8fd701a2d07b9852c806d5f4b1ed91a457cbdf6f --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/promise/semaphore.js @@ -0,0 +1,100 @@ +//#region src/promise/semaphore.ts +/** +* A counting semaphore for async functions that manages available permits. +* Semaphores are mainly used to limit the number of concurrent async tasks. +* +* Each `acquire` operation takes a permit or waits until one is available. +* Each `release` operation adds a permit, potentially allowing a waiting task to proceed. +* +* The semaphore ensures fairness by maintaining a FIFO (First In, First Out) order for acquirers. +* +* @example +* const sema = new Semaphore(2); +* +* async function task() { +* await sema.acquire(); +* try { +* // This code can only be executed by two tasks at the same time +* } finally { +* sema.release(); +* } +* } +* +* task(); +* task(); +* task(); // This task will wait until one of the previous tasks releases the semaphore. +*/ +var Semaphore = class { + /** + * The maximum number of concurrent operations allowed. + * @type {number} + */ + capacity; + /** + * The number of available permits. + * @type {number} + */ + available; + deferredTasks = []; + /** + * Creates an instance of Semaphore. + * @param {number} capacity - The maximum number of concurrent operations allowed. + * + * @example + * const sema = new Semaphore(3); // Allows up to 3 concurrent operations. + */ + constructor(capacity) { + this.capacity = capacity; + this.available = capacity; + } + /** + * Acquires a semaphore, blocking if necessary until one is available. + * @returns {Promise} A promise that resolves when the semaphore is acquired. + * + * @example + * const sema = new Semaphore(1); + * + * async function criticalSection() { + * await sema.acquire(); + * try { + * // This code section cannot be executed simultaneously + * } finally { + * sema.release(); + * } + * } + */ + async acquire() { + if (this.available > 0) { + this.available--; + return; + } + return new Promise((resolve) => { + this.deferredTasks.push(resolve); + }); + } + /** + * Releases a semaphore, allowing one more operation to proceed. + * + * @example + * const sema = new Semaphore(1); + * + * async function task() { + * await sema.acquire(); + * try { + * // This code can only be executed by two tasks at the same time + * } finally { + * sema.release(); // Allows another waiting task to proceed. + * } + * } + */ + release() { + const deferredTask = this.deferredTasks.shift(); + if (deferredTask != null) { + deferredTask(); + return; + } + if (this.available < this.capacity) this.available++; + } +}; +//#endregion +exports.Semaphore = Semaphore; diff --git a/tools/ui/node_modules/es-toolkit/dist/promise/semaphore.mjs b/tools/ui/node_modules/es-toolkit/dist/promise/semaphore.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3bc19e155f1d368c8d6ffb35c6049b7c556cf0da --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/promise/semaphore.mjs @@ -0,0 +1,100 @@ +//#region src/promise/semaphore.ts +/** +* A counting semaphore for async functions that manages available permits. +* Semaphores are mainly used to limit the number of concurrent async tasks. +* +* Each `acquire` operation takes a permit or waits until one is available. +* Each `release` operation adds a permit, potentially allowing a waiting task to proceed. +* +* The semaphore ensures fairness by maintaining a FIFO (First In, First Out) order for acquirers. +* +* @example +* const sema = new Semaphore(2); +* +* async function task() { +* await sema.acquire(); +* try { +* // This code can only be executed by two tasks at the same time +* } finally { +* sema.release(); +* } +* } +* +* task(); +* task(); +* task(); // This task will wait until one of the previous tasks releases the semaphore. +*/ +var Semaphore = class { + /** + * The maximum number of concurrent operations allowed. + * @type {number} + */ + capacity; + /** + * The number of available permits. + * @type {number} + */ + available; + deferredTasks = []; + /** + * Creates an instance of Semaphore. + * @param {number} capacity - The maximum number of concurrent operations allowed. + * + * @example + * const sema = new Semaphore(3); // Allows up to 3 concurrent operations. + */ + constructor(capacity) { + this.capacity = capacity; + this.available = capacity; + } + /** + * Acquires a semaphore, blocking if necessary until one is available. + * @returns {Promise} A promise that resolves when the semaphore is acquired. + * + * @example + * const sema = new Semaphore(1); + * + * async function criticalSection() { + * await sema.acquire(); + * try { + * // This code section cannot be executed simultaneously + * } finally { + * sema.release(); + * } + * } + */ + async acquire() { + if (this.available > 0) { + this.available--; + return; + } + return new Promise((resolve) => { + this.deferredTasks.push(resolve); + }); + } + /** + * Releases a semaphore, allowing one more operation to proceed. + * + * @example + * const sema = new Semaphore(1); + * + * async function task() { + * await sema.acquire(); + * try { + * // This code can only be executed by two tasks at the same time + * } finally { + * sema.release(); // Allows another waiting task to proceed. + * } + * } + */ + release() { + const deferredTask = this.deferredTasks.shift(); + if (deferredTask != null) { + deferredTask(); + return; + } + if (this.available < this.capacity) this.available++; + } +}; +//#endregion +export { Semaphore }; diff --git a/tools/ui/node_modules/es-toolkit/dist/promise/timeout.d.mts b/tools/ui/node_modules/es-toolkit/dist/promise/timeout.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..aed7296efe93a27ee62ac91d539eabf1f76413e3 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/promise/timeout.d.mts @@ -0,0 +1,18 @@ +//#region src/promise/timeout.d.ts +/** + * Returns a promise that rejects with a `TimeoutError` after a specified delay. + * + * @param {number} ms - The delay duration in milliseconds. + * @returns {Promise} A promise that rejects with a `TimeoutError` after the specified delay. + * @throws {TimeoutError} Throws a `TimeoutError` after the specified delay. + * + * @example + * try { + * await timeout(1000); // Timeout exception after 1 second + * } catch (error) { + * console.error(error); // Will log 'The operation was timed out' + * } + */ +declare function timeout(ms: number): Promise; +//#endregion +export { timeout }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/promise/timeout.d.ts b/tools/ui/node_modules/es-toolkit/dist/promise/timeout.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..aed7296efe93a27ee62ac91d539eabf1f76413e3 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/promise/timeout.d.ts @@ -0,0 +1,18 @@ +//#region src/promise/timeout.d.ts +/** + * Returns a promise that rejects with a `TimeoutError` after a specified delay. + * + * @param {number} ms - The delay duration in milliseconds. + * @returns {Promise} A promise that rejects with a `TimeoutError` after the specified delay. + * @throws {TimeoutError} Throws a `TimeoutError` after the specified delay. + * + * @example + * try { + * await timeout(1000); // Timeout exception after 1 second + * } catch (error) { + * console.error(error); // Will log 'The operation was timed out' + * } + */ +declare function timeout(ms: number): Promise; +//#endregion +export { timeout }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/promise/timeout.js b/tools/ui/node_modules/es-toolkit/dist/promise/timeout.js new file mode 100644 index 0000000000000000000000000000000000000000..b5cf99aa59efdc8c904c7d9596cb018fa294c3f8 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/promise/timeout.js @@ -0,0 +1,23 @@ +const require_TimeoutError = require("../error/TimeoutError.js"); +const require_delay = require("./delay.js"); +//#region src/promise/timeout.ts +/** +* Returns a promise that rejects with a `TimeoutError` after a specified delay. +* +* @param {number} ms - The delay duration in milliseconds. +* @returns {Promise} A promise that rejects with a `TimeoutError` after the specified delay. +* @throws {TimeoutError} Throws a `TimeoutError` after the specified delay. +* +* @example +* try { +* await timeout(1000); // Timeout exception after 1 second +* } catch (error) { +* console.error(error); // Will log 'The operation was timed out' +* } +*/ +async function timeout(ms) { + await require_delay.delay(ms); + throw new require_TimeoutError.TimeoutError(); +} +//#endregion +exports.timeout = timeout; diff --git a/tools/ui/node_modules/es-toolkit/dist/promise/timeout.mjs b/tools/ui/node_modules/es-toolkit/dist/promise/timeout.mjs new file mode 100644 index 0000000000000000000000000000000000000000..619ccf8a8ee758776caa4c36b173c0333f2fa59d --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/promise/timeout.mjs @@ -0,0 +1,23 @@ +import { TimeoutError } from "../error/TimeoutError.mjs"; +import { delay } from "./delay.mjs"; +//#region src/promise/timeout.ts +/** +* Returns a promise that rejects with a `TimeoutError` after a specified delay. +* +* @param {number} ms - The delay duration in milliseconds. +* @returns {Promise} A promise that rejects with a `TimeoutError` after the specified delay. +* @throws {TimeoutError} Throws a `TimeoutError` after the specified delay. +* +* @example +* try { +* await timeout(1000); // Timeout exception after 1 second +* } catch (error) { +* console.error(error); // Will log 'The operation was timed out' +* } +*/ +async function timeout(ms) { + await delay(ms); + throw new TimeoutError(); +} +//#endregion +export { timeout }; diff --git a/tools/ui/node_modules/es-toolkit/dist/promise/withTimeout.d.mts b/tools/ui/node_modules/es-toolkit/dist/promise/withTimeout.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..615c4672cdb61f5c00b64b5b536007576dbe0589 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/promise/withTimeout.d.mts @@ -0,0 +1,29 @@ +//#region src/promise/withTimeout.d.ts +/** + * Executes an async function and enforces a timeout. + * + * If the promise does not resolve within the specified time, + * the timeout will trigger and the returned promise will be rejected. + * + * + * @template T + * @param {() => Promise} run - A function that returns a promise to be executed. + * @param {number} ms - The timeout duration in milliseconds. + * @returns {Promise} A promise that resolves with the result of the `run` function or rejects if the timeout is reached. + * + * @example + * async function fetchData() { + * const response = await fetch('https://example.com/data'); + * return response.json(); + * } + * + * try { + * const data = await withTimeout(fetchData, 1000); + * console.log(data); // Logs the fetched data if `fetchData` is resolved within 1 second. + * } catch (error) { + * console.error(error); // Will log 'TimeoutError' if `fetchData` is not resolved within 1 second. + * } + */ +declare function withTimeout(run: () => Promise, ms: number): Promise; +//#endregion +export { withTimeout }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/promise/withTimeout.d.ts b/tools/ui/node_modules/es-toolkit/dist/promise/withTimeout.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..615c4672cdb61f5c00b64b5b536007576dbe0589 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/promise/withTimeout.d.ts @@ -0,0 +1,29 @@ +//#region src/promise/withTimeout.d.ts +/** + * Executes an async function and enforces a timeout. + * + * If the promise does not resolve within the specified time, + * the timeout will trigger and the returned promise will be rejected. + * + * + * @template T + * @param {() => Promise} run - A function that returns a promise to be executed. + * @param {number} ms - The timeout duration in milliseconds. + * @returns {Promise} A promise that resolves with the result of the `run` function or rejects if the timeout is reached. + * + * @example + * async function fetchData() { + * const response = await fetch('https://example.com/data'); + * return response.json(); + * } + * + * try { + * const data = await withTimeout(fetchData, 1000); + * console.log(data); // Logs the fetched data if `fetchData` is resolved within 1 second. + * } catch (error) { + * console.error(error); // Will log 'TimeoutError' if `fetchData` is not resolved within 1 second. + * } + */ +declare function withTimeout(run: () => Promise, ms: number): Promise; +//#endregion +export { withTimeout }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/promise/withTimeout.js b/tools/ui/node_modules/es-toolkit/dist/promise/withTimeout.js new file mode 100644 index 0000000000000000000000000000000000000000..ca67d971dda2f8bd196ecd3f720f5f64541c2214 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/promise/withTimeout.js @@ -0,0 +1,32 @@ +const require_timeout = require("./timeout.js"); +//#region src/promise/withTimeout.ts +/** +* Executes an async function and enforces a timeout. +* +* If the promise does not resolve within the specified time, +* the timeout will trigger and the returned promise will be rejected. +* +* +* @template T +* @param {() => Promise} run - A function that returns a promise to be executed. +* @param {number} ms - The timeout duration in milliseconds. +* @returns {Promise} A promise that resolves with the result of the `run` function or rejects if the timeout is reached. +* +* @example +* async function fetchData() { +* const response = await fetch('https://example.com/data'); +* return response.json(); +* } +* +* try { +* const data = await withTimeout(fetchData, 1000); +* console.log(data); // Logs the fetched data if `fetchData` is resolved within 1 second. +* } catch (error) { +* console.error(error); // Will log 'TimeoutError' if `fetchData` is not resolved within 1 second. +* } +*/ +async function withTimeout(run, ms) { + return Promise.race([run(), require_timeout.timeout(ms)]); +} +//#endregion +exports.withTimeout = withTimeout; diff --git a/tools/ui/node_modules/es-toolkit/dist/promise/withTimeout.mjs b/tools/ui/node_modules/es-toolkit/dist/promise/withTimeout.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2a7743fed127de1e57557b901845270b966de27b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/promise/withTimeout.mjs @@ -0,0 +1,32 @@ +import { timeout } from "./timeout.mjs"; +//#region src/promise/withTimeout.ts +/** +* Executes an async function and enforces a timeout. +* +* If the promise does not resolve within the specified time, +* the timeout will trigger and the returned promise will be rejected. +* +* +* @template T +* @param {() => Promise} run - A function that returns a promise to be executed. +* @param {number} ms - The timeout duration in milliseconds. +* @returns {Promise} A promise that resolves with the result of the `run` function or rejects if the timeout is reached. +* +* @example +* async function fetchData() { +* const response = await fetch('https://example.com/data'); +* return response.json(); +* } +* +* try { +* const data = await withTimeout(fetchData, 1000); +* console.log(data); // Logs the fetched data if `fetchData` is resolved within 1 second. +* } catch (error) { +* console.error(error); // Will log 'TimeoutError' if `fetchData` is not resolved within 1 second. +* } +*/ +async function withTimeout(run, ms) { + return Promise.race([run(), timeout(ms)]); +} +//#endregion +export { withTimeout }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/_internal/parseHex.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/_internal/parseHex.js new file mode 100644 index 0000000000000000000000000000000000000000..ebcd1b587ab7bb9df1ac9973ac73df3d9a842984 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/_internal/parseHex.js @@ -0,0 +1,32 @@ +//#region src/server/colors/_internal/parseHex.ts +const BLACK = [ + 0, + 0, + 0 +]; +const HEX_COLOR_REGEX = /^[0-9a-fA-F]{3}$|^[0-9a-fA-F]{6}$/; +/** +* Parses a hex color string (e.g. "#ff0000", "#f00", "ff0000") into +* an [r, g, b] tuple. Used by `hex()` and `bgHex()` to convert +* user-provided hex values into RGB components for ANSI escape codes. +* +* Only #RGB and #RRGGBB formats are supported. #RGBA and #RRGGBBAA +* are not accepted because ANSI terminals do not support alpha channels. +* Returns [0, 0, 0] (black) for invalid input. +* +* @param hex - A hex color string, with or without the leading `#`. +* @returns An `[r, g, b]` tuple with each component in the 0–255 range. +*/ +function parseHex(hex) { + const raw = hex.startsWith("#") ? hex.slice(1) : hex; + if (!HEX_COLOR_REGEX.test(raw)) return BLACK; + const full = raw.length === 3 ? raw[0] + raw[0] + raw[1] + raw[1] + raw[2] + raw[2] : raw; + const colorValue = parseInt(full, 16); + return [ + colorValue >> 16 & 255, + colorValue >> 8 & 255, + colorValue & 255 + ]; +} +//#endregion +exports.parseHex = parseHex; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/_internal/parseHex.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/_internal/parseHex.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3ea613035d87016afea70367d4aafc716258e8d5 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/_internal/parseHex.mjs @@ -0,0 +1,32 @@ +//#region src/server/colors/_internal/parseHex.ts +const BLACK = [ + 0, + 0, + 0 +]; +const HEX_COLOR_REGEX = /^[0-9a-fA-F]{3}$|^[0-9a-fA-F]{6}$/; +/** +* Parses a hex color string (e.g. "#ff0000", "#f00", "ff0000") into +* an [r, g, b] tuple. Used by `hex()` and `bgHex()` to convert +* user-provided hex values into RGB components for ANSI escape codes. +* +* Only #RGB and #RRGGBB formats are supported. #RGBA and #RRGGBBAA +* are not accepted because ANSI terminals do not support alpha channels. +* Returns [0, 0, 0] (black) for invalid input. +* +* @param hex - A hex color string, with or without the leading `#`. +* @returns An `[r, g, b]` tuple with each component in the 0–255 range. +*/ +function parseHex(hex) { + const raw = hex.startsWith("#") ? hex.slice(1) : hex; + if (!HEX_COLOR_REGEX.test(raw)) return BLACK; + const full = raw.length === 3 ? raw[0] + raw[0] + raw[1] + raw[1] + raw[2] + raw[2] : raw; + const colorValue = parseInt(full, 16); + return [ + colorValue >> 16 & 255, + colorValue >> 8 & 255, + colorValue & 255 + ]; +} +//#endregion +export { parseHex }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/_internal/wrapAnsi.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/_internal/wrapAnsi.js new file mode 100644 index 0000000000000000000000000000000000000000..857f7601c08cdb411c057a2af85e83210da543d1 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/_internal/wrapAnsi.js @@ -0,0 +1,21 @@ +//#region src/server/colors/_internal/wrapAnsi.ts +/** +* Wraps text with ANSI open/close codes for foreground colors and modifiers. +* +* If `text` already contains `close` (typically from a nested style that +* shares the same close code, e.g. `red(green('x'))` where both end with +* `\x1b[39m`), re-opens the outer style after each occurrence so the rest +* of the text keeps its color. For background colors use `wrapAnsiBg` +* instead — it adds the newline handling that backgrounds need. +* +* @param open - The ANSI open code (e.g. `\x1b[31m`). +* @param close - The ANSI close code (e.g. `\x1b[39m`). +* @param text - The text to wrap. +* @returns The wrapped text. +*/ +function wrapAnsi(open, close, text) { + if (text.includes(close)) text = text.replaceAll(close, close + open); + return open + text + close; +} +//#endregion +exports.wrapAnsi = wrapAnsi; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/_internal/wrapAnsi.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/_internal/wrapAnsi.mjs new file mode 100644 index 0000000000000000000000000000000000000000..52ed5fc3fdfc3994f72a0b5afcb049b396aaa4b5 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/_internal/wrapAnsi.mjs @@ -0,0 +1,21 @@ +//#region src/server/colors/_internal/wrapAnsi.ts +/** +* Wraps text with ANSI open/close codes for foreground colors and modifiers. +* +* If `text` already contains `close` (typically from a nested style that +* shares the same close code, e.g. `red(green('x'))` where both end with +* `\x1b[39m`), re-opens the outer style after each occurrence so the rest +* of the text keeps its color. For background colors use `wrapAnsiBg` +* instead — it adds the newline handling that backgrounds need. +* +* @param open - The ANSI open code (e.g. `\x1b[31m`). +* @param close - The ANSI close code (e.g. `\x1b[39m`). +* @param text - The text to wrap. +* @returns The wrapped text. +*/ +function wrapAnsi(open, close, text) { + if (text.includes(close)) text = text.replaceAll(close, close + open); + return open + text + close; +} +//#endregion +export { wrapAnsi }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/_internal/wrapAnsiBg.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/_internal/wrapAnsiBg.js new file mode 100644 index 0000000000000000000000000000000000000000..41b10fea01322f4987a0cadf07aeb0fe65f2e008 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/_internal/wrapAnsiBg.js @@ -0,0 +1,30 @@ +//#region src/server/colors/_internal/wrapAnsiBg.ts +/** +* Wraps text with ANSI open/close codes for background colors. +* +* On top of the basic wrap, handles two cases: +* +* 1. **Nested style sharing the same close.** If `text` already contains +* `close` (e.g. `bgRed(bgGreen('x'))` where both end with `\x1b[49m`), +* re-opens the outer style after each occurrence so the rest keeps its +* color. This step runs first. +* 2. **Multi-line text.** Terminals reset the background color at line +* boundaries, so the bg disappears after `\n` if not re-opened. Insert +* `close + open` around every newline. CRLF is treated as a single unit +* so the close sits outside both characters. +* +* Step 2 must run after step 1 — otherwise the close codes that step 2 +* inserts would also trigger step 1's re-open and leak duplicate codes. +* +* @param open - The ANSI background open code (e.g. `\x1b[41m`). +* @param close - The ANSI background close code (e.g. `\x1b[49m`). +* @param text - The text to wrap. +* @returns The wrapped text. +*/ +function wrapAnsiBg(open, close, text) { + if (text.includes(close)) text = text.replaceAll(close, close + open); + if (text.includes("\n")) text = text.replaceAll(/\r?\n/g, (match) => close + match + open); + return open + text + close; +} +//#endregion +exports.wrapAnsiBg = wrapAnsiBg; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/_internal/wrapAnsiBg.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/_internal/wrapAnsiBg.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0aaeaa9c19d291b9b17d8343ad81fc4337900339 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/_internal/wrapAnsiBg.mjs @@ -0,0 +1,30 @@ +//#region src/server/colors/_internal/wrapAnsiBg.ts +/** +* Wraps text with ANSI open/close codes for background colors. +* +* On top of the basic wrap, handles two cases: +* +* 1. **Nested style sharing the same close.** If `text` already contains +* `close` (e.g. `bgRed(bgGreen('x'))` where both end with `\x1b[49m`), +* re-opens the outer style after each occurrence so the rest keeps its +* color. This step runs first. +* 2. **Multi-line text.** Terminals reset the background color at line +* boundaries, so the bg disappears after `\n` if not re-opened. Insert +* `close + open` around every newline. CRLF is treated as a single unit +* so the close sits outside both characters. +* +* Step 2 must run after step 1 — otherwise the close codes that step 2 +* inserts would also trigger step 1's re-open and leak duplicate codes. +* +* @param open - The ANSI background open code (e.g. `\x1b[41m`). +* @param close - The ANSI background close code (e.g. `\x1b[49m`). +* @param text - The text to wrap. +* @returns The wrapped text. +*/ +function wrapAnsiBg(open, close, text) { + if (text.includes(close)) text = text.replaceAll(close, close + open); + if (text.includes("\n")) text = text.replaceAll(/\r?\n/g, (match) => close + match + open); + return open + text + close; +} +//#endregion +export { wrapAnsiBg }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/ansi256.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/ansi256.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..dc886f41c3ace2b122d468184263ea26c2467e48 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/ansi256.d.mts @@ -0,0 +1,18 @@ +import { ColorFunction } from "./types.mjs"; + +//#region src/server/colors/ansi256.d.ts +/** + * Returns a function that wraps text with the given 8-bit (256-color) foreground. + * + * @param code - The 8-bit color code (0–255). + * @returns A color function that wraps text with the chosen ANSI 256 foreground. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * const orange = colors.ansi256(208); + * console.log(orange('hello')); + */ +declare function ansi256(code: number): ColorFunction; +//#endregion +export { ansi256 }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/ansi256.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/ansi256.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..11555dd60e3a9473e359f87badac9837b331dd8f --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/ansi256.d.ts @@ -0,0 +1,18 @@ +import { ColorFunction } from "./types.js"; + +//#region src/server/colors/ansi256.d.ts +/** + * Returns a function that wraps text with the given 8-bit (256-color) foreground. + * + * @param code - The 8-bit color code (0–255). + * @returns A color function that wraps text with the chosen ANSI 256 foreground. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * const orange = colors.ansi256(208); + * console.log(orange('hello')); + */ +declare function ansi256(code: number): ColorFunction; +//#endregion +export { ansi256 }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/ansi256.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/ansi256.js new file mode 100644 index 0000000000000000000000000000000000000000..983d6ec076421180108abeb34e17fd80a4bb356d --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/ansi256.js @@ -0,0 +1,19 @@ +const require_wrapAnsi = require("./_internal/wrapAnsi.js"); +//#region src/server/colors/ansi256.ts +/** +* Returns a function that wraps text with the given 8-bit (256-color) foreground. +* +* @param code - The 8-bit color code (0–255). +* @returns A color function that wraps text with the chosen ANSI 256 foreground. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* const orange = colors.ansi256(208); +* console.log(orange('hello')); +*/ +function ansi256(code) { + return (text) => require_wrapAnsi.wrapAnsi(`\x1b[38;5;${code}m`, "\x1B[39m", text); +} +//#endregion +exports.ansi256 = ansi256; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/ansi256.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/ansi256.mjs new file mode 100644 index 0000000000000000000000000000000000000000..38743db3b7296e584262a8eddc873f15dcd07555 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/ansi256.mjs @@ -0,0 +1,19 @@ +import { wrapAnsi } from "./_internal/wrapAnsi.mjs"; +//#region src/server/colors/ansi256.ts +/** +* Returns a function that wraps text with the given 8-bit (256-color) foreground. +* +* @param code - The 8-bit color code (0–255). +* @returns A color function that wraps text with the chosen ANSI 256 foreground. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* const orange = colors.ansi256(208); +* console.log(orange('hello')); +*/ +function ansi256(code) { + return (text) => wrapAnsi(`\x1b[38;5;${code}m`, "\x1B[39m", text); +} +//#endregion +export { ansi256 }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgAnsi256.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgAnsi256.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..b4ce8cedee74d0435d71bdb10457099b46f97791 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgAnsi256.d.mts @@ -0,0 +1,18 @@ +import { ColorFunction } from "./types.mjs"; + +//#region src/server/colors/bgAnsi256.d.ts +/** + * Returns a function that wraps text with the given 8-bit (256-color) background. + * + * @param code - The 8-bit color code (0–255). + * @returns A color function that wraps text with the chosen ANSI 256 background. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * const warn = colors.bgAnsi256(208); + * console.log(warn('hello')); + */ +declare function bgAnsi256(code: number): ColorFunction; +//#endregion +export { bgAnsi256 }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgAnsi256.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgAnsi256.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..69a5c79998eba0eb922991f83d086aa76bda86cd --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgAnsi256.d.ts @@ -0,0 +1,18 @@ +import { ColorFunction } from "./types.js"; + +//#region src/server/colors/bgAnsi256.d.ts +/** + * Returns a function that wraps text with the given 8-bit (256-color) background. + * + * @param code - The 8-bit color code (0–255). + * @returns A color function that wraps text with the chosen ANSI 256 background. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * const warn = colors.bgAnsi256(208); + * console.log(warn('hello')); + */ +declare function bgAnsi256(code: number): ColorFunction; +//#endregion +export { bgAnsi256 }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgAnsi256.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgAnsi256.js new file mode 100644 index 0000000000000000000000000000000000000000..af9dea8b0934182c51630735bea6ef7e04b0a08f --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgAnsi256.js @@ -0,0 +1,19 @@ +const require_wrapAnsiBg = require("./_internal/wrapAnsiBg.js"); +//#region src/server/colors/bgAnsi256.ts +/** +* Returns a function that wraps text with the given 8-bit (256-color) background. +* +* @param code - The 8-bit color code (0–255). +* @returns A color function that wraps text with the chosen ANSI 256 background. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* const warn = colors.bgAnsi256(208); +* console.log(warn('hello')); +*/ +function bgAnsi256(code) { + return (text) => require_wrapAnsiBg.wrapAnsiBg(`\x1b[48;5;${code}m`, "\x1B[49m", text); +} +//#endregion +exports.bgAnsi256 = bgAnsi256; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgAnsi256.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgAnsi256.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ef3372e7e6c05cbf47151e735dd8bf33cd27cc24 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgAnsi256.mjs @@ -0,0 +1,19 @@ +import { wrapAnsiBg } from "./_internal/wrapAnsiBg.mjs"; +//#region src/server/colors/bgAnsi256.ts +/** +* Returns a function that wraps text with the given 8-bit (256-color) background. +* +* @param code - The 8-bit color code (0–255). +* @returns A color function that wraps text with the chosen ANSI 256 background. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* const warn = colors.bgAnsi256(208); +* console.log(warn('hello')); +*/ +function bgAnsi256(code) { + return (text) => wrapAnsiBg(`\x1b[48;5;${code}m`, "\x1B[49m", text); +} +//#endregion +export { bgAnsi256 }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlack.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlack.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..32b0ed8d692efbf10f45dddd7fa4cd5ca909ec57 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlack.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/bgBlack.d.ts +/** + * Black background. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bgBlack('hello')); + */ +declare function bgBlack(text: string): string; +//#endregion +export { bgBlack }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlack.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlack.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..32b0ed8d692efbf10f45dddd7fa4cd5ca909ec57 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlack.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/bgBlack.d.ts +/** + * Black background. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bgBlack('hello')); + */ +declare function bgBlack(text: string): string; +//#endregion +export { bgBlack }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlack.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlack.js new file mode 100644 index 0000000000000000000000000000000000000000..45476ece1ef0e3a97f38ae78ebe9d0cc38b433d7 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlack.js @@ -0,0 +1,18 @@ +const require_wrapAnsiBg = require("./_internal/wrapAnsiBg.js"); +//#region src/server/colors/bgBlack.ts +/** +* Black background. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bgBlack('hello')); +*/ +function bgBlack(text) { + return require_wrapAnsiBg.wrapAnsiBg("\x1B[40m", "\x1B[49m", text); +} +//#endregion +exports.bgBlack = bgBlack; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlack.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlack.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b540ddc8f68a2479cb53cbc10a23bbcc907d3273 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlack.mjs @@ -0,0 +1,18 @@ +import { wrapAnsiBg } from "./_internal/wrapAnsiBg.mjs"; +//#region src/server/colors/bgBlack.ts +/** +* Black background. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bgBlack('hello')); +*/ +function bgBlack(text) { + return wrapAnsiBg("\x1B[40m", "\x1B[49m", text); +} +//#endregion +export { bgBlack }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlackBright.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlackBright.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..b362d2844a389a915dfe3931acbe77c351c52358 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlackBright.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/bgBlackBright.d.ts +/** + * Bright black (gray) background. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bgBlackBright('hello')); + */ +declare function bgBlackBright(text: string): string; +//#endregion +export { bgBlackBright }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlackBright.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlackBright.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b362d2844a389a915dfe3931acbe77c351c52358 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlackBright.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/bgBlackBright.d.ts +/** + * Bright black (gray) background. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bgBlackBright('hello')); + */ +declare function bgBlackBright(text: string): string; +//#endregion +export { bgBlackBright }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlackBright.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlackBright.js new file mode 100644 index 0000000000000000000000000000000000000000..06c785dc3ed7bea9ac539b6dc2ba5135e3bda627 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlackBright.js @@ -0,0 +1,18 @@ +const require_wrapAnsiBg = require("./_internal/wrapAnsiBg.js"); +//#region src/server/colors/bgBlackBright.ts +/** +* Bright black (gray) background. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bgBlackBright('hello')); +*/ +function bgBlackBright(text) { + return require_wrapAnsiBg.wrapAnsiBg("\x1B[100m", "\x1B[49m", text); +} +//#endregion +exports.bgBlackBright = bgBlackBright; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlackBright.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlackBright.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b60b70e53df6fe060af1a7918322808a5fcb230c --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlackBright.mjs @@ -0,0 +1,18 @@ +import { wrapAnsiBg } from "./_internal/wrapAnsiBg.mjs"; +//#region src/server/colors/bgBlackBright.ts +/** +* Bright black (gray) background. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bgBlackBright('hello')); +*/ +function bgBlackBright(text) { + return wrapAnsiBg("\x1B[100m", "\x1B[49m", text); +} +//#endregion +export { bgBlackBright }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlue.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlue.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..3c35f05fde5d44d9b9f9961c01bd6ebb2a2bb74b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlue.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/bgBlue.d.ts +/** + * Blue background. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bgBlue('hello')); + */ +declare function bgBlue(text: string): string; +//#endregion +export { bgBlue }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlue.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlue.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3c35f05fde5d44d9b9f9961c01bd6ebb2a2bb74b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlue.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/bgBlue.d.ts +/** + * Blue background. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bgBlue('hello')); + */ +declare function bgBlue(text: string): string; +//#endregion +export { bgBlue }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlue.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlue.js new file mode 100644 index 0000000000000000000000000000000000000000..3d8f23f63369ff2ecc67e28cf6c253849c3b6d4b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlue.js @@ -0,0 +1,18 @@ +const require_wrapAnsiBg = require("./_internal/wrapAnsiBg.js"); +//#region src/server/colors/bgBlue.ts +/** +* Blue background. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bgBlue('hello')); +*/ +function bgBlue(text) { + return require_wrapAnsiBg.wrapAnsiBg("\x1B[44m", "\x1B[49m", text); +} +//#endregion +exports.bgBlue = bgBlue; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlue.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlue.mjs new file mode 100644 index 0000000000000000000000000000000000000000..46eddcbcfd89048f12b201fa3897265cc1eb1512 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlue.mjs @@ -0,0 +1,18 @@ +import { wrapAnsiBg } from "./_internal/wrapAnsiBg.mjs"; +//#region src/server/colors/bgBlue.ts +/** +* Blue background. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bgBlue('hello')); +*/ +function bgBlue(text) { + return wrapAnsiBg("\x1B[44m", "\x1B[49m", text); +} +//#endregion +export { bgBlue }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlueBright.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlueBright.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..a6cee4bdbe6ad56712312a48a13d72fb34c403a5 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlueBright.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/bgBlueBright.d.ts +/** + * Bright blue background. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bgBlueBright('hello')); + */ +declare function bgBlueBright(text: string): string; +//#endregion +export { bgBlueBright }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlueBright.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlueBright.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a6cee4bdbe6ad56712312a48a13d72fb34c403a5 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlueBright.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/bgBlueBright.d.ts +/** + * Bright blue background. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bgBlueBright('hello')); + */ +declare function bgBlueBright(text: string): string; +//#endregion +export { bgBlueBright }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlueBright.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlueBright.js new file mode 100644 index 0000000000000000000000000000000000000000..3913fa27684a73c2e2e6a01c7baf1b00739bc62d --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlueBright.js @@ -0,0 +1,18 @@ +const require_wrapAnsiBg = require("./_internal/wrapAnsiBg.js"); +//#region src/server/colors/bgBlueBright.ts +/** +* Bright blue background. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bgBlueBright('hello')); +*/ +function bgBlueBright(text) { + return require_wrapAnsiBg.wrapAnsiBg("\x1B[104m", "\x1B[49m", text); +} +//#endregion +exports.bgBlueBright = bgBlueBright; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlueBright.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlueBright.mjs new file mode 100644 index 0000000000000000000000000000000000000000..9086809c8349f3b5daed2c4f22d00d5392982e6b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgBlueBright.mjs @@ -0,0 +1,18 @@ +import { wrapAnsiBg } from "./_internal/wrapAnsiBg.mjs"; +//#region src/server/colors/bgBlueBright.ts +/** +* Bright blue background. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bgBlueBright('hello')); +*/ +function bgBlueBright(text) { + return wrapAnsiBg("\x1B[104m", "\x1B[49m", text); +} +//#endregion +export { bgBlueBright }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgCyan.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgCyan.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..d1d145ebf7663a04fe8c094923766f41fa3c8cf5 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgCyan.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/bgCyan.d.ts +/** + * Cyan background. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bgCyan('hello')); + */ +declare function bgCyan(text: string): string; +//#endregion +export { bgCyan }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgCyan.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgCyan.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d1d145ebf7663a04fe8c094923766f41fa3c8cf5 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgCyan.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/bgCyan.d.ts +/** + * Cyan background. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bgCyan('hello')); + */ +declare function bgCyan(text: string): string; +//#endregion +export { bgCyan }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgCyan.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgCyan.js new file mode 100644 index 0000000000000000000000000000000000000000..7fb0b0d9b07d42f06ff1d20bd8a87ebafcdeb0cf --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgCyan.js @@ -0,0 +1,18 @@ +const require_wrapAnsiBg = require("./_internal/wrapAnsiBg.js"); +//#region src/server/colors/bgCyan.ts +/** +* Cyan background. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bgCyan('hello')); +*/ +function bgCyan(text) { + return require_wrapAnsiBg.wrapAnsiBg("\x1B[46m", "\x1B[49m", text); +} +//#endregion +exports.bgCyan = bgCyan; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgCyan.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgCyan.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b998bd2625fbd1ce971f3a0b14b8c3d786414f1d --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgCyan.mjs @@ -0,0 +1,18 @@ +import { wrapAnsiBg } from "./_internal/wrapAnsiBg.mjs"; +//#region src/server/colors/bgCyan.ts +/** +* Cyan background. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bgCyan('hello')); +*/ +function bgCyan(text) { + return wrapAnsiBg("\x1B[46m", "\x1B[49m", text); +} +//#endregion +export { bgCyan }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgCyanBright.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgCyanBright.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..d06bd8ec62c63fae1461a13cb0549be237de8273 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgCyanBright.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/bgCyanBright.d.ts +/** + * Bright cyan background. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bgCyanBright('hello')); + */ +declare function bgCyanBright(text: string): string; +//#endregion +export { bgCyanBright }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgCyanBright.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgCyanBright.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d06bd8ec62c63fae1461a13cb0549be237de8273 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgCyanBright.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/bgCyanBright.d.ts +/** + * Bright cyan background. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bgCyanBright('hello')); + */ +declare function bgCyanBright(text: string): string; +//#endregion +export { bgCyanBright }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgCyanBright.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgCyanBright.js new file mode 100644 index 0000000000000000000000000000000000000000..c75d6257cdf807dff6efbf3c5d772f6f45768d90 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgCyanBright.js @@ -0,0 +1,18 @@ +const require_wrapAnsiBg = require("./_internal/wrapAnsiBg.js"); +//#region src/server/colors/bgCyanBright.ts +/** +* Bright cyan background. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bgCyanBright('hello')); +*/ +function bgCyanBright(text) { + return require_wrapAnsiBg.wrapAnsiBg("\x1B[106m", "\x1B[49m", text); +} +//#endregion +exports.bgCyanBright = bgCyanBright; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgCyanBright.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgCyanBright.mjs new file mode 100644 index 0000000000000000000000000000000000000000..49b832b751292717370facc871ac60c13532d2aa --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgCyanBright.mjs @@ -0,0 +1,18 @@ +import { wrapAnsiBg } from "./_internal/wrapAnsiBg.mjs"; +//#region src/server/colors/bgCyanBright.ts +/** +* Bright cyan background. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bgCyanBright('hello')); +*/ +function bgCyanBright(text) { + return wrapAnsiBg("\x1B[106m", "\x1B[49m", text); +} +//#endregion +export { bgCyanBright }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgGreen.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgGreen.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..4c19110d738a9a28a8749dc977c470d1ba63bdcd --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgGreen.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/bgGreen.d.ts +/** + * Green background. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bgGreen('hello')); + */ +declare function bgGreen(text: string): string; +//#endregion +export { bgGreen }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgGreen.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgGreen.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4c19110d738a9a28a8749dc977c470d1ba63bdcd --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgGreen.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/bgGreen.d.ts +/** + * Green background. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bgGreen('hello')); + */ +declare function bgGreen(text: string): string; +//#endregion +export { bgGreen }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgGreen.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgGreen.js new file mode 100644 index 0000000000000000000000000000000000000000..265f7c9c3944e9ac582f5fd710cf99bd0c18e862 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgGreen.js @@ -0,0 +1,18 @@ +const require_wrapAnsiBg = require("./_internal/wrapAnsiBg.js"); +//#region src/server/colors/bgGreen.ts +/** +* Green background. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bgGreen('hello')); +*/ +function bgGreen(text) { + return require_wrapAnsiBg.wrapAnsiBg("\x1B[42m", "\x1B[49m", text); +} +//#endregion +exports.bgGreen = bgGreen; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgGreen.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgGreen.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2fd0da18c4f6364aaea7cec5ef7c92884bc4e7c8 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgGreen.mjs @@ -0,0 +1,18 @@ +import { wrapAnsiBg } from "./_internal/wrapAnsiBg.mjs"; +//#region src/server/colors/bgGreen.ts +/** +* Green background. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bgGreen('hello')); +*/ +function bgGreen(text) { + return wrapAnsiBg("\x1B[42m", "\x1B[49m", text); +} +//#endregion +export { bgGreen }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgGreenBright.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgGreenBright.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..edb68e310e3dafb30ba53d0d6249019bcc184869 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgGreenBright.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/bgGreenBright.d.ts +/** + * Bright green background. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bgGreenBright('hello')); + */ +declare function bgGreenBright(text: string): string; +//#endregion +export { bgGreenBright }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgGreenBright.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgGreenBright.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..edb68e310e3dafb30ba53d0d6249019bcc184869 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgGreenBright.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/bgGreenBright.d.ts +/** + * Bright green background. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bgGreenBright('hello')); + */ +declare function bgGreenBright(text: string): string; +//#endregion +export { bgGreenBright }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgGreenBright.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgGreenBright.js new file mode 100644 index 0000000000000000000000000000000000000000..d9b7cdae2b7efbb09656899542b0ccd3f02f311c --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgGreenBright.js @@ -0,0 +1,18 @@ +const require_wrapAnsiBg = require("./_internal/wrapAnsiBg.js"); +//#region src/server/colors/bgGreenBright.ts +/** +* Bright green background. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bgGreenBright('hello')); +*/ +function bgGreenBright(text) { + return require_wrapAnsiBg.wrapAnsiBg("\x1B[102m", "\x1B[49m", text); +} +//#endregion +exports.bgGreenBright = bgGreenBright; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgGreenBright.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgGreenBright.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6a8e49201b52bb3886a6f08da45e79a7543f6f2d --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgGreenBright.mjs @@ -0,0 +1,18 @@ +import { wrapAnsiBg } from "./_internal/wrapAnsiBg.mjs"; +//#region src/server/colors/bgGreenBright.ts +/** +* Bright green background. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bgGreenBright('hello')); +*/ +function bgGreenBright(text) { + return wrapAnsiBg("\x1B[102m", "\x1B[49m", text); +} +//#endregion +export { bgGreenBright }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgHex.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgHex.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..e90e63409e280f3873d41cd0378f217185beb765 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgHex.d.mts @@ -0,0 +1,18 @@ +import { ColorFunction } from "./types.mjs"; + +//#region src/server/colors/bgHex.d.ts +/** + * Returns a function that wraps text with a 24-bit background color parsed from a hex string. + * Accepts `#RGB`, `#RRGGBB`, or the same without `#`. + * + * @param color - A hex color string (e.g. `"#ff6347"`, `"#f00"`). + * @returns A color function that wraps text with the parsed RGB background. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bgHex('#ff6347')('hello')); + */ +declare function bgHex(color: string): ColorFunction; +//#endregion +export { bgHex }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgHex.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgHex.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5e4cb523efa3345fdc53c4fc63c83e3f77c595d3 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgHex.d.ts @@ -0,0 +1,18 @@ +import { ColorFunction } from "./types.js"; + +//#region src/server/colors/bgHex.d.ts +/** + * Returns a function that wraps text with a 24-bit background color parsed from a hex string. + * Accepts `#RGB`, `#RRGGBB`, or the same without `#`. + * + * @param color - A hex color string (e.g. `"#ff6347"`, `"#f00"`). + * @returns A color function that wraps text with the parsed RGB background. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bgHex('#ff6347')('hello')); + */ +declare function bgHex(color: string): ColorFunction; +//#endregion +export { bgHex }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgHex.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgHex.js new file mode 100644 index 0000000000000000000000000000000000000000..c209265f3026f75b87168e8df45d0e13d2035c43 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgHex.js @@ -0,0 +1,21 @@ +const require_wrapAnsiBg = require("./_internal/wrapAnsiBg.js"); +const require_parseHex = require("./_internal/parseHex.js"); +//#region src/server/colors/bgHex.ts +/** +* Returns a function that wraps text with a 24-bit background color parsed from a hex string. +* Accepts `#RGB`, `#RRGGBB`, or the same without `#`. +* +* @param color - A hex color string (e.g. `"#ff6347"`, `"#f00"`). +* @returns A color function that wraps text with the parsed RGB background. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bgHex('#ff6347')('hello')); +*/ +function bgHex(color) { + const [r, g, b] = require_parseHex.parseHex(color); + return (text) => require_wrapAnsiBg.wrapAnsiBg(`\x1b[48;2;${r};${g};${b}m`, "\x1B[49m", text); +} +//#endregion +exports.bgHex = bgHex; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgHex.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgHex.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4f14257a2817487c5f374e8eb58aa97b57c1ce4b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgHex.mjs @@ -0,0 +1,21 @@ +import { wrapAnsiBg } from "./_internal/wrapAnsiBg.mjs"; +import { parseHex } from "./_internal/parseHex.mjs"; +//#region src/server/colors/bgHex.ts +/** +* Returns a function that wraps text with a 24-bit background color parsed from a hex string. +* Accepts `#RGB`, `#RRGGBB`, or the same without `#`. +* +* @param color - A hex color string (e.g. `"#ff6347"`, `"#f00"`). +* @returns A color function that wraps text with the parsed RGB background. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bgHex('#ff6347')('hello')); +*/ +function bgHex(color) { + const [r, g, b] = parseHex(color); + return (text) => wrapAnsiBg(`\x1b[48;2;${r};${g};${b}m`, "\x1B[49m", text); +} +//#endregion +export { bgHex }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgMagenta.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgMagenta.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..6bbabca8598b242d7441495b46082d55e5b424d5 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgMagenta.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/bgMagenta.d.ts +/** + * Magenta background. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bgMagenta('hello')); + */ +declare function bgMagenta(text: string): string; +//#endregion +export { bgMagenta }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgMagenta.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgMagenta.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6bbabca8598b242d7441495b46082d55e5b424d5 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgMagenta.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/bgMagenta.d.ts +/** + * Magenta background. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bgMagenta('hello')); + */ +declare function bgMagenta(text: string): string; +//#endregion +export { bgMagenta }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgMagenta.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgMagenta.js new file mode 100644 index 0000000000000000000000000000000000000000..47ab5ff4b57395ddab4630fc3694c2bfca48b933 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgMagenta.js @@ -0,0 +1,18 @@ +const require_wrapAnsiBg = require("./_internal/wrapAnsiBg.js"); +//#region src/server/colors/bgMagenta.ts +/** +* Magenta background. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bgMagenta('hello')); +*/ +function bgMagenta(text) { + return require_wrapAnsiBg.wrapAnsiBg("\x1B[45m", "\x1B[49m", text); +} +//#endregion +exports.bgMagenta = bgMagenta; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgMagenta.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgMagenta.mjs new file mode 100644 index 0000000000000000000000000000000000000000..876f98feb025cfc4c855a20176f681883a1fb245 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgMagenta.mjs @@ -0,0 +1,18 @@ +import { wrapAnsiBg } from "./_internal/wrapAnsiBg.mjs"; +//#region src/server/colors/bgMagenta.ts +/** +* Magenta background. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bgMagenta('hello')); +*/ +function bgMagenta(text) { + return wrapAnsiBg("\x1B[45m", "\x1B[49m", text); +} +//#endregion +export { bgMagenta }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgMagentaBright.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgMagentaBright.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..a8cb9910658092792324550a7c58159033ee1b5b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgMagentaBright.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/bgMagentaBright.d.ts +/** + * Bright magenta background. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bgMagentaBright('hello')); + */ +declare function bgMagentaBright(text: string): string; +//#endregion +export { bgMagentaBright }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgMagentaBright.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgMagentaBright.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a8cb9910658092792324550a7c58159033ee1b5b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgMagentaBright.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/bgMagentaBright.d.ts +/** + * Bright magenta background. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bgMagentaBright('hello')); + */ +declare function bgMagentaBright(text: string): string; +//#endregion +export { bgMagentaBright }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgMagentaBright.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgMagentaBright.js new file mode 100644 index 0000000000000000000000000000000000000000..655834b15e10efa3cdc58c937ef82f82bc6cd398 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgMagentaBright.js @@ -0,0 +1,18 @@ +const require_wrapAnsiBg = require("./_internal/wrapAnsiBg.js"); +//#region src/server/colors/bgMagentaBright.ts +/** +* Bright magenta background. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bgMagentaBright('hello')); +*/ +function bgMagentaBright(text) { + return require_wrapAnsiBg.wrapAnsiBg("\x1B[105m", "\x1B[49m", text); +} +//#endregion +exports.bgMagentaBright = bgMagentaBright; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgMagentaBright.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgMagentaBright.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c8bff2e26d93f0bb14bee0282631443c1902ea24 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgMagentaBright.mjs @@ -0,0 +1,18 @@ +import { wrapAnsiBg } from "./_internal/wrapAnsiBg.mjs"; +//#region src/server/colors/bgMagentaBright.ts +/** +* Bright magenta background. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bgMagentaBright('hello')); +*/ +function bgMagentaBright(text) { + return wrapAnsiBg("\x1B[105m", "\x1B[49m", text); +} +//#endregion +export { bgMagentaBright }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRed.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRed.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..78a2dd7a22cc17a47122675f580261d43f004cef --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRed.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/bgRed.d.ts +/** + * Red background. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bgRed('hello')); + */ +declare function bgRed(text: string): string; +//#endregion +export { bgRed }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRed.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRed.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..78a2dd7a22cc17a47122675f580261d43f004cef --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRed.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/bgRed.d.ts +/** + * Red background. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bgRed('hello')); + */ +declare function bgRed(text: string): string; +//#endregion +export { bgRed }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRed.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRed.js new file mode 100644 index 0000000000000000000000000000000000000000..54450c3ce6615cfd053736d6b221578eb63f7be0 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRed.js @@ -0,0 +1,18 @@ +const require_wrapAnsiBg = require("./_internal/wrapAnsiBg.js"); +//#region src/server/colors/bgRed.ts +/** +* Red background. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bgRed('hello')); +*/ +function bgRed(text) { + return require_wrapAnsiBg.wrapAnsiBg("\x1B[41m", "\x1B[49m", text); +} +//#endregion +exports.bgRed = bgRed; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRed.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRed.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5a05aa9ace0b94c5fefc05182833e424c27b3589 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRed.mjs @@ -0,0 +1,18 @@ +import { wrapAnsiBg } from "./_internal/wrapAnsiBg.mjs"; +//#region src/server/colors/bgRed.ts +/** +* Red background. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bgRed('hello')); +*/ +function bgRed(text) { + return wrapAnsiBg("\x1B[41m", "\x1B[49m", text); +} +//#endregion +export { bgRed }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRedBright.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRedBright.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..bf6ff14b570c759084a4aca6b652b8debdec6651 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRedBright.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/bgRedBright.d.ts +/** + * Bright red background. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bgRedBright('hello')); + */ +declare function bgRedBright(text: string): string; +//#endregion +export { bgRedBright }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRedBright.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRedBright.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bf6ff14b570c759084a4aca6b652b8debdec6651 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRedBright.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/bgRedBright.d.ts +/** + * Bright red background. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bgRedBright('hello')); + */ +declare function bgRedBright(text: string): string; +//#endregion +export { bgRedBright }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRedBright.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRedBright.js new file mode 100644 index 0000000000000000000000000000000000000000..ac35f163d275917c7ec4a9270128da4eb4da1a7b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRedBright.js @@ -0,0 +1,18 @@ +const require_wrapAnsiBg = require("./_internal/wrapAnsiBg.js"); +//#region src/server/colors/bgRedBright.ts +/** +* Bright red background. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bgRedBright('hello')); +*/ +function bgRedBright(text) { + return require_wrapAnsiBg.wrapAnsiBg("\x1B[101m", "\x1B[49m", text); +} +//#endregion +exports.bgRedBright = bgRedBright; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRedBright.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRedBright.mjs new file mode 100644 index 0000000000000000000000000000000000000000..27e9ef8108e7770a16685caad41477d3bc470376 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRedBright.mjs @@ -0,0 +1,18 @@ +import { wrapAnsiBg } from "./_internal/wrapAnsiBg.mjs"; +//#region src/server/colors/bgRedBright.ts +/** +* Bright red background. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bgRedBright('hello')); +*/ +function bgRedBright(text) { + return wrapAnsiBg("\x1B[101m", "\x1B[49m", text); +} +//#endregion +export { bgRedBright }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRgb.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRgb.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..85b23e5b0890384a982971b6def3c1a09e59606b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRgb.d.mts @@ -0,0 +1,20 @@ +import { ColorFunction } from "./types.mjs"; + +//#region src/server/colors/bgRgb.d.ts +/** + * Returns a function that wraps text with the given 24-bit (truecolor) background. + * + * @param r - Red component (0–255). + * @param g - Green component (0–255). + * @param b - Blue component (0–255). + * @returns A color function that wraps text with the chosen RGB background. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * const highlight = colors.bgRgb(255, 99, 71); + * console.log(highlight('hello')); + */ +declare function bgRgb(r: number, g: number, b: number): ColorFunction; +//#endregion +export { bgRgb }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRgb.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRgb.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..92ddd2fc021d418296e922762c9ccbbf5dca31c5 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRgb.d.ts @@ -0,0 +1,20 @@ +import { ColorFunction } from "./types.js"; + +//#region src/server/colors/bgRgb.d.ts +/** + * Returns a function that wraps text with the given 24-bit (truecolor) background. + * + * @param r - Red component (0–255). + * @param g - Green component (0–255). + * @param b - Blue component (0–255). + * @returns A color function that wraps text with the chosen RGB background. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * const highlight = colors.bgRgb(255, 99, 71); + * console.log(highlight('hello')); + */ +declare function bgRgb(r: number, g: number, b: number): ColorFunction; +//#endregion +export { bgRgb }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRgb.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRgb.js new file mode 100644 index 0000000000000000000000000000000000000000..853086eb59070284fe3478d109089a45a088b978 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRgb.js @@ -0,0 +1,21 @@ +const require_wrapAnsiBg = require("./_internal/wrapAnsiBg.js"); +//#region src/server/colors/bgRgb.ts +/** +* Returns a function that wraps text with the given 24-bit (truecolor) background. +* +* @param r - Red component (0–255). +* @param g - Green component (0–255). +* @param b - Blue component (0–255). +* @returns A color function that wraps text with the chosen RGB background. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* const highlight = colors.bgRgb(255, 99, 71); +* console.log(highlight('hello')); +*/ +function bgRgb(r, g, b) { + return (text) => require_wrapAnsiBg.wrapAnsiBg(`\x1b[48;2;${r};${g};${b}m`, "\x1B[49m", text); +} +//#endregion +exports.bgRgb = bgRgb; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRgb.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRgb.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1c6dc17b6ab43b223a64e781a2b8d16f8fdb19b0 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgRgb.mjs @@ -0,0 +1,21 @@ +import { wrapAnsiBg } from "./_internal/wrapAnsiBg.mjs"; +//#region src/server/colors/bgRgb.ts +/** +* Returns a function that wraps text with the given 24-bit (truecolor) background. +* +* @param r - Red component (0–255). +* @param g - Green component (0–255). +* @param b - Blue component (0–255). +* @returns A color function that wraps text with the chosen RGB background. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* const highlight = colors.bgRgb(255, 99, 71); +* console.log(highlight('hello')); +*/ +function bgRgb(r, g, b) { + return (text) => wrapAnsiBg(`\x1b[48;2;${r};${g};${b}m`, "\x1B[49m", text); +} +//#endregion +export { bgRgb }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgWhite.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgWhite.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..6542892645a1380af8b4af9efb928f619dd7e36e --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgWhite.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/bgWhite.d.ts +/** + * White background. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bgWhite('hello')); + */ +declare function bgWhite(text: string): string; +//#endregion +export { bgWhite }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgWhite.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgWhite.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6542892645a1380af8b4af9efb928f619dd7e36e --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgWhite.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/bgWhite.d.ts +/** + * White background. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bgWhite('hello')); + */ +declare function bgWhite(text: string): string; +//#endregion +export { bgWhite }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgWhite.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgWhite.js new file mode 100644 index 0000000000000000000000000000000000000000..1028bd622daa6daf7a1b78925f713084a5a6dced --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgWhite.js @@ -0,0 +1,18 @@ +const require_wrapAnsiBg = require("./_internal/wrapAnsiBg.js"); +//#region src/server/colors/bgWhite.ts +/** +* White background. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bgWhite('hello')); +*/ +function bgWhite(text) { + return require_wrapAnsiBg.wrapAnsiBg("\x1B[47m", "\x1B[49m", text); +} +//#endregion +exports.bgWhite = bgWhite; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgWhite.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgWhite.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8371e6e91ed8aa14e3885b6cde560d28219ac16f --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgWhite.mjs @@ -0,0 +1,18 @@ +import { wrapAnsiBg } from "./_internal/wrapAnsiBg.mjs"; +//#region src/server/colors/bgWhite.ts +/** +* White background. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bgWhite('hello')); +*/ +function bgWhite(text) { + return wrapAnsiBg("\x1B[47m", "\x1B[49m", text); +} +//#endregion +export { bgWhite }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgWhiteBright.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgWhiteBright.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..60f37b2ded2aa1d8f9404f1f05fe470d64738044 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgWhiteBright.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/bgWhiteBright.d.ts +/** + * Bright white background. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bgWhiteBright('hello')); + */ +declare function bgWhiteBright(text: string): string; +//#endregion +export { bgWhiteBright }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgWhiteBright.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgWhiteBright.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..60f37b2ded2aa1d8f9404f1f05fe470d64738044 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgWhiteBright.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/bgWhiteBright.d.ts +/** + * Bright white background. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bgWhiteBright('hello')); + */ +declare function bgWhiteBright(text: string): string; +//#endregion +export { bgWhiteBright }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgWhiteBright.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgWhiteBright.js new file mode 100644 index 0000000000000000000000000000000000000000..652820263e2b70cb30bd656303eeb1a25d4814bd --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgWhiteBright.js @@ -0,0 +1,18 @@ +const require_wrapAnsiBg = require("./_internal/wrapAnsiBg.js"); +//#region src/server/colors/bgWhiteBright.ts +/** +* Bright white background. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bgWhiteBright('hello')); +*/ +function bgWhiteBright(text) { + return require_wrapAnsiBg.wrapAnsiBg("\x1B[107m", "\x1B[49m", text); +} +//#endregion +exports.bgWhiteBright = bgWhiteBright; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgWhiteBright.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgWhiteBright.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5cc2ab1ff92fe2dee6d4f0534613ccc002e6ccba --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgWhiteBright.mjs @@ -0,0 +1,18 @@ +import { wrapAnsiBg } from "./_internal/wrapAnsiBg.mjs"; +//#region src/server/colors/bgWhiteBright.ts +/** +* Bright white background. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bgWhiteBright('hello')); +*/ +function bgWhiteBright(text) { + return wrapAnsiBg("\x1B[107m", "\x1B[49m", text); +} +//#endregion +export { bgWhiteBright }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgYellow.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgYellow.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..1d91f3f608748fce025b71877d82681aecbcaeda --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgYellow.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/bgYellow.d.ts +/** + * Yellow background. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bgYellow('hello')); + */ +declare function bgYellow(text: string): string; +//#endregion +export { bgYellow }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgYellow.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgYellow.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1d91f3f608748fce025b71877d82681aecbcaeda --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgYellow.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/bgYellow.d.ts +/** + * Yellow background. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bgYellow('hello')); + */ +declare function bgYellow(text: string): string; +//#endregion +export { bgYellow }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgYellow.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgYellow.js new file mode 100644 index 0000000000000000000000000000000000000000..6a84d8c6aaf11f4d316442e291ef44caf36a24e6 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgYellow.js @@ -0,0 +1,18 @@ +const require_wrapAnsiBg = require("./_internal/wrapAnsiBg.js"); +//#region src/server/colors/bgYellow.ts +/** +* Yellow background. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bgYellow('hello')); +*/ +function bgYellow(text) { + return require_wrapAnsiBg.wrapAnsiBg("\x1B[43m", "\x1B[49m", text); +} +//#endregion +exports.bgYellow = bgYellow; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgYellow.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgYellow.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2ffb6c2665f1cfeab7855a8cac16e0725fefaea3 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgYellow.mjs @@ -0,0 +1,18 @@ +import { wrapAnsiBg } from "./_internal/wrapAnsiBg.mjs"; +//#region src/server/colors/bgYellow.ts +/** +* Yellow background. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bgYellow('hello')); +*/ +function bgYellow(text) { + return wrapAnsiBg("\x1B[43m", "\x1B[49m", text); +} +//#endregion +export { bgYellow }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgYellowBright.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgYellowBright.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..d08f6792996d04ca9579521b7040602535d95619 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgYellowBright.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/bgYellowBright.d.ts +/** + * Bright yellow background. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bgYellowBright('hello')); + */ +declare function bgYellowBright(text: string): string; +//#endregion +export { bgYellowBright }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgYellowBright.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgYellowBright.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d08f6792996d04ca9579521b7040602535d95619 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgYellowBright.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/bgYellowBright.d.ts +/** + * Bright yellow background. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bgYellowBright('hello')); + */ +declare function bgYellowBright(text: string): string; +//#endregion +export { bgYellowBright }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgYellowBright.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgYellowBright.js new file mode 100644 index 0000000000000000000000000000000000000000..334c2743d76b41001300eb7e4b0ac8f209b4c079 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgYellowBright.js @@ -0,0 +1,18 @@ +const require_wrapAnsiBg = require("./_internal/wrapAnsiBg.js"); +//#region src/server/colors/bgYellowBright.ts +/** +* Bright yellow background. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bgYellowBright('hello')); +*/ +function bgYellowBright(text) { + return require_wrapAnsiBg.wrapAnsiBg("\x1B[103m", "\x1B[49m", text); +} +//#endregion +exports.bgYellowBright = bgYellowBright; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bgYellowBright.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgYellowBright.mjs new file mode 100644 index 0000000000000000000000000000000000000000..78c77aee750834716bd19483a28dc0ac52a09b03 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bgYellowBright.mjs @@ -0,0 +1,18 @@ +import { wrapAnsiBg } from "./_internal/wrapAnsiBg.mjs"; +//#region src/server/colors/bgYellowBright.ts +/** +* Bright yellow background. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bgYellowBright('hello')); +*/ +function bgYellowBright(text) { + return wrapAnsiBg("\x1B[103m", "\x1B[49m", text); +} +//#endregion +export { bgYellowBright }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/black.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/black.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..1b03a3f69c5bdee30aab1013a743bb45126585ac --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/black.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/black.d.ts +/** + * Black foreground. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.black('hello')); + */ +declare function black(text: string): string; +//#endregion +export { black }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/black.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/black.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1b03a3f69c5bdee30aab1013a743bb45126585ac --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/black.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/black.d.ts +/** + * Black foreground. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.black('hello')); + */ +declare function black(text: string): string; +//#endregion +export { black }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/black.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/black.js new file mode 100644 index 0000000000000000000000000000000000000000..697a8447919f15a87e2372c1f4de86ea9d4b3345 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/black.js @@ -0,0 +1,18 @@ +const require_wrapAnsi = require("./_internal/wrapAnsi.js"); +//#region src/server/colors/black.ts +/** +* Black foreground. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.black('hello')); +*/ +function black(text) { + return require_wrapAnsi.wrapAnsi("\x1B[30m", "\x1B[39m", text); +} +//#endregion +exports.black = black; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/black.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/black.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7265507e523089b22de949ef15c338a25beb1c82 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/black.mjs @@ -0,0 +1,18 @@ +import { wrapAnsi } from "./_internal/wrapAnsi.mjs"; +//#region src/server/colors/black.ts +/** +* Black foreground. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.black('hello')); +*/ +function black(text) { + return wrapAnsi("\x1B[30m", "\x1B[39m", text); +} +//#endregion +export { black }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/blackBright.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/blackBright.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..76560617d7002322bce86a894306ad3d02635bd7 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/blackBright.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/blackBright.d.ts +/** + * Bright black (gray) foreground. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.blackBright('hello')); + */ +declare function blackBright(text: string): string; +//#endregion +export { blackBright }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/blackBright.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/blackBright.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..76560617d7002322bce86a894306ad3d02635bd7 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/blackBright.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/blackBright.d.ts +/** + * Bright black (gray) foreground. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.blackBright('hello')); + */ +declare function blackBright(text: string): string; +//#endregion +export { blackBright }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/blackBright.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/blackBright.js new file mode 100644 index 0000000000000000000000000000000000000000..2f1b244e02ababa5f2e6487c4d471f51796f2d63 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/blackBright.js @@ -0,0 +1,18 @@ +const require_wrapAnsi = require("./_internal/wrapAnsi.js"); +//#region src/server/colors/blackBright.ts +/** +* Bright black (gray) foreground. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.blackBright('hello')); +*/ +function blackBright(text) { + return require_wrapAnsi.wrapAnsi("\x1B[90m", "\x1B[39m", text); +} +//#endregion +exports.blackBright = blackBright; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/blackBright.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/blackBright.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6f97b28e4e193f00415a95a4f1cdbba31aed9fba --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/blackBright.mjs @@ -0,0 +1,18 @@ +import { wrapAnsi } from "./_internal/wrapAnsi.mjs"; +//#region src/server/colors/blackBright.ts +/** +* Bright black (gray) foreground. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.blackBright('hello')); +*/ +function blackBright(text) { + return wrapAnsi("\x1B[90m", "\x1B[39m", text); +} +//#endregion +export { blackBright }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/blue.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/blue.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..c5b1588e12df32412275c61daccbb1d2920d97bc --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/blue.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/blue.d.ts +/** + * Blue foreground. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.blue('hello')); + */ +declare function blue(text: string): string; +//#endregion +export { blue }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/blue.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/blue.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c5b1588e12df32412275c61daccbb1d2920d97bc --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/blue.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/blue.d.ts +/** + * Blue foreground. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.blue('hello')); + */ +declare function blue(text: string): string; +//#endregion +export { blue }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/blue.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/blue.js new file mode 100644 index 0000000000000000000000000000000000000000..aea6d179f8e1a2aa86e2906fea2a74bd2321dc1b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/blue.js @@ -0,0 +1,18 @@ +const require_wrapAnsi = require("./_internal/wrapAnsi.js"); +//#region src/server/colors/blue.ts +/** +* Blue foreground. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.blue('hello')); +*/ +function blue(text) { + return require_wrapAnsi.wrapAnsi("\x1B[34m", "\x1B[39m", text); +} +//#endregion +exports.blue = blue; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/blue.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/blue.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e480fdd32eedb875139104dfb1fcc422ae82064f --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/blue.mjs @@ -0,0 +1,18 @@ +import { wrapAnsi } from "./_internal/wrapAnsi.mjs"; +//#region src/server/colors/blue.ts +/** +* Blue foreground. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.blue('hello')); +*/ +function blue(text) { + return wrapAnsi("\x1B[34m", "\x1B[39m", text); +} +//#endregion +export { blue }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/blueBright.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/blueBright.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..e3e9538aa29b5e9d69016945411d08e2097d7d90 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/blueBright.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/blueBright.d.ts +/** + * Bright blue foreground. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.blueBright('hello')); + */ +declare function blueBright(text: string): string; +//#endregion +export { blueBright }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/blueBright.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/blueBright.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e3e9538aa29b5e9d69016945411d08e2097d7d90 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/blueBright.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/blueBright.d.ts +/** + * Bright blue foreground. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.blueBright('hello')); + */ +declare function blueBright(text: string): string; +//#endregion +export { blueBright }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/blueBright.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/blueBright.js new file mode 100644 index 0000000000000000000000000000000000000000..f9d8ac3a2747c430053d6c42476c700290f7d119 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/blueBright.js @@ -0,0 +1,18 @@ +const require_wrapAnsi = require("./_internal/wrapAnsi.js"); +//#region src/server/colors/blueBright.ts +/** +* Bright blue foreground. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.blueBright('hello')); +*/ +function blueBright(text) { + return require_wrapAnsi.wrapAnsi("\x1B[94m", "\x1B[39m", text); +} +//#endregion +exports.blueBright = blueBright; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/blueBright.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/blueBright.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7f69dd293bef5a559c45a0151f16ae10bf20b39f --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/blueBright.mjs @@ -0,0 +1,18 @@ +import { wrapAnsi } from "./_internal/wrapAnsi.mjs"; +//#region src/server/colors/blueBright.ts +/** +* Bright blue foreground. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.blueBright('hello')); +*/ +function blueBright(text) { + return wrapAnsi("\x1B[94m", "\x1B[39m", text); +} +//#endregion +export { blueBright }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bold.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bold.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..70652a7f93151c461c9bdc60e6ba859595550865 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bold.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/bold.d.ts +/** + * Bold text. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bold('hello')); + */ +declare function bold(text: string): string; +//#endregion +export { bold }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bold.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/bold.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..70652a7f93151c461c9bdc60e6ba859595550865 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bold.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/bold.d.ts +/** + * Bold text. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.bold('hello')); + */ +declare function bold(text: string): string; +//#endregion +export { bold }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bold.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/bold.js new file mode 100644 index 0000000000000000000000000000000000000000..f16e29b61058367306c0690f41576ea6d4f0ba82 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bold.js @@ -0,0 +1,18 @@ +const require_wrapAnsi = require("./_internal/wrapAnsi.js"); +//#region src/server/colors/bold.ts +/** +* Bold text. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bold('hello')); +*/ +function bold(text) { + return require_wrapAnsi.wrapAnsi("\x1B[1m", "\x1B[22m", text); +} +//#endregion +exports.bold = bold; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/bold.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/bold.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3c89815ccfa8ccbec2765c4f70a87ef47e54ff25 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/bold.mjs @@ -0,0 +1,18 @@ +import { wrapAnsi } from "./_internal/wrapAnsi.mjs"; +//#region src/server/colors/bold.ts +/** +* Bold text. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.bold('hello')); +*/ +function bold(text) { + return wrapAnsi("\x1B[1m", "\x1B[22m", text); +} +//#endregion +export { bold }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/cyan.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/cyan.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..c9b61ad637ddda4ba1346517317775b4a23cd28d --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/cyan.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/cyan.d.ts +/** + * Cyan foreground. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.cyan('hello')); + */ +declare function cyan(text: string): string; +//#endregion +export { cyan }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/cyan.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/cyan.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c9b61ad637ddda4ba1346517317775b4a23cd28d --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/cyan.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/cyan.d.ts +/** + * Cyan foreground. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.cyan('hello')); + */ +declare function cyan(text: string): string; +//#endregion +export { cyan }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/cyan.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/cyan.js new file mode 100644 index 0000000000000000000000000000000000000000..1b67e4afe04cc9848ae711cce26eb6a5f247f6ec --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/cyan.js @@ -0,0 +1,18 @@ +const require_wrapAnsi = require("./_internal/wrapAnsi.js"); +//#region src/server/colors/cyan.ts +/** +* Cyan foreground. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.cyan('hello')); +*/ +function cyan(text) { + return require_wrapAnsi.wrapAnsi("\x1B[36m", "\x1B[39m", text); +} +//#endregion +exports.cyan = cyan; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/cyan.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/cyan.mjs new file mode 100644 index 0000000000000000000000000000000000000000..212cdd30d85c9b468e9913539009d73448e0a943 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/cyan.mjs @@ -0,0 +1,18 @@ +import { wrapAnsi } from "./_internal/wrapAnsi.mjs"; +//#region src/server/colors/cyan.ts +/** +* Cyan foreground. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.cyan('hello')); +*/ +function cyan(text) { + return wrapAnsi("\x1B[36m", "\x1B[39m", text); +} +//#endregion +export { cyan }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/cyanBright.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/cyanBright.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..fcba8369bd8a73bd27cbf9fefcb458bbefc5c1e3 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/cyanBright.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/cyanBright.d.ts +/** + * Bright cyan foreground. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.cyanBright('hello')); + */ +declare function cyanBright(text: string): string; +//#endregion +export { cyanBright }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/cyanBright.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/cyanBright.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fcba8369bd8a73bd27cbf9fefcb458bbefc5c1e3 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/cyanBright.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/cyanBright.d.ts +/** + * Bright cyan foreground. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.cyanBright('hello')); + */ +declare function cyanBright(text: string): string; +//#endregion +export { cyanBright }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/cyanBright.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/cyanBright.js new file mode 100644 index 0000000000000000000000000000000000000000..4db3fa717c78688d3322df80a088be1810b0d6ea --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/cyanBright.js @@ -0,0 +1,18 @@ +const require_wrapAnsi = require("./_internal/wrapAnsi.js"); +//#region src/server/colors/cyanBright.ts +/** +* Bright cyan foreground. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.cyanBright('hello')); +*/ +function cyanBright(text) { + return require_wrapAnsi.wrapAnsi("\x1B[96m", "\x1B[39m", text); +} +//#endregion +exports.cyanBright = cyanBright; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/cyanBright.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/cyanBright.mjs new file mode 100644 index 0000000000000000000000000000000000000000..227c154726a8e0c782abf0fda498ead2a444e1d0 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/cyanBright.mjs @@ -0,0 +1,18 @@ +import { wrapAnsi } from "./_internal/wrapAnsi.mjs"; +//#region src/server/colors/cyanBright.ts +/** +* Bright cyan foreground. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.cyanBright('hello')); +*/ +function cyanBright(text) { + return wrapAnsi("\x1B[96m", "\x1B[39m", text); +} +//#endregion +export { cyanBright }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/dim.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/dim.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..1f8d0687cb456865baf889a9e080018be32eba54 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/dim.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/dim.d.ts +/** + * Dim (faint) text. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.dim('hello')); + */ +declare function dim(text: string): string; +//#endregion +export { dim }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/dim.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/dim.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1f8d0687cb456865baf889a9e080018be32eba54 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/dim.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/dim.d.ts +/** + * Dim (faint) text. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.dim('hello')); + */ +declare function dim(text: string): string; +//#endregion +export { dim }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/dim.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/dim.js new file mode 100644 index 0000000000000000000000000000000000000000..f9ee7d6904b510bbf3824cd8ad0578fea473118a --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/dim.js @@ -0,0 +1,18 @@ +const require_wrapAnsi = require("./_internal/wrapAnsi.js"); +//#region src/server/colors/dim.ts +/** +* Dim (faint) text. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.dim('hello')); +*/ +function dim(text) { + return require_wrapAnsi.wrapAnsi("\x1B[2m", "\x1B[22m", text); +} +//#endregion +exports.dim = dim; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/dim.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/dim.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ee9a5abaefb019612d617ff6e8f2ddb33b991178 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/dim.mjs @@ -0,0 +1,18 @@ +import { wrapAnsi } from "./_internal/wrapAnsi.mjs"; +//#region src/server/colors/dim.ts +/** +* Dim (faint) text. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.dim('hello')); +*/ +function dim(text) { + return wrapAnsi("\x1B[2m", "\x1B[22m", text); +} +//#endregion +export { dim }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/gray.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/gray.js new file mode 100644 index 0000000000000000000000000000000000000000..c75aef87111a6e2ff3628268b65426e7cf2a29b3 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/gray.js @@ -0,0 +1,18 @@ +//#region src/server/colors/gray.ts +/** +* Gray foreground — alias of `blackBright`. Wraps text with ANSI codes. +* +* "Gray" and "bright black" map to the same SGR code (`\x1b[90m`); this export +* exists so callers can use the friendlier name. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.gray('muted')); +*/ +const gray = require("./blackBright.js").blackBright; +//#endregion +exports.gray = gray; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/gray.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/gray.mjs new file mode 100644 index 0000000000000000000000000000000000000000..fd1a9df0610e7543e7aefc4e4e3089ba480cfafa --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/gray.mjs @@ -0,0 +1,19 @@ +import { blackBright } from "./blackBright.mjs"; +//#region src/server/colors/gray.ts +/** +* Gray foreground — alias of `blackBright`. Wraps text with ANSI codes. +* +* "Gray" and "bright black" map to the same SGR code (`\x1b[90m`); this export +* exists so callers can use the friendlier name. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.gray('muted')); +*/ +const gray = blackBright; +//#endregion +export { gray }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/green.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/green.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..0745426a3a95517747b10975145dfda627f9a956 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/green.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/green.d.ts +/** + * Green foreground. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.green('hello')); + */ +declare function green(text: string): string; +//#endregion +export { green }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/green.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/green.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0745426a3a95517747b10975145dfda627f9a956 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/green.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/green.d.ts +/** + * Green foreground. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.green('hello')); + */ +declare function green(text: string): string; +//#endregion +export { green }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/green.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/green.js new file mode 100644 index 0000000000000000000000000000000000000000..c942ba93e66bdddfe27d88d50b3a530b968e9999 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/green.js @@ -0,0 +1,18 @@ +const require_wrapAnsi = require("./_internal/wrapAnsi.js"); +//#region src/server/colors/green.ts +/** +* Green foreground. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.green('hello')); +*/ +function green(text) { + return require_wrapAnsi.wrapAnsi("\x1B[32m", "\x1B[39m", text); +} +//#endregion +exports.green = green; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/green.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/green.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4cecea700533ed44b9858f92c1baee57aa7ee3ea --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/green.mjs @@ -0,0 +1,18 @@ +import { wrapAnsi } from "./_internal/wrapAnsi.mjs"; +//#region src/server/colors/green.ts +/** +* Green foreground. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.green('hello')); +*/ +function green(text) { + return wrapAnsi("\x1B[32m", "\x1B[39m", text); +} +//#endregion +export { green }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/greenBright.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/greenBright.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..0400726c71a4bbf2480d72e29cfcc57456a8fe2b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/greenBright.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/greenBright.d.ts +/** + * Bright green foreground. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.greenBright('hello')); + */ +declare function greenBright(text: string): string; +//#endregion +export { greenBright }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/greenBright.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/greenBright.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0400726c71a4bbf2480d72e29cfcc57456a8fe2b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/greenBright.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/greenBright.d.ts +/** + * Bright green foreground. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.greenBright('hello')); + */ +declare function greenBright(text: string): string; +//#endregion +export { greenBright }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/greenBright.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/greenBright.js new file mode 100644 index 0000000000000000000000000000000000000000..e6c0080ba30c63cb563727abfb26ec683e436935 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/greenBright.js @@ -0,0 +1,18 @@ +const require_wrapAnsi = require("./_internal/wrapAnsi.js"); +//#region src/server/colors/greenBright.ts +/** +* Bright green foreground. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.greenBright('hello')); +*/ +function greenBright(text) { + return require_wrapAnsi.wrapAnsi("\x1B[92m", "\x1B[39m", text); +} +//#endregion +exports.greenBright = greenBright; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/greenBright.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/greenBright.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7b2b76ab79a231a48f19b58a43f5f294559399a4 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/greenBright.mjs @@ -0,0 +1,18 @@ +import { wrapAnsi } from "./_internal/wrapAnsi.mjs"; +//#region src/server/colors/greenBright.ts +/** +* Bright green foreground. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.greenBright('hello')); +*/ +function greenBright(text) { + return wrapAnsi("\x1B[92m", "\x1B[39m", text); +} +//#endregion +export { greenBright }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/hex.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/hex.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..50268e4e0783cc0a42b17c25a5179acf2d81f7ba --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/hex.d.mts @@ -0,0 +1,18 @@ +import { ColorFunction } from "./types.mjs"; + +//#region src/server/colors/hex.d.ts +/** + * Returns a function that wraps text with a 24-bit foreground color parsed from a hex string. + * Accepts `#RGB`, `#RRGGBB`, or the same without `#`. + * + * @param color - A hex color string (e.g. `"#ff6347"`, `"#f00"`). + * @returns A color function that wraps text with the parsed RGB foreground. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.hex('#ff6347')('hello')); + */ +declare function hex(color: string): ColorFunction; +//#endregion +export { hex }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/hex.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/hex.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3b5eaa26db3f07cddaf1798deefe521ab88def58 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/hex.d.ts @@ -0,0 +1,18 @@ +import { ColorFunction } from "./types.js"; + +//#region src/server/colors/hex.d.ts +/** + * Returns a function that wraps text with a 24-bit foreground color parsed from a hex string. + * Accepts `#RGB`, `#RRGGBB`, or the same without `#`. + * + * @param color - A hex color string (e.g. `"#ff6347"`, `"#f00"`). + * @returns A color function that wraps text with the parsed RGB foreground. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.hex('#ff6347')('hello')); + */ +declare function hex(color: string): ColorFunction; +//#endregion +export { hex }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/hex.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/hex.js new file mode 100644 index 0000000000000000000000000000000000000000..980e28fa460f9208d5802b2ab47f95807499444e --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/hex.js @@ -0,0 +1,21 @@ +const require_wrapAnsi = require("./_internal/wrapAnsi.js"); +const require_parseHex = require("./_internal/parseHex.js"); +//#region src/server/colors/hex.ts +/** +* Returns a function that wraps text with a 24-bit foreground color parsed from a hex string. +* Accepts `#RGB`, `#RRGGBB`, or the same without `#`. +* +* @param color - A hex color string (e.g. `"#ff6347"`, `"#f00"`). +* @returns A color function that wraps text with the parsed RGB foreground. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.hex('#ff6347')('hello')); +*/ +function hex(color) { + const [r, g, b] = require_parseHex.parseHex(color); + return (text) => require_wrapAnsi.wrapAnsi(`\x1b[38;2;${r};${g};${b}m`, "\x1B[39m", text); +} +//#endregion +exports.hex = hex; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/hex.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/hex.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1d1103acc33ff8406e5297e09fd08ee44c8b162b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/hex.mjs @@ -0,0 +1,21 @@ +import { wrapAnsi } from "./_internal/wrapAnsi.mjs"; +import { parseHex } from "./_internal/parseHex.mjs"; +//#region src/server/colors/hex.ts +/** +* Returns a function that wraps text with a 24-bit foreground color parsed from a hex string. +* Accepts `#RGB`, `#RRGGBB`, or the same without `#`. +* +* @param color - A hex color string (e.g. `"#ff6347"`, `"#f00"`). +* @returns A color function that wraps text with the parsed RGB foreground. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.hex('#ff6347')('hello')); +*/ +function hex(color) { + const [r, g, b] = parseHex(color); + return (text) => wrapAnsi(`\x1b[38;2;${r};${g};${b}m`, "\x1B[39m", text); +} +//#endregion +export { hex }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/hidden.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/hidden.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..4ff3c3036001f4ed0f246c923eda96b993ac451b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/hidden.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/hidden.d.ts +/** + * Hides text from rendering while keeping it selectable. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.hidden('hello')); + */ +declare function hidden(text: string): string; +//#endregion +export { hidden }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/hidden.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/hidden.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4ff3c3036001f4ed0f246c923eda96b993ac451b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/hidden.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/hidden.d.ts +/** + * Hides text from rendering while keeping it selectable. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.hidden('hello')); + */ +declare function hidden(text: string): string; +//#endregion +export { hidden }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/hidden.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/hidden.js new file mode 100644 index 0000000000000000000000000000000000000000..acaad67dae2d7275d9f9e7c031b78ced0d9f6ed5 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/hidden.js @@ -0,0 +1,18 @@ +const require_wrapAnsi = require("./_internal/wrapAnsi.js"); +//#region src/server/colors/hidden.ts +/** +* Hides text from rendering while keeping it selectable. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.hidden('hello')); +*/ +function hidden(text) { + return require_wrapAnsi.wrapAnsi("\x1B[8m", "\x1B[28m", text); +} +//#endregion +exports.hidden = hidden; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/hidden.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/hidden.mjs new file mode 100644 index 0000000000000000000000000000000000000000..9103d4578979c37319550bf756c04da952448688 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/hidden.mjs @@ -0,0 +1,18 @@ +import { wrapAnsi } from "./_internal/wrapAnsi.mjs"; +//#region src/server/colors/hidden.ts +/** +* Hides text from rendering while keeping it selectable. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.hidden('hello')); +*/ +function hidden(text) { + return wrapAnsi("\x1B[8m", "\x1B[28m", text); +} +//#endregion +export { hidden }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/index.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..31368219ad3bf11a4115741af340c8422a39a4b1 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/index.d.mts @@ -0,0 +1,99 @@ +import { ansi256 } from "./ansi256.mjs"; +import { bgAnsi256 } from "./bgAnsi256.mjs"; +import { bgBlack } from "./bgBlack.mjs"; +import { bgBlackBright } from "./bgBlackBright.mjs"; +import { bgBlue } from "./bgBlue.mjs"; +import { bgBlueBright } from "./bgBlueBright.mjs"; +import { bgCyan } from "./bgCyan.mjs"; +import { bgCyanBright } from "./bgCyanBright.mjs"; +import { bgGreen } from "./bgGreen.mjs"; +import { bgGreenBright } from "./bgGreenBright.mjs"; +import { bgHex } from "./bgHex.mjs"; +import { bgMagenta } from "./bgMagenta.mjs"; +import { bgMagentaBright } from "./bgMagentaBright.mjs"; +import { bgRed } from "./bgRed.mjs"; +import { bgRedBright } from "./bgRedBright.mjs"; +import { bgRgb } from "./bgRgb.mjs"; +import { bgWhite } from "./bgWhite.mjs"; +import { bgWhiteBright } from "./bgWhiteBright.mjs"; +import { bgYellow } from "./bgYellow.mjs"; +import { bgYellowBright } from "./bgYellowBright.mjs"; +import { black } from "./black.mjs"; +import { blackBright } from "./blackBright.mjs"; +import { blue } from "./blue.mjs"; +import { blueBright } from "./blueBright.mjs"; +import { bold } from "./bold.mjs"; +import { cyan } from "./cyan.mjs"; +import { cyanBright } from "./cyanBright.mjs"; +import { dim } from "./dim.mjs"; +import { green } from "./green.mjs"; +import { greenBright } from "./greenBright.mjs"; +import { hex } from "./hex.mjs"; +import { hidden } from "./hidden.mjs"; +import { inverse } from "./inverse.mjs"; +import { italic } from "./italic.mjs"; +import { magenta } from "./magenta.mjs"; +import { magentaBright } from "./magentaBright.mjs"; +import { red } from "./red.mjs"; +import { redBright } from "./redBright.mjs"; +import { reset } from "./reset.mjs"; +import { rgb } from "./rgb.mjs"; +import { strikethrough } from "./strikethrough.mjs"; +import { underline } from "./underline.mjs"; +import { white } from "./white.mjs"; +import { whiteBright } from "./whiteBright.mjs"; +import { yellow } from "./yellow.mjs"; +import { yellowBright } from "./yellowBright.mjs"; + +//#region src/server/colors/index.d.ts +declare const colors: Readonly<{ + reset: typeof reset; + bold: typeof bold; + dim: typeof dim; + italic: typeof italic; + underline: typeof underline; + inverse: typeof inverse; + hidden: typeof hidden; + strikethrough: typeof strikethrough; + black: typeof black; + red: typeof red; + green: typeof green; + yellow: typeof yellow; + blue: typeof blue; + magenta: typeof magenta; + cyan: typeof cyan; + white: typeof white; + gray: typeof blackBright; + blackBright: typeof blackBright; + redBright: typeof redBright; + greenBright: typeof greenBright; + yellowBright: typeof yellowBright; + blueBright: typeof blueBright; + magentaBright: typeof magentaBright; + cyanBright: typeof cyanBright; + whiteBright: typeof whiteBright; + bgBlack: typeof bgBlack; + bgRed: typeof bgRed; + bgGreen: typeof bgGreen; + bgYellow: typeof bgYellow; + bgBlue: typeof bgBlue; + bgMagenta: typeof bgMagenta; + bgCyan: typeof bgCyan; + bgWhite: typeof bgWhite; + bgBlackBright: typeof bgBlackBright; + bgRedBright: typeof bgRedBright; + bgGreenBright: typeof bgGreenBright; + bgYellowBright: typeof bgYellowBright; + bgBlueBright: typeof bgBlueBright; + bgMagentaBright: typeof bgMagentaBright; + bgCyanBright: typeof bgCyanBright; + bgWhiteBright: typeof bgWhiteBright; + ansi256: typeof ansi256; + bgAnsi256: typeof bgAnsi256; + rgb: typeof rgb; + bgRgb: typeof bgRgb; + hex: typeof hex; + bgHex: typeof bgHex; +}>; +//#endregion +export { colors }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/index.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..049014fbbba91e921eccd2f7a50528e25197d566 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/index.d.ts @@ -0,0 +1,99 @@ +import { ansi256 } from "./ansi256.js"; +import { bgAnsi256 } from "./bgAnsi256.js"; +import { bgBlack } from "./bgBlack.js"; +import { bgBlackBright } from "./bgBlackBright.js"; +import { bgBlue } from "./bgBlue.js"; +import { bgBlueBright } from "./bgBlueBright.js"; +import { bgCyan } from "./bgCyan.js"; +import { bgCyanBright } from "./bgCyanBright.js"; +import { bgGreen } from "./bgGreen.js"; +import { bgGreenBright } from "./bgGreenBright.js"; +import { bgHex } from "./bgHex.js"; +import { bgMagenta } from "./bgMagenta.js"; +import { bgMagentaBright } from "./bgMagentaBright.js"; +import { bgRed } from "./bgRed.js"; +import { bgRedBright } from "./bgRedBright.js"; +import { bgRgb } from "./bgRgb.js"; +import { bgWhite } from "./bgWhite.js"; +import { bgWhiteBright } from "./bgWhiteBright.js"; +import { bgYellow } from "./bgYellow.js"; +import { bgYellowBright } from "./bgYellowBright.js"; +import { black } from "./black.js"; +import { blackBright } from "./blackBright.js"; +import { blue } from "./blue.js"; +import { blueBright } from "./blueBright.js"; +import { bold } from "./bold.js"; +import { cyan } from "./cyan.js"; +import { cyanBright } from "./cyanBright.js"; +import { dim } from "./dim.js"; +import { green } from "./green.js"; +import { greenBright } from "./greenBright.js"; +import { hex } from "./hex.js"; +import { hidden } from "./hidden.js"; +import { inverse } from "./inverse.js"; +import { italic } from "./italic.js"; +import { magenta } from "./magenta.js"; +import { magentaBright } from "./magentaBright.js"; +import { red } from "./red.js"; +import { redBright } from "./redBright.js"; +import { reset } from "./reset.js"; +import { rgb } from "./rgb.js"; +import { strikethrough } from "./strikethrough.js"; +import { underline } from "./underline.js"; +import { white } from "./white.js"; +import { whiteBright } from "./whiteBright.js"; +import { yellow } from "./yellow.js"; +import { yellowBright } from "./yellowBright.js"; + +//#region src/server/colors/index.d.ts +declare const colors: Readonly<{ + reset: typeof reset; + bold: typeof bold; + dim: typeof dim; + italic: typeof italic; + underline: typeof underline; + inverse: typeof inverse; + hidden: typeof hidden; + strikethrough: typeof strikethrough; + black: typeof black; + red: typeof red; + green: typeof green; + yellow: typeof yellow; + blue: typeof blue; + magenta: typeof magenta; + cyan: typeof cyan; + white: typeof white; + gray: typeof blackBright; + blackBright: typeof blackBright; + redBright: typeof redBright; + greenBright: typeof greenBright; + yellowBright: typeof yellowBright; + blueBright: typeof blueBright; + magentaBright: typeof magentaBright; + cyanBright: typeof cyanBright; + whiteBright: typeof whiteBright; + bgBlack: typeof bgBlack; + bgRed: typeof bgRed; + bgGreen: typeof bgGreen; + bgYellow: typeof bgYellow; + bgBlue: typeof bgBlue; + bgMagenta: typeof bgMagenta; + bgCyan: typeof bgCyan; + bgWhite: typeof bgWhite; + bgBlackBright: typeof bgBlackBright; + bgRedBright: typeof bgRedBright; + bgGreenBright: typeof bgGreenBright; + bgYellowBright: typeof bgYellowBright; + bgBlueBright: typeof bgBlueBright; + bgMagentaBright: typeof bgMagentaBright; + bgCyanBright: typeof bgCyanBright; + bgWhiteBright: typeof bgWhiteBright; + ansi256: typeof ansi256; + bgAnsi256: typeof bgAnsi256; + rgb: typeof rgb; + bgRgb: typeof bgRgb; + hex: typeof hex; + bgHex: typeof bgHex; +}>; +//#endregion +export { colors }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/index.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/index.js new file mode 100644 index 0000000000000000000000000000000000000000..57e0d1957e6fcb06e76e4b2ea759a7796e8ca694 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/index.js @@ -0,0 +1,99 @@ +const require_ansi256 = require("./ansi256.js"); +const require_bgAnsi256 = require("./bgAnsi256.js"); +const require_bgBlack = require("./bgBlack.js"); +const require_bgBlackBright = require("./bgBlackBright.js"); +const require_bgBlue = require("./bgBlue.js"); +const require_bgBlueBright = require("./bgBlueBright.js"); +const require_bgCyan = require("./bgCyan.js"); +const require_bgCyanBright = require("./bgCyanBright.js"); +const require_bgGreen = require("./bgGreen.js"); +const require_bgGreenBright = require("./bgGreenBright.js"); +const require_bgHex = require("./bgHex.js"); +const require_bgMagenta = require("./bgMagenta.js"); +const require_bgMagentaBright = require("./bgMagentaBright.js"); +const require_bgRed = require("./bgRed.js"); +const require_bgRedBright = require("./bgRedBright.js"); +const require_bgRgb = require("./bgRgb.js"); +const require_bgWhite = require("./bgWhite.js"); +const require_bgWhiteBright = require("./bgWhiteBright.js"); +const require_bgYellow = require("./bgYellow.js"); +const require_bgYellowBright = require("./bgYellowBright.js"); +const require_black = require("./black.js"); +const require_blackBright = require("./blackBright.js"); +const require_blue = require("./blue.js"); +const require_blueBright = require("./blueBright.js"); +const require_bold = require("./bold.js"); +const require_cyan = require("./cyan.js"); +const require_cyanBright = require("./cyanBright.js"); +const require_dim = require("./dim.js"); +const require_gray = require("./gray.js"); +const require_green = require("./green.js"); +const require_greenBright = require("./greenBright.js"); +const require_hex = require("./hex.js"); +const require_hidden = require("./hidden.js"); +const require_inverse = require("./inverse.js"); +const require_italic = require("./italic.js"); +const require_magenta = require("./magenta.js"); +const require_magentaBright = require("./magentaBright.js"); +const require_red = require("./red.js"); +const require_redBright = require("./redBright.js"); +const require_reset = require("./reset.js"); +const require_rgb = require("./rgb.js"); +const require_strikethrough = require("./strikethrough.js"); +const require_underline = require("./underline.js"); +const require_white = require("./white.js"); +const require_whiteBright = require("./whiteBright.js"); +const require_yellow = require("./yellow.js"); +const require_yellowBright = require("./yellowBright.js"); +//#region src/server/colors/index.ts +const colors = /* @__PURE__ */ Object.freeze({ + reset: require_reset.reset, + bold: require_bold.bold, + dim: require_dim.dim, + italic: require_italic.italic, + underline: require_underline.underline, + inverse: require_inverse.inverse, + hidden: require_hidden.hidden, + strikethrough: require_strikethrough.strikethrough, + black: require_black.black, + red: require_red.red, + green: require_green.green, + yellow: require_yellow.yellow, + blue: require_blue.blue, + magenta: require_magenta.magenta, + cyan: require_cyan.cyan, + white: require_white.white, + gray: require_gray.gray, + blackBright: require_blackBright.blackBright, + redBright: require_redBright.redBright, + greenBright: require_greenBright.greenBright, + yellowBright: require_yellowBright.yellowBright, + blueBright: require_blueBright.blueBright, + magentaBright: require_magentaBright.magentaBright, + cyanBright: require_cyanBright.cyanBright, + whiteBright: require_whiteBright.whiteBright, + bgBlack: require_bgBlack.bgBlack, + bgRed: require_bgRed.bgRed, + bgGreen: require_bgGreen.bgGreen, + bgYellow: require_bgYellow.bgYellow, + bgBlue: require_bgBlue.bgBlue, + bgMagenta: require_bgMagenta.bgMagenta, + bgCyan: require_bgCyan.bgCyan, + bgWhite: require_bgWhite.bgWhite, + bgBlackBright: require_bgBlackBright.bgBlackBright, + bgRedBright: require_bgRedBright.bgRedBright, + bgGreenBright: require_bgGreenBright.bgGreenBright, + bgYellowBright: require_bgYellowBright.bgYellowBright, + bgBlueBright: require_bgBlueBright.bgBlueBright, + bgMagentaBright: require_bgMagentaBright.bgMagentaBright, + bgCyanBright: require_bgCyanBright.bgCyanBright, + bgWhiteBright: require_bgWhiteBright.bgWhiteBright, + ansi256: require_ansi256.ansi256, + bgAnsi256: require_bgAnsi256.bgAnsi256, + rgb: require_rgb.rgb, + bgRgb: require_bgRgb.bgRgb, + hex: require_hex.hex, + bgHex: require_bgHex.bgHex +}); +//#endregion +exports.colors = colors; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/index.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0de3b6335185d941da557b59ca36042dd1e9d030 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/index.mjs @@ -0,0 +1,99 @@ +import { ansi256 } from "./ansi256.mjs"; +import { bgAnsi256 } from "./bgAnsi256.mjs"; +import { bgBlack } from "./bgBlack.mjs"; +import { bgBlackBright } from "./bgBlackBright.mjs"; +import { bgBlue } from "./bgBlue.mjs"; +import { bgBlueBright } from "./bgBlueBright.mjs"; +import { bgCyan } from "./bgCyan.mjs"; +import { bgCyanBright } from "./bgCyanBright.mjs"; +import { bgGreen } from "./bgGreen.mjs"; +import { bgGreenBright } from "./bgGreenBright.mjs"; +import { bgHex } from "./bgHex.mjs"; +import { bgMagenta } from "./bgMagenta.mjs"; +import { bgMagentaBright } from "./bgMagentaBright.mjs"; +import { bgRed } from "./bgRed.mjs"; +import { bgRedBright } from "./bgRedBright.mjs"; +import { bgRgb } from "./bgRgb.mjs"; +import { bgWhite } from "./bgWhite.mjs"; +import { bgWhiteBright } from "./bgWhiteBright.mjs"; +import { bgYellow } from "./bgYellow.mjs"; +import { bgYellowBright } from "./bgYellowBright.mjs"; +import { black } from "./black.mjs"; +import { blackBright } from "./blackBright.mjs"; +import { blue } from "./blue.mjs"; +import { blueBright } from "./blueBright.mjs"; +import { bold } from "./bold.mjs"; +import { cyan } from "./cyan.mjs"; +import { cyanBright } from "./cyanBright.mjs"; +import { dim } from "./dim.mjs"; +import { gray } from "./gray.mjs"; +import { green } from "./green.mjs"; +import { greenBright } from "./greenBright.mjs"; +import { hex } from "./hex.mjs"; +import { hidden } from "./hidden.mjs"; +import { inverse } from "./inverse.mjs"; +import { italic } from "./italic.mjs"; +import { magenta } from "./magenta.mjs"; +import { magentaBright } from "./magentaBright.mjs"; +import { red } from "./red.mjs"; +import { redBright } from "./redBright.mjs"; +import { reset } from "./reset.mjs"; +import { rgb } from "./rgb.mjs"; +import { strikethrough } from "./strikethrough.mjs"; +import { underline } from "./underline.mjs"; +import { white } from "./white.mjs"; +import { whiteBright } from "./whiteBright.mjs"; +import { yellow } from "./yellow.mjs"; +import { yellowBright } from "./yellowBright.mjs"; +//#region src/server/colors/index.ts +const colors = /* @__PURE__ */ Object.freeze({ + reset, + bold, + dim, + italic, + underline, + inverse, + hidden, + strikethrough, + black, + red, + green, + yellow, + blue, + magenta, + cyan, + white, + gray, + blackBright, + redBright, + greenBright, + yellowBright, + blueBright, + magentaBright, + cyanBright, + whiteBright, + bgBlack, + bgRed, + bgGreen, + bgYellow, + bgBlue, + bgMagenta, + bgCyan, + bgWhite, + bgBlackBright, + bgRedBright, + bgGreenBright, + bgYellowBright, + bgBlueBright, + bgMagentaBright, + bgCyanBright, + bgWhiteBright, + ansi256, + bgAnsi256, + rgb, + bgRgb, + hex, + bgHex +}); +//#endregion +export { colors }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/inverse.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/inverse.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..1c3cfe623195b8147755abbd114792349dfa5e01 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/inverse.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/inverse.d.ts +/** + * Swaps the foreground and background colors. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.inverse('hello')); + */ +declare function inverse(text: string): string; +//#endregion +export { inverse }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/inverse.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/inverse.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1c3cfe623195b8147755abbd114792349dfa5e01 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/inverse.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/inverse.d.ts +/** + * Swaps the foreground and background colors. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.inverse('hello')); + */ +declare function inverse(text: string): string; +//#endregion +export { inverse }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/inverse.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/inverse.js new file mode 100644 index 0000000000000000000000000000000000000000..377a745b3ae22d8f58689a840f0925d8accd32a4 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/inverse.js @@ -0,0 +1,18 @@ +const require_wrapAnsi = require("./_internal/wrapAnsi.js"); +//#region src/server/colors/inverse.ts +/** +* Swaps the foreground and background colors. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.inverse('hello')); +*/ +function inverse(text) { + return require_wrapAnsi.wrapAnsi("\x1B[7m", "\x1B[27m", text); +} +//#endregion +exports.inverse = inverse; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/inverse.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/inverse.mjs new file mode 100644 index 0000000000000000000000000000000000000000..63fdb999e644b7be83c287146412191207fdcf78 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/inverse.mjs @@ -0,0 +1,18 @@ +import { wrapAnsi } from "./_internal/wrapAnsi.mjs"; +//#region src/server/colors/inverse.ts +/** +* Swaps the foreground and background colors. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.inverse('hello')); +*/ +function inverse(text) { + return wrapAnsi("\x1B[7m", "\x1B[27m", text); +} +//#endregion +export { inverse }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/italic.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/italic.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..84c5a173b8f062af2456632a66907696ee856c27 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/italic.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/italic.d.ts +/** + * Italic text. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.italic('hello')); + */ +declare function italic(text: string): string; +//#endregion +export { italic }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/italic.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/italic.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..84c5a173b8f062af2456632a66907696ee856c27 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/italic.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/italic.d.ts +/** + * Italic text. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.italic('hello')); + */ +declare function italic(text: string): string; +//#endregion +export { italic }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/italic.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/italic.js new file mode 100644 index 0000000000000000000000000000000000000000..39638cd68e10997451418943930b4d1ac3e1c1f2 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/italic.js @@ -0,0 +1,18 @@ +const require_wrapAnsi = require("./_internal/wrapAnsi.js"); +//#region src/server/colors/italic.ts +/** +* Italic text. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.italic('hello')); +*/ +function italic(text) { + return require_wrapAnsi.wrapAnsi("\x1B[3m", "\x1B[23m", text); +} +//#endregion +exports.italic = italic; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/italic.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/italic.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b886d94937e89ba692b429c6af5d90137210c7e7 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/italic.mjs @@ -0,0 +1,18 @@ +import { wrapAnsi } from "./_internal/wrapAnsi.mjs"; +//#region src/server/colors/italic.ts +/** +* Italic text. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.italic('hello')); +*/ +function italic(text) { + return wrapAnsi("\x1B[3m", "\x1B[23m", text); +} +//#endregion +export { italic }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/magenta.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/magenta.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..2570e93fb3aa830cef656f505d8d4520d0d9b31c --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/magenta.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/magenta.d.ts +/** + * Magenta foreground. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.magenta('hello')); + */ +declare function magenta(text: string): string; +//#endregion +export { magenta }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/magenta.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/magenta.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2570e93fb3aa830cef656f505d8d4520d0d9b31c --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/magenta.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/magenta.d.ts +/** + * Magenta foreground. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.magenta('hello')); + */ +declare function magenta(text: string): string; +//#endregion +export { magenta }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/magenta.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/magenta.js new file mode 100644 index 0000000000000000000000000000000000000000..fbf19f85a93803e155222be989a2707e68dae4cf --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/magenta.js @@ -0,0 +1,18 @@ +const require_wrapAnsi = require("./_internal/wrapAnsi.js"); +//#region src/server/colors/magenta.ts +/** +* Magenta foreground. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.magenta('hello')); +*/ +function magenta(text) { + return require_wrapAnsi.wrapAnsi("\x1B[35m", "\x1B[39m", text); +} +//#endregion +exports.magenta = magenta; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/magenta.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/magenta.mjs new file mode 100644 index 0000000000000000000000000000000000000000..461e8c73510accd6f9df681ee60f8a2f1fb40472 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/magenta.mjs @@ -0,0 +1,18 @@ +import { wrapAnsi } from "./_internal/wrapAnsi.mjs"; +//#region src/server/colors/magenta.ts +/** +* Magenta foreground. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.magenta('hello')); +*/ +function magenta(text) { + return wrapAnsi("\x1B[35m", "\x1B[39m", text); +} +//#endregion +export { magenta }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/magentaBright.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/magentaBright.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..8e698371abe8e4c1b43d2d607522ec6efa808f83 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/magentaBright.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/magentaBright.d.ts +/** + * Bright magenta foreground. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.magentaBright('hello')); + */ +declare function magentaBright(text: string): string; +//#endregion +export { magentaBright }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/magentaBright.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/magentaBright.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8e698371abe8e4c1b43d2d607522ec6efa808f83 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/magentaBright.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/magentaBright.d.ts +/** + * Bright magenta foreground. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.magentaBright('hello')); + */ +declare function magentaBright(text: string): string; +//#endregion +export { magentaBright }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/magentaBright.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/magentaBright.js new file mode 100644 index 0000000000000000000000000000000000000000..bde01bcf45f93360c36afc51f8690e096e2d7e8e --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/magentaBright.js @@ -0,0 +1,18 @@ +const require_wrapAnsi = require("./_internal/wrapAnsi.js"); +//#region src/server/colors/magentaBright.ts +/** +* Bright magenta foreground. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.magentaBright('hello')); +*/ +function magentaBright(text) { + return require_wrapAnsi.wrapAnsi("\x1B[95m", "\x1B[39m", text); +} +//#endregion +exports.magentaBright = magentaBright; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/magentaBright.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/magentaBright.mjs new file mode 100644 index 0000000000000000000000000000000000000000..db14d235b92e290907db716c15e9eed472027f4f --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/magentaBright.mjs @@ -0,0 +1,18 @@ +import { wrapAnsi } from "./_internal/wrapAnsi.mjs"; +//#region src/server/colors/magentaBright.ts +/** +* Bright magenta foreground. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.magentaBright('hello')); +*/ +function magentaBright(text) { + return wrapAnsi("\x1B[95m", "\x1B[39m", text); +} +//#endregion +export { magentaBright }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/red.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/red.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..1e2395b1e94c63022483e20334a2bf61b1bb26ab --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/red.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/red.d.ts +/** + * Red foreground. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.red('error')); + */ +declare function red(text: string): string; +//#endregion +export { red }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/red.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/red.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1e2395b1e94c63022483e20334a2bf61b1bb26ab --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/red.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/red.d.ts +/** + * Red foreground. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.red('error')); + */ +declare function red(text: string): string; +//#endregion +export { red }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/red.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/red.js new file mode 100644 index 0000000000000000000000000000000000000000..abca1e4b90c6fb7f1483aba92a5772dbd0e9e793 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/red.js @@ -0,0 +1,18 @@ +const require_wrapAnsi = require("./_internal/wrapAnsi.js"); +//#region src/server/colors/red.ts +/** +* Red foreground. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.red('error')); +*/ +function red(text) { + return require_wrapAnsi.wrapAnsi("\x1B[31m", "\x1B[39m", text); +} +//#endregion +exports.red = red; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/red.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/red.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ca88d09e848c50d5e2a313a4da6e3f5202f11faa --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/red.mjs @@ -0,0 +1,18 @@ +import { wrapAnsi } from "./_internal/wrapAnsi.mjs"; +//#region src/server/colors/red.ts +/** +* Red foreground. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.red('error')); +*/ +function red(text) { + return wrapAnsi("\x1B[31m", "\x1B[39m", text); +} +//#endregion +export { red }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/redBright.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/redBright.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..73fdb5a8f5d1effe4636e35bed91c16c39187049 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/redBright.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/redBright.d.ts +/** + * Bright red foreground. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.redBright('hello')); + */ +declare function redBright(text: string): string; +//#endregion +export { redBright }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/redBright.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/redBright.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..73fdb5a8f5d1effe4636e35bed91c16c39187049 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/redBright.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/redBright.d.ts +/** + * Bright red foreground. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.redBright('hello')); + */ +declare function redBright(text: string): string; +//#endregion +export { redBright }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/redBright.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/redBright.js new file mode 100644 index 0000000000000000000000000000000000000000..282fe5fe39e544fcd69170641ef13d63c1ef4663 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/redBright.js @@ -0,0 +1,18 @@ +const require_wrapAnsi = require("./_internal/wrapAnsi.js"); +//#region src/server/colors/redBright.ts +/** +* Bright red foreground. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.redBright('hello')); +*/ +function redBright(text) { + return require_wrapAnsi.wrapAnsi("\x1B[91m", "\x1B[39m", text); +} +//#endregion +exports.redBright = redBright; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/redBright.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/redBright.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3bb0957a0079d130e60402526bf1e71ca2104c16 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/redBright.mjs @@ -0,0 +1,18 @@ +import { wrapAnsi } from "./_internal/wrapAnsi.mjs"; +//#region src/server/colors/redBright.ts +/** +* Bright red foreground. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.redBright('hello')); +*/ +function redBright(text) { + return wrapAnsi("\x1B[91m", "\x1B[39m", text); +} +//#endregion +export { redBright }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/reset.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/reset.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..a66cfcb9065eb74f78e0be24c010e5350cfe4ef5 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/reset.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/reset.d.ts +/** + * Resets every style and color set up to this point. Wraps text with the ANSI reset code. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.reset('hello')); + */ +declare function reset(text: string): string; +//#endregion +export { reset }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/reset.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/reset.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a66cfcb9065eb74f78e0be24c010e5350cfe4ef5 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/reset.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/reset.d.ts +/** + * Resets every style and color set up to this point. Wraps text with the ANSI reset code. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.reset('hello')); + */ +declare function reset(text: string): string; +//#endregion +export { reset }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/reset.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/reset.js new file mode 100644 index 0000000000000000000000000000000000000000..78ed60622f409717ab3598e8955bb080f18bed11 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/reset.js @@ -0,0 +1,18 @@ +const require_wrapAnsi = require("./_internal/wrapAnsi.js"); +//#region src/server/colors/reset.ts +/** +* Resets every style and color set up to this point. Wraps text with the ANSI reset code. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.reset('hello')); +*/ +function reset(text) { + return require_wrapAnsi.wrapAnsi("\x1B[0m", "\x1B[0m", text); +} +//#endregion +exports.reset = reset; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/reset.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/reset.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4b7a536b7c87c580e4230e6fc3fede3e32a9a777 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/reset.mjs @@ -0,0 +1,18 @@ +import { wrapAnsi } from "./_internal/wrapAnsi.mjs"; +//#region src/server/colors/reset.ts +/** +* Resets every style and color set up to this point. Wraps text with the ANSI reset code. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.reset('hello')); +*/ +function reset(text) { + return wrapAnsi("\x1B[0m", "\x1B[0m", text); +} +//#endregion +export { reset }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/rgb.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/rgb.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..6b238feaf5fe98a6ea0724c60c852a9edc156971 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/rgb.d.mts @@ -0,0 +1,20 @@ +import { ColorFunction } from "./types.mjs"; + +//#region src/server/colors/rgb.d.ts +/** + * Returns a function that wraps text with the given 24-bit (truecolor) foreground. + * + * @param r - Red component (0–255). + * @param g - Green component (0–255). + * @param b - Blue component (0–255). + * @returns A color function that wraps text with the chosen RGB foreground. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * const brand = colors.rgb(255, 99, 71); + * console.log(brand('hello')); + */ +declare function rgb(r: number, g: number, b: number): ColorFunction; +//#endregion +export { rgb }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/rgb.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/rgb.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6950003923648257097efe6030d979ce53a0918d --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/rgb.d.ts @@ -0,0 +1,20 @@ +import { ColorFunction } from "./types.js"; + +//#region src/server/colors/rgb.d.ts +/** + * Returns a function that wraps text with the given 24-bit (truecolor) foreground. + * + * @param r - Red component (0–255). + * @param g - Green component (0–255). + * @param b - Blue component (0–255). + * @returns A color function that wraps text with the chosen RGB foreground. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * const brand = colors.rgb(255, 99, 71); + * console.log(brand('hello')); + */ +declare function rgb(r: number, g: number, b: number): ColorFunction; +//#endregion +export { rgb }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/rgb.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/rgb.js new file mode 100644 index 0000000000000000000000000000000000000000..cfbf7f8f49686efcb5305fbd0bdefe503f2f8b06 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/rgb.js @@ -0,0 +1,21 @@ +const require_wrapAnsi = require("./_internal/wrapAnsi.js"); +//#region src/server/colors/rgb.ts +/** +* Returns a function that wraps text with the given 24-bit (truecolor) foreground. +* +* @param r - Red component (0–255). +* @param g - Green component (0–255). +* @param b - Blue component (0–255). +* @returns A color function that wraps text with the chosen RGB foreground. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* const brand = colors.rgb(255, 99, 71); +* console.log(brand('hello')); +*/ +function rgb(r, g, b) { + return (text) => require_wrapAnsi.wrapAnsi(`\x1b[38;2;${r};${g};${b}m`, "\x1B[39m", text); +} +//#endregion +exports.rgb = rgb; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/rgb.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/rgb.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e601e58c7430788631acd9ed41e70fd9e77ac3d1 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/rgb.mjs @@ -0,0 +1,21 @@ +import { wrapAnsi } from "./_internal/wrapAnsi.mjs"; +//#region src/server/colors/rgb.ts +/** +* Returns a function that wraps text with the given 24-bit (truecolor) foreground. +* +* @param r - Red component (0–255). +* @param g - Green component (0–255). +* @param b - Blue component (0–255). +* @returns A color function that wraps text with the chosen RGB foreground. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* const brand = colors.rgb(255, 99, 71); +* console.log(brand('hello')); +*/ +function rgb(r, g, b) { + return (text) => wrapAnsi(`\x1b[38;2;${r};${g};${b}m`, "\x1B[39m", text); +} +//#endregion +export { rgb }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/strikethrough.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/strikethrough.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..c26b890934e6d6c49c5fccd28ce55b69e9de827f --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/strikethrough.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/strikethrough.d.ts +/** + * Strikethrough text. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.strikethrough('hello')); + */ +declare function strikethrough(text: string): string; +//#endregion +export { strikethrough }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/strikethrough.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/strikethrough.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c26b890934e6d6c49c5fccd28ce55b69e9de827f --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/strikethrough.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/strikethrough.d.ts +/** + * Strikethrough text. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.strikethrough('hello')); + */ +declare function strikethrough(text: string): string; +//#endregion +export { strikethrough }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/strikethrough.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/strikethrough.js new file mode 100644 index 0000000000000000000000000000000000000000..e195bf111bf8a31d5a22347bc70d8614c90d25b2 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/strikethrough.js @@ -0,0 +1,18 @@ +const require_wrapAnsi = require("./_internal/wrapAnsi.js"); +//#region src/server/colors/strikethrough.ts +/** +* Strikethrough text. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.strikethrough('hello')); +*/ +function strikethrough(text) { + return require_wrapAnsi.wrapAnsi("\x1B[9m", "\x1B[29m", text); +} +//#endregion +exports.strikethrough = strikethrough; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/strikethrough.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/strikethrough.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ccdabc01242df2189bf12b57223258a2c08c0f09 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/strikethrough.mjs @@ -0,0 +1,18 @@ +import { wrapAnsi } from "./_internal/wrapAnsi.mjs"; +//#region src/server/colors/strikethrough.ts +/** +* Strikethrough text. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.strikethrough('hello')); +*/ +function strikethrough(text) { + return wrapAnsi("\x1B[9m", "\x1B[29m", text); +} +//#endregion +export { strikethrough }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/types.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/types.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..960e540a027d24f377b54dfa3db960023e545c62 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/types.d.mts @@ -0,0 +1,4 @@ +//#region src/server/colors/types.d.ts +type ColorFunction = (text: string) => string; +//#endregion +export { ColorFunction }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/types.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..960e540a027d24f377b54dfa3db960023e545c62 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/types.d.ts @@ -0,0 +1,4 @@ +//#region src/server/colors/types.d.ts +type ColorFunction = (text: string) => string; +//#endregion +export { ColorFunction }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/underline.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/underline.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..87b33fb1700e6ff4f2fa1651ddc239fc8f68ed52 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/underline.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/underline.d.ts +/** + * Underlined text. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.underline('hello')); + */ +declare function underline(text: string): string; +//#endregion +export { underline }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/underline.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/underline.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..87b33fb1700e6ff4f2fa1651ddc239fc8f68ed52 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/underline.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/underline.d.ts +/** + * Underlined text. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.underline('hello')); + */ +declare function underline(text: string): string; +//#endregion +export { underline }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/underline.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/underline.js new file mode 100644 index 0000000000000000000000000000000000000000..2e817929848b99bbfe8d54e6a718d273b2d9192a --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/underline.js @@ -0,0 +1,18 @@ +const require_wrapAnsi = require("./_internal/wrapAnsi.js"); +//#region src/server/colors/underline.ts +/** +* Underlined text. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.underline('hello')); +*/ +function underline(text) { + return require_wrapAnsi.wrapAnsi("\x1B[4m", "\x1B[24m", text); +} +//#endregion +exports.underline = underline; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/underline.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/underline.mjs new file mode 100644 index 0000000000000000000000000000000000000000..eb93c69da80e4c42e25e69fd3797a72987496a3c --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/underline.mjs @@ -0,0 +1,18 @@ +import { wrapAnsi } from "./_internal/wrapAnsi.mjs"; +//#region src/server/colors/underline.ts +/** +* Underlined text. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.underline('hello')); +*/ +function underline(text) { + return wrapAnsi("\x1B[4m", "\x1B[24m", text); +} +//#endregion +export { underline }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/white.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/white.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..ad1b521e61fc72a9723707b918c0922271f69dcc --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/white.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/white.d.ts +/** + * White foreground. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.white('hello')); + */ +declare function white(text: string): string; +//#endregion +export { white }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/white.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/white.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ad1b521e61fc72a9723707b918c0922271f69dcc --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/white.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/white.d.ts +/** + * White foreground. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.white('hello')); + */ +declare function white(text: string): string; +//#endregion +export { white }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/white.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/white.js new file mode 100644 index 0000000000000000000000000000000000000000..1f7f2467c2eed5c97499e58fb9343194062666aa --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/white.js @@ -0,0 +1,18 @@ +const require_wrapAnsi = require("./_internal/wrapAnsi.js"); +//#region src/server/colors/white.ts +/** +* White foreground. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.white('hello')); +*/ +function white(text) { + return require_wrapAnsi.wrapAnsi("\x1B[37m", "\x1B[39m", text); +} +//#endregion +exports.white = white; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/white.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/white.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1708b952d7d75d5d9b5af40a0622d24e888364ad --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/white.mjs @@ -0,0 +1,18 @@ +import { wrapAnsi } from "./_internal/wrapAnsi.mjs"; +//#region src/server/colors/white.ts +/** +* White foreground. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.white('hello')); +*/ +function white(text) { + return wrapAnsi("\x1B[37m", "\x1B[39m", text); +} +//#endregion +export { white }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/whiteBright.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/whiteBright.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..d8b0ea01dc4ae57e4ebb313edcf3acac70724364 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/whiteBright.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/whiteBright.d.ts +/** + * Bright white foreground. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.whiteBright('hello')); + */ +declare function whiteBright(text: string): string; +//#endregion +export { whiteBright }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/whiteBright.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/whiteBright.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d8b0ea01dc4ae57e4ebb313edcf3acac70724364 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/whiteBright.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/whiteBright.d.ts +/** + * Bright white foreground. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.whiteBright('hello')); + */ +declare function whiteBright(text: string): string; +//#endregion +export { whiteBright }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/whiteBright.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/whiteBright.js new file mode 100644 index 0000000000000000000000000000000000000000..f95e5b261f2178d10fa1d73b798f083c025050c7 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/whiteBright.js @@ -0,0 +1,18 @@ +const require_wrapAnsi = require("./_internal/wrapAnsi.js"); +//#region src/server/colors/whiteBright.ts +/** +* Bright white foreground. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.whiteBright('hello')); +*/ +function whiteBright(text) { + return require_wrapAnsi.wrapAnsi("\x1B[97m", "\x1B[39m", text); +} +//#endregion +exports.whiteBright = whiteBright; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/whiteBright.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/whiteBright.mjs new file mode 100644 index 0000000000000000000000000000000000000000..cd5dfecd3fb2a9fa200baba0d53aca63b39127e2 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/whiteBright.mjs @@ -0,0 +1,18 @@ +import { wrapAnsi } from "./_internal/wrapAnsi.mjs"; +//#region src/server/colors/whiteBright.ts +/** +* Bright white foreground. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.whiteBright('hello')); +*/ +function whiteBright(text) { + return wrapAnsi("\x1B[97m", "\x1B[39m", text); +} +//#endregion +export { whiteBright }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/yellow.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/yellow.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..345d1d444845e71f9ba9e6f18606659690d646f4 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/yellow.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/yellow.d.ts +/** + * Yellow foreground. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.yellow('hello')); + */ +declare function yellow(text: string): string; +//#endregion +export { yellow }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/yellow.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/yellow.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..345d1d444845e71f9ba9e6f18606659690d646f4 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/yellow.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/yellow.d.ts +/** + * Yellow foreground. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.yellow('hello')); + */ +declare function yellow(text: string): string; +//#endregion +export { yellow }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/yellow.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/yellow.js new file mode 100644 index 0000000000000000000000000000000000000000..5188bb20608ea1679bb1cde438dcaa533d2ed6bc --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/yellow.js @@ -0,0 +1,18 @@ +const require_wrapAnsi = require("./_internal/wrapAnsi.js"); +//#region src/server/colors/yellow.ts +/** +* Yellow foreground. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.yellow('hello')); +*/ +function yellow(text) { + return require_wrapAnsi.wrapAnsi("\x1B[33m", "\x1B[39m", text); +} +//#endregion +exports.yellow = yellow; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/yellow.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/yellow.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ec3b92c86eb1476217c27bb24f2624723ff9bc61 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/yellow.mjs @@ -0,0 +1,18 @@ +import { wrapAnsi } from "./_internal/wrapAnsi.mjs"; +//#region src/server/colors/yellow.ts +/** +* Yellow foreground. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.yellow('hello')); +*/ +function yellow(text) { + return wrapAnsi("\x1B[33m", "\x1B[39m", text); +} +//#endregion +export { yellow }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/yellowBright.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/colors/yellowBright.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..8b7a4a9b28c10665e36362ef9408dbc17c33d497 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/yellowBright.d.mts @@ -0,0 +1,15 @@ +//#region src/server/colors/yellowBright.d.ts +/** + * Bright yellow foreground. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.yellowBright('hello')); + */ +declare function yellowBright(text: string): string; +//#endregion +export { yellowBright }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/yellowBright.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/colors/yellowBright.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8b7a4a9b28c10665e36362ef9408dbc17c33d497 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/yellowBright.d.ts @@ -0,0 +1,15 @@ +//#region src/server/colors/yellowBright.d.ts +/** + * Bright yellow foreground. Wraps text with ANSI codes. + * + * @param text - The text to style. + * @returns The styled text. + * + * @example + * import { colors } from 'es-toolkit/server'; + * + * console.log(colors.yellowBright('hello')); + */ +declare function yellowBright(text: string): string; +//#endregion +export { yellowBright }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/yellowBright.js b/tools/ui/node_modules/es-toolkit/dist/server/colors/yellowBright.js new file mode 100644 index 0000000000000000000000000000000000000000..fadd80ebf8e08a2d53664c6bfcba58703c405a57 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/yellowBright.js @@ -0,0 +1,18 @@ +const require_wrapAnsi = require("./_internal/wrapAnsi.js"); +//#region src/server/colors/yellowBright.ts +/** +* Bright yellow foreground. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.yellowBright('hello')); +*/ +function yellowBright(text) { + return require_wrapAnsi.wrapAnsi("\x1B[93m", "\x1B[39m", text); +} +//#endregion +exports.yellowBright = yellowBright; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/colors/yellowBright.mjs b/tools/ui/node_modules/es-toolkit/dist/server/colors/yellowBright.mjs new file mode 100644 index 0000000000000000000000000000000000000000..fe45d326f0ecd6ad58684014fcfcc060571671e5 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/colors/yellowBright.mjs @@ -0,0 +1,18 @@ +import { wrapAnsi } from "./_internal/wrapAnsi.mjs"; +//#region src/server/colors/yellowBright.ts +/** +* Bright yellow foreground. Wraps text with ANSI codes. +* +* @param text - The text to style. +* @returns The styled text. +* +* @example +* import { colors } from 'es-toolkit/server'; +* +* console.log(colors.yellowBright('hello')); +*/ +function yellowBright(text) { + return wrapAnsi("\x1B[93m", "\x1B[39m", text); +} +//#endregion +export { yellowBright }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/exec.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/exec.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..b67ac9120a85374545aa71accf2dd757521992ca --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/exec.d.mts @@ -0,0 +1,63 @@ +import { SpawnOptions } from "node:child_process"; + +//#region src/server/exec.d.ts +interface ExecOptions { + signal?: AbortSignal; + timeout?: number; + stdin?: string; + spawnOptions?: SpawnOptions; + throwOnNonZeroExitCode?: boolean; +} +interface ExecResult { + pid: number | undefined; + stderr: string; + stdout: string; + exitCode: number | null; +} +/** + * Executes a command and captures its output. + * + * This function spawns a child process, collects its stdout and stderr, and resolves with the + * process result when execution finishes. By default, it throws an {@link ExecError} when the + * process exits with a non-zero exit code. + * + * @param {string} _command - The command to execute. + * @param {string[]} args - The arguments passed to the command. + * @param {ExecOptions} options - The options object. + * @param {AbortSignal} options.signal - An optional AbortSignal used to abort the process. + * @param {number} options.timeout - An optional timeout in milliseconds. When provided, the + * process is aborted after the timeout expires. + * @param {string} options.stdin - An optional string written to the process stdin. + * @param {SpawnOptions} options.spawnOptions - Additional options forwarded to `child_process.spawn`. + * @param {boolean} options.throwOnNonZeroExitCode - Whether to throw an {@link ExecError} when the + * process exits with a non-zero exit code. Defaults to `true`. + * @returns {Promise} A promise that resolves with the process result. + * @throws {ExecError} Throws when `throwOnNonZeroExitCode` is enabled and the process exits with a + * non-zero exit code. + * + * @example + * const result = await exec('echo', ['hello']); + * + * console.log(result.stdout.trim()); + * // => 'hello' + * + * @example + * const result = await exec('git', ['diff', '--quiet'], { + * throwOnNonZeroExitCode: false, + * }); + * + * console.log(result.exitCode); + * // => 1 when there are changes + */ +declare function exec(_command: string, args?: string[], options?: ExecOptions): Promise; +/** + * Represents an error thrown when a process exits with a non-zero exit code. + * + * @param {ExecResult} result - The captured process result. + */ +declare class ExecError extends Error { + readonly result: ExecResult; + constructor(result: ExecResult); +} +//#endregion +export { ExecError, exec }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/exec.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/exec.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b67ac9120a85374545aa71accf2dd757521992ca --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/exec.d.ts @@ -0,0 +1,63 @@ +import { SpawnOptions } from "node:child_process"; + +//#region src/server/exec.d.ts +interface ExecOptions { + signal?: AbortSignal; + timeout?: number; + stdin?: string; + spawnOptions?: SpawnOptions; + throwOnNonZeroExitCode?: boolean; +} +interface ExecResult { + pid: number | undefined; + stderr: string; + stdout: string; + exitCode: number | null; +} +/** + * Executes a command and captures its output. + * + * This function spawns a child process, collects its stdout and stderr, and resolves with the + * process result when execution finishes. By default, it throws an {@link ExecError} when the + * process exits with a non-zero exit code. + * + * @param {string} _command - The command to execute. + * @param {string[]} args - The arguments passed to the command. + * @param {ExecOptions} options - The options object. + * @param {AbortSignal} options.signal - An optional AbortSignal used to abort the process. + * @param {number} options.timeout - An optional timeout in milliseconds. When provided, the + * process is aborted after the timeout expires. + * @param {string} options.stdin - An optional string written to the process stdin. + * @param {SpawnOptions} options.spawnOptions - Additional options forwarded to `child_process.spawn`. + * @param {boolean} options.throwOnNonZeroExitCode - Whether to throw an {@link ExecError} when the + * process exits with a non-zero exit code. Defaults to `true`. + * @returns {Promise} A promise that resolves with the process result. + * @throws {ExecError} Throws when `throwOnNonZeroExitCode` is enabled and the process exits with a + * non-zero exit code. + * + * @example + * const result = await exec('echo', ['hello']); + * + * console.log(result.stdout.trim()); + * // => 'hello' + * + * @example + * const result = await exec('git', ['diff', '--quiet'], { + * throwOnNonZeroExitCode: false, + * }); + * + * console.log(result.exitCode); + * // => 1 when there are changes + */ +declare function exec(_command: string, args?: string[], options?: ExecOptions): Promise; +/** + * Represents an error thrown when a process exits with a non-zero exit code. + * + * @param {ExecResult} result - The captured process result. + */ +declare class ExecError extends Error { + readonly result: ExecResult; + constructor(result: ExecResult); +} +//#endregion +export { ExecError, exec }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/exec.js b/tools/ui/node_modules/es-toolkit/dist/server/exec.js new file mode 100644 index 0000000000000000000000000000000000000000..69505162ba6f9be5ef5c2bbe3a9dbefc28f29b46 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/exec.js @@ -0,0 +1,103 @@ +let node_child_process = require("node:child_process"); +let node_path = require("node:path"); +//#region src/server/exec.ts +/** +* Executes a command and captures its output. +* +* This function spawns a child process, collects its stdout and stderr, and resolves with the +* process result when execution finishes. By default, it throws an {@link ExecError} when the +* process exits with a non-zero exit code. +* +* @param {string} _command - The command to execute. +* @param {string[]} args - The arguments passed to the command. +* @param {ExecOptions} options - The options object. +* @param {AbortSignal} options.signal - An optional AbortSignal used to abort the process. +* @param {number} options.timeout - An optional timeout in milliseconds. When provided, the +* process is aborted after the timeout expires. +* @param {string} options.stdin - An optional string written to the process stdin. +* @param {SpawnOptions} options.spawnOptions - Additional options forwarded to `child_process.spawn`. +* @param {boolean} options.throwOnNonZeroExitCode - Whether to throw an {@link ExecError} when the +* process exits with a non-zero exit code. Defaults to `true`. +* @returns {Promise} A promise that resolves with the process result. +* @throws {ExecError} Throws when `throwOnNonZeroExitCode` is enabled and the process exits with a +* non-zero exit code. +* +* @example +* const result = await exec('echo', ['hello']); +* +* console.log(result.stdout.trim()); +* // => 'hello' +* +* @example +* const result = await exec('git', ['diff', '--quiet'], { +* throwOnNonZeroExitCode: false, +* }); +* +* console.log(result.exitCode); +* // => 1 when there are changes +*/ +async function exec(_command, args = [], options = {}) { + const command = (0, node_path.normalize)(_command); + const signal = parseAbortSignal(options); + const resolver = Promise.withResolvers(); + const process = (0, node_child_process.spawn)(command, args, { + windowsHide: true, + ...options.spawnOptions, + signal + }); + handleStdin(process, options); + process.once("close", () => { + resolver.resolve(); + }); + process.once("error", (error) => { + resolver.reject(error); + }); + const stdoutPromise = process.stdout != null ? streamToString(process.stdout) : Promise.resolve(""); + const stderrPromise = process.stderr != null ? streamToString(process.stderr) : Promise.resolve(""); + await resolver.promise; + const stdout = await stdoutPromise; + const stderr = await stderrPromise; + if ((options.throwOnNonZeroExitCode ?? true) && process.exitCode !== 0) throw new ExecError({ + pid: process.pid, + stdout, + stderr, + exitCode: process.exitCode + }); + return { + pid: process.pid, + stdout, + stderr, + exitCode: process.exitCode + }; +} +/** +* Represents an error thrown when a process exits with a non-zero exit code. +* +* @param {ExecResult} result - The captured process result. +*/ +var ExecError = class extends Error { + result; + constructor(result) { + super(`Process exited with non-zero exit code (${result.exitCode})`); + this.result = result; + this.name = "ExecError"; + } +}; +async function streamToString(stream) { + return Buffer.concat(await stream.toArray()).toString("utf-8"); +} +function handleStdin(process, options) { + if (options.stdin == null) return; + if (typeof options.stdin === "string") process.stdin?.end(options.stdin); +} +function parseAbortSignal(options) { + const signals = []; + if (options.signal != null) signals.push(options.signal); + if (options.timeout != null) signals.push(AbortSignal.timeout(options.timeout)); + if (options.spawnOptions?.signal != null) signals.push(options.spawnOptions.signal); + if (signals.length === 0) return; + return AbortSignal.any(signals); +} +//#endregion +exports.ExecError = ExecError; +exports.exec = exec; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/exec.mjs b/tools/ui/node_modules/es-toolkit/dist/server/exec.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6614de7666ee6585405f09bd6ee5a770c7f17daf --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/exec.mjs @@ -0,0 +1,102 @@ +import { spawn } from "node:child_process"; +import { normalize } from "node:path"; +//#region src/server/exec.ts +/** +* Executes a command and captures its output. +* +* This function spawns a child process, collects its stdout and stderr, and resolves with the +* process result when execution finishes. By default, it throws an {@link ExecError} when the +* process exits with a non-zero exit code. +* +* @param {string} _command - The command to execute. +* @param {string[]} args - The arguments passed to the command. +* @param {ExecOptions} options - The options object. +* @param {AbortSignal} options.signal - An optional AbortSignal used to abort the process. +* @param {number} options.timeout - An optional timeout in milliseconds. When provided, the +* process is aborted after the timeout expires. +* @param {string} options.stdin - An optional string written to the process stdin. +* @param {SpawnOptions} options.spawnOptions - Additional options forwarded to `child_process.spawn`. +* @param {boolean} options.throwOnNonZeroExitCode - Whether to throw an {@link ExecError} when the +* process exits with a non-zero exit code. Defaults to `true`. +* @returns {Promise} A promise that resolves with the process result. +* @throws {ExecError} Throws when `throwOnNonZeroExitCode` is enabled and the process exits with a +* non-zero exit code. +* +* @example +* const result = await exec('echo', ['hello']); +* +* console.log(result.stdout.trim()); +* // => 'hello' +* +* @example +* const result = await exec('git', ['diff', '--quiet'], { +* throwOnNonZeroExitCode: false, +* }); +* +* console.log(result.exitCode); +* // => 1 when there are changes +*/ +async function exec(_command, args = [], options = {}) { + const command = normalize(_command); + const signal = parseAbortSignal(options); + const resolver = Promise.withResolvers(); + const process = spawn(command, args, { + windowsHide: true, + ...options.spawnOptions, + signal + }); + handleStdin(process, options); + process.once("close", () => { + resolver.resolve(); + }); + process.once("error", (error) => { + resolver.reject(error); + }); + const stdoutPromise = process.stdout != null ? streamToString(process.stdout) : Promise.resolve(""); + const stderrPromise = process.stderr != null ? streamToString(process.stderr) : Promise.resolve(""); + await resolver.promise; + const stdout = await stdoutPromise; + const stderr = await stderrPromise; + if ((options.throwOnNonZeroExitCode ?? true) && process.exitCode !== 0) throw new ExecError({ + pid: process.pid, + stdout, + stderr, + exitCode: process.exitCode + }); + return { + pid: process.pid, + stdout, + stderr, + exitCode: process.exitCode + }; +} +/** +* Represents an error thrown when a process exits with a non-zero exit code. +* +* @param {ExecResult} result - The captured process result. +*/ +var ExecError = class extends Error { + result; + constructor(result) { + super(`Process exited with non-zero exit code (${result.exitCode})`); + this.result = result; + this.name = "ExecError"; + } +}; +async function streamToString(stream) { + return Buffer.concat(await stream.toArray()).toString("utf-8"); +} +function handleStdin(process, options) { + if (options.stdin == null) return; + if (typeof options.stdin === "string") process.stdin?.end(options.stdin); +} +function parseAbortSignal(options) { + const signals = []; + if (options.signal != null) signals.push(options.signal); + if (options.timeout != null) signals.push(AbortSignal.timeout(options.timeout)); + if (options.spawnOptions?.signal != null) signals.push(options.spawnOptions.signal); + if (signals.length === 0) return; + return AbortSignal.any(signals); +} +//#endregion +export { ExecError, exec }; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/index.d.mts b/tools/ui/node_modules/es-toolkit/dist/server/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..c5cca478317bba3b04867b71a0a9ad51d3856468 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/index.d.mts @@ -0,0 +1,4 @@ +import { ColorFunction } from "./colors/types.mjs"; +import { colors } from "./colors/index.mjs"; +import { ExecError, exec } from "./exec.mjs"; +export { type ColorFunction, ExecError, colors, exec }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/index.d.ts b/tools/ui/node_modules/es-toolkit/dist/server/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7e714e6afb5e204aaa4d977991ec77b1c8fa240b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/index.d.ts @@ -0,0 +1,4 @@ +import { ColorFunction } from "./colors/types.js"; +import { colors } from "./colors/index.js"; +import { ExecError, exec } from "./exec.js"; +export { type ColorFunction, ExecError, colors, exec }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/server/index.js b/tools/ui/node_modules/es-toolkit/dist/server/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d67feeb79074210530b1c52802847792138bd0db --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/index.js @@ -0,0 +1,6 @@ +Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); +const require_index = require("./colors/index.js"); +const require_exec = require("./exec.js"); +exports.ExecError = require_exec.ExecError; +exports.colors = require_index.colors; +exports.exec = require_exec.exec; diff --git a/tools/ui/node_modules/es-toolkit/dist/server/index.mjs b/tools/ui/node_modules/es-toolkit/dist/server/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..151a52c6857e0d6a637129f214f7a0e187fbbc8e --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/server/index.mjs @@ -0,0 +1,3 @@ +import { colors } from "./colors/index.mjs"; +import { ExecError, exec } from "./exec.mjs"; +export { ExecError, colors, exec }; diff --git a/tools/ui/node_modules/es-toolkit/dist/set/countBy.d.mts b/tools/ui/node_modules/es-toolkit/dist/set/countBy.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..2f7211bb7a83274ca291813c5881a005ab664b42 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/countBy.d.mts @@ -0,0 +1,27 @@ +//#region src/set/countBy.d.ts +/** + * Counts the occurrences of items in a Set based on a transformation function. + * + * This function takes a Set and a function that generates a key from each value. + * It returns a Map with the generated keys and their counts as values. + * The count is incremented for each element for which the transformation produces the same key. + * + * @template T - The type of elements in the Set. + * @template K - The type of keys produced by the transformation function. + * @param {Set} set - The Set to count occurrences from. + * @param {(value: T, value2: T, set: Set) => K} mapper - The function to produce a key for counting. + * @returns {Map} A Map containing the mapped keys and their counts. + * + * @example + * const set = new Set([1, 2, 3, 4, 5]); + * const result = countBy(set, (value) => value % 2 === 0 ? 'even' : 'odd'); + * // result will be Map(2) { 'odd' => 3, 'even' => 2 } + * + * @example + * const set = new Set(['apple', 'banana', 'cherry']); + * const result = countBy(set, (value) => value.length); + * // result will be Map(2) { 5 => 1, 6 => 2 } + */ +declare function countBy(set: Set, mapper: (value: T, value2: T, set: Set) => K): Map; +//#endregion +export { countBy }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/set/countBy.d.ts b/tools/ui/node_modules/es-toolkit/dist/set/countBy.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2f7211bb7a83274ca291813c5881a005ab664b42 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/countBy.d.ts @@ -0,0 +1,27 @@ +//#region src/set/countBy.d.ts +/** + * Counts the occurrences of items in a Set based on a transformation function. + * + * This function takes a Set and a function that generates a key from each value. + * It returns a Map with the generated keys and their counts as values. + * The count is incremented for each element for which the transformation produces the same key. + * + * @template T - The type of elements in the Set. + * @template K - The type of keys produced by the transformation function. + * @param {Set} set - The Set to count occurrences from. + * @param {(value: T, value2: T, set: Set) => K} mapper - The function to produce a key for counting. + * @returns {Map} A Map containing the mapped keys and their counts. + * + * @example + * const set = new Set([1, 2, 3, 4, 5]); + * const result = countBy(set, (value) => value % 2 === 0 ? 'even' : 'odd'); + * // result will be Map(2) { 'odd' => 3, 'even' => 2 } + * + * @example + * const set = new Set(['apple', 'banana', 'cherry']); + * const result = countBy(set, (value) => value.length); + * // result will be Map(2) { 5 => 1, 6 => 2 } + */ +declare function countBy(set: Set, mapper: (value: T, value2: T, set: Set) => K): Map; +//#endregion +export { countBy }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/set/countBy.js b/tools/ui/node_modules/es-toolkit/dist/set/countBy.js new file mode 100644 index 0000000000000000000000000000000000000000..f0983bf930cb2cd43b6602fc3e3603720c683680 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/countBy.js @@ -0,0 +1,34 @@ +//#region src/set/countBy.ts +/** +* Counts the occurrences of items in a Set based on a transformation function. +* +* This function takes a Set and a function that generates a key from each value. +* It returns a Map with the generated keys and their counts as values. +* The count is incremented for each element for which the transformation produces the same key. +* +* @template T - The type of elements in the Set. +* @template K - The type of keys produced by the transformation function. +* @param {Set} set - The Set to count occurrences from. +* @param {(value: T, value2: T, set: Set) => K} mapper - The function to produce a key for counting. +* @returns {Map} A Map containing the mapped keys and their counts. +* +* @example +* const set = new Set([1, 2, 3, 4, 5]); +* const result = countBy(set, (value) => value % 2 === 0 ? 'even' : 'odd'); +* // result will be Map(2) { 'odd' => 3, 'even' => 2 } +* +* @example +* const set = new Set(['apple', 'banana', 'cherry']); +* const result = countBy(set, (value) => value.length); +* // result will be Map(2) { 5 => 1, 6 => 2 } +*/ +function countBy(set, mapper) { + const result = /* @__PURE__ */ new Map(); + for (const value of set) { + const mappedKey = mapper(value, value, set); + result.set(mappedKey, (result.get(mappedKey) ?? 0) + 1); + } + return result; +} +//#endregion +exports.countBy = countBy; diff --git a/tools/ui/node_modules/es-toolkit/dist/set/countBy.mjs b/tools/ui/node_modules/es-toolkit/dist/set/countBy.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a0963ae797d7ec2308cf5e58d2aaf93ea932b492 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/countBy.mjs @@ -0,0 +1,34 @@ +//#region src/set/countBy.ts +/** +* Counts the occurrences of items in a Set based on a transformation function. +* +* This function takes a Set and a function that generates a key from each value. +* It returns a Map with the generated keys and their counts as values. +* The count is incremented for each element for which the transformation produces the same key. +* +* @template T - The type of elements in the Set. +* @template K - The type of keys produced by the transformation function. +* @param {Set} set - The Set to count occurrences from. +* @param {(value: T, value2: T, set: Set) => K} mapper - The function to produce a key for counting. +* @returns {Map} A Map containing the mapped keys and their counts. +* +* @example +* const set = new Set([1, 2, 3, 4, 5]); +* const result = countBy(set, (value) => value % 2 === 0 ? 'even' : 'odd'); +* // result will be Map(2) { 'odd' => 3, 'even' => 2 } +* +* @example +* const set = new Set(['apple', 'banana', 'cherry']); +* const result = countBy(set, (value) => value.length); +* // result will be Map(2) { 5 => 1, 6 => 2 } +*/ +function countBy(set, mapper) { + const result = /* @__PURE__ */ new Map(); + for (const value of set) { + const mappedKey = mapper(value, value, set); + result.set(mappedKey, (result.get(mappedKey) ?? 0) + 1); + } + return result; +} +//#endregion +export { countBy }; diff --git a/tools/ui/node_modules/es-toolkit/dist/set/every.d.mts b/tools/ui/node_modules/es-toolkit/dist/set/every.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..130eb588b5cb2d58d88f901b17c9bd0af0bed8ca --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/every.d.mts @@ -0,0 +1,24 @@ +//#region src/set/every.d.ts +/** + * Tests whether all elements in a Set satisfy the provided predicate function. + * + * This function iterates through all elements of the Set and checks if the predicate function + * returns true for every element. It returns true if the predicate is satisfied for all elements, + * and false otherwise. + * + * @template T - The type of elements in the Set. + * @param {Set} set - The Set to test. + * @param {(value: T, value2: T, set: Set) => boolean} doesMatch - A predicate function that tests each element. + * @returns {boolean} true if all elements satisfy the predicate, false otherwise. + * + * @example + * const set = new Set([10, 20, 30]); + * const result = every(set, (value) => value > 5); + * // result will be: true + * + * const result2 = every(set, (value) => value > 15); + * // result2 will be: false + */ +declare function every(set: Set, doesMatch: (value: T, value2: T, set: Set) => boolean): boolean; +//#endregion +export { every }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/set/every.d.ts b/tools/ui/node_modules/es-toolkit/dist/set/every.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..130eb588b5cb2d58d88f901b17c9bd0af0bed8ca --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/every.d.ts @@ -0,0 +1,24 @@ +//#region src/set/every.d.ts +/** + * Tests whether all elements in a Set satisfy the provided predicate function. + * + * This function iterates through all elements of the Set and checks if the predicate function + * returns true for every element. It returns true if the predicate is satisfied for all elements, + * and false otherwise. + * + * @template T - The type of elements in the Set. + * @param {Set} set - The Set to test. + * @param {(value: T, value2: T, set: Set) => boolean} doesMatch - A predicate function that tests each element. + * @returns {boolean} true if all elements satisfy the predicate, false otherwise. + * + * @example + * const set = new Set([10, 20, 30]); + * const result = every(set, (value) => value > 5); + * // result will be: true + * + * const result2 = every(set, (value) => value > 15); + * // result2 will be: false + */ +declare function every(set: Set, doesMatch: (value: T, value2: T, set: Set) => boolean): boolean; +//#endregion +export { every }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/set/every.js b/tools/ui/node_modules/es-toolkit/dist/set/every.js new file mode 100644 index 0000000000000000000000000000000000000000..eb8cc64d6b0d2e3077963c27635c3176adb9c3f5 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/every.js @@ -0,0 +1,27 @@ +//#region src/set/every.ts +/** +* Tests whether all elements in a Set satisfy the provided predicate function. +* +* This function iterates through all elements of the Set and checks if the predicate function +* returns true for every element. It returns true if the predicate is satisfied for all elements, +* and false otherwise. +* +* @template T - The type of elements in the Set. +* @param {Set} set - The Set to test. +* @param {(value: T, value2: T, set: Set) => boolean} doesMatch - A predicate function that tests each element. +* @returns {boolean} true if all elements satisfy the predicate, false otherwise. +* +* @example +* const set = new Set([10, 20, 30]); +* const result = every(set, (value) => value > 5); +* // result will be: true +* +* const result2 = every(set, (value) => value > 15); +* // result2 will be: false +*/ +function every(set, doesMatch) { + for (const value of set) if (!doesMatch(value, value, set)) return false; + return true; +} +//#endregion +exports.every = every; diff --git a/tools/ui/node_modules/es-toolkit/dist/set/every.mjs b/tools/ui/node_modules/es-toolkit/dist/set/every.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4d1c9876116e16efe7dd8c25d4c6d574022799c2 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/every.mjs @@ -0,0 +1,27 @@ +//#region src/set/every.ts +/** +* Tests whether all elements in a Set satisfy the provided predicate function. +* +* This function iterates through all elements of the Set and checks if the predicate function +* returns true for every element. It returns true if the predicate is satisfied for all elements, +* and false otherwise. +* +* @template T - The type of elements in the Set. +* @param {Set} set - The Set to test. +* @param {(value: T, value2: T, set: Set) => boolean} doesMatch - A predicate function that tests each element. +* @returns {boolean} true if all elements satisfy the predicate, false otherwise. +* +* @example +* const set = new Set([10, 20, 30]); +* const result = every(set, (value) => value > 5); +* // result will be: true +* +* const result2 = every(set, (value) => value > 15); +* // result2 will be: false +*/ +function every(set, doesMatch) { + for (const value of set) if (!doesMatch(value, value, set)) return false; + return true; +} +//#endregion +export { every }; diff --git a/tools/ui/node_modules/es-toolkit/dist/set/filter.d.mts b/tools/ui/node_modules/es-toolkit/dist/set/filter.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..b4c9c302fe114b5c7168c9a86dc279cf171d32b0 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/filter.d.mts @@ -0,0 +1,21 @@ +//#region src/set/filter.d.ts +/** + * Filters a Set based on a predicate function. + * + * This function takes a Set and a predicate function, and returns a new Set containing + * only the elements for which the predicate function returns true. + * + * @template T - The type of elements in the Set. + * @param {Set} set - The Set to filter. + * @param {(value: T, value2: T, set: Set) => boolean} callback - A predicate function that tests each element. + * @returns {Set} A new Set containing only the elements that satisfy the predicate. + * + * @example + * const set = new Set([1, 2, 3, 4, 5]); + * const result = filter(set, (value) => value > 2); + * // result will be: + * // Set(3) { 3, 4, 5 } + */ +declare function filter(set: Set, callback: (value: T, value2: T, set: Set) => boolean): Set; +//#endregion +export { filter }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/set/filter.d.ts b/tools/ui/node_modules/es-toolkit/dist/set/filter.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b4c9c302fe114b5c7168c9a86dc279cf171d32b0 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/filter.d.ts @@ -0,0 +1,21 @@ +//#region src/set/filter.d.ts +/** + * Filters a Set based on a predicate function. + * + * This function takes a Set and a predicate function, and returns a new Set containing + * only the elements for which the predicate function returns true. + * + * @template T - The type of elements in the Set. + * @param {Set} set - The Set to filter. + * @param {(value: T, value2: T, set: Set) => boolean} callback - A predicate function that tests each element. + * @returns {Set} A new Set containing only the elements that satisfy the predicate. + * + * @example + * const set = new Set([1, 2, 3, 4, 5]); + * const result = filter(set, (value) => value > 2); + * // result will be: + * // Set(3) { 3, 4, 5 } + */ +declare function filter(set: Set, callback: (value: T, value2: T, set: Set) => boolean): Set; +//#endregion +export { filter }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/set/filter.js b/tools/ui/node_modules/es-toolkit/dist/set/filter.js new file mode 100644 index 0000000000000000000000000000000000000000..3ad9f46fc304eced8f5caba3000bce8c82d817ef --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/filter.js @@ -0,0 +1,25 @@ +//#region src/set/filter.ts +/** +* Filters a Set based on a predicate function. +* +* This function takes a Set and a predicate function, and returns a new Set containing +* only the elements for which the predicate function returns true. +* +* @template T - The type of elements in the Set. +* @param {Set} set - The Set to filter. +* @param {(value: T, value2: T, set: Set) => boolean} callback - A predicate function that tests each element. +* @returns {Set} A new Set containing only the elements that satisfy the predicate. +* +* @example +* const set = new Set([1, 2, 3, 4, 5]); +* const result = filter(set, (value) => value > 2); +* // result will be: +* // Set(3) { 3, 4, 5 } +*/ +function filter(set, callback) { + const result = /* @__PURE__ */ new Set(); + for (const value of set) if (callback(value, value, set)) result.add(value); + return result; +} +//#endregion +exports.filter = filter; diff --git a/tools/ui/node_modules/es-toolkit/dist/set/filter.mjs b/tools/ui/node_modules/es-toolkit/dist/set/filter.mjs new file mode 100644 index 0000000000000000000000000000000000000000..9a4b3f8d2b2d19950e4e5667230c3eb040dd5198 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/filter.mjs @@ -0,0 +1,25 @@ +//#region src/set/filter.ts +/** +* Filters a Set based on a predicate function. +* +* This function takes a Set and a predicate function, and returns a new Set containing +* only the elements for which the predicate function returns true. +* +* @template T - The type of elements in the Set. +* @param {Set} set - The Set to filter. +* @param {(value: T, value2: T, set: Set) => boolean} callback - A predicate function that tests each element. +* @returns {Set} A new Set containing only the elements that satisfy the predicate. +* +* @example +* const set = new Set([1, 2, 3, 4, 5]); +* const result = filter(set, (value) => value > 2); +* // result will be: +* // Set(3) { 3, 4, 5 } +*/ +function filter(set, callback) { + const result = /* @__PURE__ */ new Set(); + for (const value of set) if (callback(value, value, set)) result.add(value); + return result; +} +//#endregion +export { filter }; diff --git a/tools/ui/node_modules/es-toolkit/dist/set/find.d.mts b/tools/ui/node_modules/es-toolkit/dist/set/find.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..85abb4b5c6ed9fc735e42e162755b6fa4cfc35a8 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/find.d.mts @@ -0,0 +1,25 @@ +//#region src/set/find.d.ts +/** + * Finds the first element in a Set for which the predicate function returns true. + * + * This function iterates through the elements of the Set and returns the first + * element for which the predicate function returns true. If no element satisfies the predicate, + * it returns undefined. + * + * @template T - The type of elements in the Set. + * @param {Set} set - The Set to search. + * @param {(value: T, value2: T, set: Set) => boolean} doesMatch - A predicate function that tests each element. + * @returns {T | undefined} The first element that satisfies the predicate, or undefined if none found. + * + * @example + * const set = new Set([ + * { name: 'apple', quantity: 10 }, + * { name: 'banana', quantity: 5 }, + * { name: 'grape', quantity: 15 } + * ]); + * const result = find(set, (value) => value.quantity > 10); + * // result will be: { name: 'grape', quantity: 15 } + */ +declare function find(set: Set, doesMatch: (value: T, value2: T, set: Set) => boolean): T | undefined; +//#endregion +export { find }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/set/find.d.ts b/tools/ui/node_modules/es-toolkit/dist/set/find.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..85abb4b5c6ed9fc735e42e162755b6fa4cfc35a8 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/find.d.ts @@ -0,0 +1,25 @@ +//#region src/set/find.d.ts +/** + * Finds the first element in a Set for which the predicate function returns true. + * + * This function iterates through the elements of the Set and returns the first + * element for which the predicate function returns true. If no element satisfies the predicate, + * it returns undefined. + * + * @template T - The type of elements in the Set. + * @param {Set} set - The Set to search. + * @param {(value: T, value2: T, set: Set) => boolean} doesMatch - A predicate function that tests each element. + * @returns {T | undefined} The first element that satisfies the predicate, or undefined if none found. + * + * @example + * const set = new Set([ + * { name: 'apple', quantity: 10 }, + * { name: 'banana', quantity: 5 }, + * { name: 'grape', quantity: 15 } + * ]); + * const result = find(set, (value) => value.quantity > 10); + * // result will be: { name: 'grape', quantity: 15 } + */ +declare function find(set: Set, doesMatch: (value: T, value2: T, set: Set) => boolean): T | undefined; +//#endregion +export { find }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/set/find.js b/tools/ui/node_modules/es-toolkit/dist/set/find.js new file mode 100644 index 0000000000000000000000000000000000000000..5539ae0ed4379339e87fde0dca42bea02e2318b5 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/find.js @@ -0,0 +1,27 @@ +//#region src/set/find.ts +/** +* Finds the first element in a Set for which the predicate function returns true. +* +* This function iterates through the elements of the Set and returns the first +* element for which the predicate function returns true. If no element satisfies the predicate, +* it returns undefined. +* +* @template T - The type of elements in the Set. +* @param {Set} set - The Set to search. +* @param {(value: T, value2: T, set: Set) => boolean} doesMatch - A predicate function that tests each element. +* @returns {T | undefined} The first element that satisfies the predicate, or undefined if none found. +* +* @example +* const set = new Set([ +* { name: 'apple', quantity: 10 }, +* { name: 'banana', quantity: 5 }, +* { name: 'grape', quantity: 15 } +* ]); +* const result = find(set, (value) => value.quantity > 10); +* // result will be: { name: 'grape', quantity: 15 } +*/ +function find(set, doesMatch) { + for (const value of set) if (doesMatch(value, value, set)) return value; +} +//#endregion +exports.find = find; diff --git a/tools/ui/node_modules/es-toolkit/dist/set/find.mjs b/tools/ui/node_modules/es-toolkit/dist/set/find.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c6fca8c4f33102ab3d89452a2a738aa789bd638a --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/find.mjs @@ -0,0 +1,27 @@ +//#region src/set/find.ts +/** +* Finds the first element in a Set for which the predicate function returns true. +* +* This function iterates through the elements of the Set and returns the first +* element for which the predicate function returns true. If no element satisfies the predicate, +* it returns undefined. +* +* @template T - The type of elements in the Set. +* @param {Set} set - The Set to search. +* @param {(value: T, value2: T, set: Set) => boolean} doesMatch - A predicate function that tests each element. +* @returns {T | undefined} The first element that satisfies the predicate, or undefined if none found. +* +* @example +* const set = new Set([ +* { name: 'apple', quantity: 10 }, +* { name: 'banana', quantity: 5 }, +* { name: 'grape', quantity: 15 } +* ]); +* const result = find(set, (value) => value.quantity > 10); +* // result will be: { name: 'grape', quantity: 15 } +*/ +function find(set, doesMatch) { + for (const value of set) if (doesMatch(value, value, set)) return value; +} +//#endregion +export { find }; diff --git a/tools/ui/node_modules/es-toolkit/dist/set/forEach.d.mts b/tools/ui/node_modules/es-toolkit/dist/set/forEach.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..571dbb85d910329066bc31a1772fa5db70ad0030 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/forEach.d.mts @@ -0,0 +1,26 @@ +//#region src/set/forEach.d.ts +/** + * Executes a provided function once for each element in a Set. + * + * This function iterates through all elements of the Set and executes the callback function + * for each element. The callback receives the value twice (for consistency with Map.forEach) + * and the Set itself as arguments. + * + * @template T - The type of elements in the Set. + * @param {Set} set - The Set to iterate over. + * @param {(value: T, value2: T, set: Set) => void} callback - A function to execute for each element. + * @returns {void} + * + * @example + * const set = new Set([1, 2, 3]); + * forEach(set, (value) => { + * console.log(value * 2); + * }); + * // Output: + * // 2 + * // 4 + * // 6 + */ +declare function forEach(set: Set, callback: (value: T, value2: T, set: Set) => void): void; +//#endregion +export { forEach }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/set/forEach.d.ts b/tools/ui/node_modules/es-toolkit/dist/set/forEach.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..571dbb85d910329066bc31a1772fa5db70ad0030 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/forEach.d.ts @@ -0,0 +1,26 @@ +//#region src/set/forEach.d.ts +/** + * Executes a provided function once for each element in a Set. + * + * This function iterates through all elements of the Set and executes the callback function + * for each element. The callback receives the value twice (for consistency with Map.forEach) + * and the Set itself as arguments. + * + * @template T - The type of elements in the Set. + * @param {Set} set - The Set to iterate over. + * @param {(value: T, value2: T, set: Set) => void} callback - A function to execute for each element. + * @returns {void} + * + * @example + * const set = new Set([1, 2, 3]); + * forEach(set, (value) => { + * console.log(value * 2); + * }); + * // Output: + * // 2 + * // 4 + * // 6 + */ +declare function forEach(set: Set, callback: (value: T, value2: T, set: Set) => void): void; +//#endregion +export { forEach }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/set/forEach.js b/tools/ui/node_modules/es-toolkit/dist/set/forEach.js new file mode 100644 index 0000000000000000000000000000000000000000..3c6d5e2728b404777d8aeab63896f9c224f425e6 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/forEach.js @@ -0,0 +1,28 @@ +//#region src/set/forEach.ts +/** +* Executes a provided function once for each element in a Set. +* +* This function iterates through all elements of the Set and executes the callback function +* for each element. The callback receives the value twice (for consistency with Map.forEach) +* and the Set itself as arguments. +* +* @template T - The type of elements in the Set. +* @param {Set} set - The Set to iterate over. +* @param {(value: T, value2: T, set: Set) => void} callback - A function to execute for each element. +* @returns {void} +* +* @example +* const set = new Set([1, 2, 3]); +* forEach(set, (value) => { +* console.log(value * 2); +* }); +* // Output: +* // 2 +* // 4 +* // 6 +*/ +function forEach(set, callback) { + for (const value of set) callback(value, value, set); +} +//#endregion +exports.forEach = forEach; diff --git a/tools/ui/node_modules/es-toolkit/dist/set/forEach.mjs b/tools/ui/node_modules/es-toolkit/dist/set/forEach.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3e4a1e45a0d3d3d240f4b6fb1a0362c236edd19b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/forEach.mjs @@ -0,0 +1,28 @@ +//#region src/set/forEach.ts +/** +* Executes a provided function once for each element in a Set. +* +* This function iterates through all elements of the Set and executes the callback function +* for each element. The callback receives the value twice (for consistency with Map.forEach) +* and the Set itself as arguments. +* +* @template T - The type of elements in the Set. +* @param {Set} set - The Set to iterate over. +* @param {(value: T, value2: T, set: Set) => void} callback - A function to execute for each element. +* @returns {void} +* +* @example +* const set = new Set([1, 2, 3]); +* forEach(set, (value) => { +* console.log(value * 2); +* }); +* // Output: +* // 2 +* // 4 +* // 6 +*/ +function forEach(set, callback) { + for (const value of set) callback(value, value, set); +} +//#endregion +export { forEach }; diff --git a/tools/ui/node_modules/es-toolkit/dist/set/index.d.mts b/tools/ui/node_modules/es-toolkit/dist/set/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..9a6c71d0f7ee4d9d39119311b9fe344688fe2c85 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/index.d.mts @@ -0,0 +1,10 @@ +import { countBy } from "./countBy.mjs"; +import { every } from "./every.mjs"; +import { filter } from "./filter.mjs"; +import { find } from "./find.mjs"; +import { forEach } from "./forEach.mjs"; +import { keyBy } from "./keyBy.mjs"; +import { map } from "./map.mjs"; +import { reduce } from "./reduce.mjs"; +import { some } from "./some.mjs"; +export { countBy, every, filter, find, forEach, keyBy, map, reduce, some }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/set/index.d.ts b/tools/ui/node_modules/es-toolkit/dist/set/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..34d18980f6c48339a6173199ae2c23eadc7baadf --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/index.d.ts @@ -0,0 +1,10 @@ +import { countBy } from "./countBy.js"; +import { every } from "./every.js"; +import { filter } from "./filter.js"; +import { find } from "./find.js"; +import { forEach } from "./forEach.js"; +import { keyBy } from "./keyBy.js"; +import { map } from "./map.js"; +import { reduce } from "./reduce.js"; +import { some } from "./some.js"; +export { countBy, every, filter, find, forEach, keyBy, map, reduce, some }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/set/index.js b/tools/ui/node_modules/es-toolkit/dist/set/index.js new file mode 100644 index 0000000000000000000000000000000000000000..fce6dd763f0ad0a0f73c0d5982ea85a2798e5c0f --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/index.js @@ -0,0 +1,19 @@ +Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); +const require_countBy = require("./countBy.js"); +const require_every = require("./every.js"); +const require_filter = require("./filter.js"); +const require_find = require("./find.js"); +const require_forEach = require("./forEach.js"); +const require_keyBy = require("./keyBy.js"); +const require_map = require("./map.js"); +const require_reduce = require("./reduce.js"); +const require_some = require("./some.js"); +exports.countBy = require_countBy.countBy; +exports.every = require_every.every; +exports.filter = require_filter.filter; +exports.find = require_find.find; +exports.forEach = require_forEach.forEach; +exports.keyBy = require_keyBy.keyBy; +exports.map = require_map.map; +exports.reduce = require_reduce.reduce; +exports.some = require_some.some; diff --git a/tools/ui/node_modules/es-toolkit/dist/set/index.mjs b/tools/ui/node_modules/es-toolkit/dist/set/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b2054f4842d17f3543f767a425f1125c84f702c6 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/index.mjs @@ -0,0 +1,10 @@ +import { countBy } from "./countBy.mjs"; +import { every } from "./every.mjs"; +import { filter } from "./filter.mjs"; +import { find } from "./find.mjs"; +import { forEach } from "./forEach.mjs"; +import { keyBy } from "./keyBy.mjs"; +import { map } from "./map.mjs"; +import { reduce } from "./reduce.mjs"; +import { some } from "./some.mjs"; +export { countBy, every, filter, find, forEach, keyBy, map, reduce, some }; diff --git a/tools/ui/node_modules/es-toolkit/dist/set/keyBy.d.mts b/tools/ui/node_modules/es-toolkit/dist/set/keyBy.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..22f2ecd0de8f75a145f8bf00151ecf8313db62da --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/keyBy.d.mts @@ -0,0 +1,31 @@ +//#region src/set/keyBy.d.ts +/** + * Maps each element of a Set based on a provided key-generating function. + * + * This function takes a Set and a function that generates a key from each value. + * It returns a new Map where the keys are generated by the key function and the values are + * the corresponding values from the original set. If multiple elements produce the same key, + * the last value encountered will be used. + * + * @template T - The type of elements in the Set. + * @template K - The type of keys to produce in the returned Map. + * @param {Set} set - The set of elements to be mapped. + * @param {(value: T, value2: T, set: Set) => K} getKeyFromValue - A function that generates a key from a value. + * @returns {Map} A Map where the generated keys are mapped to each element's value. + * + * @example + * const set = new Set([ + * { type: 'fruit', name: 'apple' }, + * { type: 'fruit', name: 'banana' }, + * { type: 'vegetable', name: 'carrot' } + * ]); + * const result = keyBy(set, item => item.type); + * // result will be: + * // Map(2) { + * // 'fruit' => { type: 'fruit', name: 'banana' }, + * // 'vegetable' => { type: 'vegetable', name: 'carrot' } + * // } + */ +declare function keyBy(set: Set, getKeyFromValue: (value: T, value2: T, set: Set) => K): Map; +//#endregion +export { keyBy }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/set/keyBy.d.ts b/tools/ui/node_modules/es-toolkit/dist/set/keyBy.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..22f2ecd0de8f75a145f8bf00151ecf8313db62da --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/keyBy.d.ts @@ -0,0 +1,31 @@ +//#region src/set/keyBy.d.ts +/** + * Maps each element of a Set based on a provided key-generating function. + * + * This function takes a Set and a function that generates a key from each value. + * It returns a new Map where the keys are generated by the key function and the values are + * the corresponding values from the original set. If multiple elements produce the same key, + * the last value encountered will be used. + * + * @template T - The type of elements in the Set. + * @template K - The type of keys to produce in the returned Map. + * @param {Set} set - The set of elements to be mapped. + * @param {(value: T, value2: T, set: Set) => K} getKeyFromValue - A function that generates a key from a value. + * @returns {Map} A Map where the generated keys are mapped to each element's value. + * + * @example + * const set = new Set([ + * { type: 'fruit', name: 'apple' }, + * { type: 'fruit', name: 'banana' }, + * { type: 'vegetable', name: 'carrot' } + * ]); + * const result = keyBy(set, item => item.type); + * // result will be: + * // Map(2) { + * // 'fruit' => { type: 'fruit', name: 'banana' }, + * // 'vegetable' => { type: 'vegetable', name: 'carrot' } + * // } + */ +declare function keyBy(set: Set, getKeyFromValue: (value: T, value2: T, set: Set) => K): Map; +//#endregion +export { keyBy }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/set/keyBy.js b/tools/ui/node_modules/es-toolkit/dist/set/keyBy.js new file mode 100644 index 0000000000000000000000000000000000000000..b238a2d982963ec1828b145767307644af776a83 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/keyBy.js @@ -0,0 +1,38 @@ +//#region src/set/keyBy.ts +/** +* Maps each element of a Set based on a provided key-generating function. +* +* This function takes a Set and a function that generates a key from each value. +* It returns a new Map where the keys are generated by the key function and the values are +* the corresponding values from the original set. If multiple elements produce the same key, +* the last value encountered will be used. +* +* @template T - The type of elements in the Set. +* @template K - The type of keys to produce in the returned Map. +* @param {Set} set - The set of elements to be mapped. +* @param {(value: T, value2: T, set: Set) => K} getKeyFromValue - A function that generates a key from a value. +* @returns {Map} A Map where the generated keys are mapped to each element's value. +* +* @example +* const set = new Set([ +* { type: 'fruit', name: 'apple' }, +* { type: 'fruit', name: 'banana' }, +* { type: 'vegetable', name: 'carrot' } +* ]); +* const result = keyBy(set, item => item.type); +* // result will be: +* // Map(2) { +* // 'fruit' => { type: 'fruit', name: 'banana' }, +* // 'vegetable' => { type: 'vegetable', name: 'carrot' } +* // } +*/ +function keyBy(set, getKeyFromValue) { + const result = /* @__PURE__ */ new Map(); + for (const value of set) { + const newKey = getKeyFromValue(value, value, set); + result.set(newKey, value); + } + return result; +} +//#endregion +exports.keyBy = keyBy; diff --git a/tools/ui/node_modules/es-toolkit/dist/set/keyBy.mjs b/tools/ui/node_modules/es-toolkit/dist/set/keyBy.mjs new file mode 100644 index 0000000000000000000000000000000000000000..823e5ffa49b5b218822f28ba21633135c3da774a --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/keyBy.mjs @@ -0,0 +1,38 @@ +//#region src/set/keyBy.ts +/** +* Maps each element of a Set based on a provided key-generating function. +* +* This function takes a Set and a function that generates a key from each value. +* It returns a new Map where the keys are generated by the key function and the values are +* the corresponding values from the original set. If multiple elements produce the same key, +* the last value encountered will be used. +* +* @template T - The type of elements in the Set. +* @template K - The type of keys to produce in the returned Map. +* @param {Set} set - The set of elements to be mapped. +* @param {(value: T, value2: T, set: Set) => K} getKeyFromValue - A function that generates a key from a value. +* @returns {Map} A Map where the generated keys are mapped to each element's value. +* +* @example +* const set = new Set([ +* { type: 'fruit', name: 'apple' }, +* { type: 'fruit', name: 'banana' }, +* { type: 'vegetable', name: 'carrot' } +* ]); +* const result = keyBy(set, item => item.type); +* // result will be: +* // Map(2) { +* // 'fruit' => { type: 'fruit', name: 'banana' }, +* // 'vegetable' => { type: 'vegetable', name: 'carrot' } +* // } +*/ +function keyBy(set, getKeyFromValue) { + const result = /* @__PURE__ */ new Map(); + for (const value of set) { + const newKey = getKeyFromValue(value, value, set); + result.set(newKey, value); + } + return result; +} +//#endregion +export { keyBy }; diff --git a/tools/ui/node_modules/es-toolkit/dist/set/map.d.mts b/tools/ui/node_modules/es-toolkit/dist/set/map.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..69379243347cbcbff6c35a7b77ca3e266486bbb5 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/map.d.mts @@ -0,0 +1,22 @@ +//#region src/set/map.d.ts +/** + * Creates a new Set with elements transformed by the provided function. + * + * This function takes a Set and a function that generates a new value from each element. + * It returns a new Set where the elements are the result of applying the function to each element. + * + * @template T - The type of elements in the input Set. + * @template U - The type of elements in the output Set. + * @param {Set} set - The Set to transform. + * @param {(value: T, value2: T, set: Set) => U} getNewValue - A function that generates a new value from an element. + * @returns {Set} A new Set with transformed elements. + * + * @example + * const set = new Set([1, 2, 3]); + * const result = map(set, (value) => value * 2); + * // result will be: + * // Set(3) { 2, 4, 6 } + */ +declare function map(set: Set, getNewValue: (value: T, value2: T, set: Set) => U): Set; +//#endregion +export { map }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/set/map.d.ts b/tools/ui/node_modules/es-toolkit/dist/set/map.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..69379243347cbcbff6c35a7b77ca3e266486bbb5 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/map.d.ts @@ -0,0 +1,22 @@ +//#region src/set/map.d.ts +/** + * Creates a new Set with elements transformed by the provided function. + * + * This function takes a Set and a function that generates a new value from each element. + * It returns a new Set where the elements are the result of applying the function to each element. + * + * @template T - The type of elements in the input Set. + * @template U - The type of elements in the output Set. + * @param {Set} set - The Set to transform. + * @param {(value: T, value2: T, set: Set) => U} getNewValue - A function that generates a new value from an element. + * @returns {Set} A new Set with transformed elements. + * + * @example + * const set = new Set([1, 2, 3]); + * const result = map(set, (value) => value * 2); + * // result will be: + * // Set(3) { 2, 4, 6 } + */ +declare function map(set: Set, getNewValue: (value: T, value2: T, set: Set) => U): Set; +//#endregion +export { map }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/set/map.js b/tools/ui/node_modules/es-toolkit/dist/set/map.js new file mode 100644 index 0000000000000000000000000000000000000000..06d505bba87878199715850e0569d2c96dfb1483 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/map.js @@ -0,0 +1,29 @@ +//#region src/set/map.ts +/** +* Creates a new Set with elements transformed by the provided function. +* +* This function takes a Set and a function that generates a new value from each element. +* It returns a new Set where the elements are the result of applying the function to each element. +* +* @template T - The type of elements in the input Set. +* @template U - The type of elements in the output Set. +* @param {Set} set - The Set to transform. +* @param {(value: T, value2: T, set: Set) => U} getNewValue - A function that generates a new value from an element. +* @returns {Set} A new Set with transformed elements. +* +* @example +* const set = new Set([1, 2, 3]); +* const result = map(set, (value) => value * 2); +* // result will be: +* // Set(3) { 2, 4, 6 } +*/ +function map(set, getNewValue) { + const result = /* @__PURE__ */ new Set(); + for (const value of set) { + const newValue = getNewValue(value, value, set); + result.add(newValue); + } + return result; +} +//#endregion +exports.map = map; diff --git a/tools/ui/node_modules/es-toolkit/dist/set/map.mjs b/tools/ui/node_modules/es-toolkit/dist/set/map.mjs new file mode 100644 index 0000000000000000000000000000000000000000..25a7d4a9c74e8be29ed052e8985156b8ec65771c --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/map.mjs @@ -0,0 +1,29 @@ +//#region src/set/map.ts +/** +* Creates a new Set with elements transformed by the provided function. +* +* This function takes a Set and a function that generates a new value from each element. +* It returns a new Set where the elements are the result of applying the function to each element. +* +* @template T - The type of elements in the input Set. +* @template U - The type of elements in the output Set. +* @param {Set} set - The Set to transform. +* @param {(value: T, value2: T, set: Set) => U} getNewValue - A function that generates a new value from an element. +* @returns {Set} A new Set with transformed elements. +* +* @example +* const set = new Set([1, 2, 3]); +* const result = map(set, (value) => value * 2); +* // result will be: +* // Set(3) { 2, 4, 6 } +*/ +function map(set, getNewValue) { + const result = /* @__PURE__ */ new Set(); + for (const value of set) { + const newValue = getNewValue(value, value, set); + result.add(newValue); + } + return result; +} +//#endregion +export { map }; diff --git a/tools/ui/node_modules/es-toolkit/dist/set/reduce.d.mts b/tools/ui/node_modules/es-toolkit/dist/set/reduce.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..4fa7ba15e5b8e0bd5e99d47951172e8cf3f635f1 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/reduce.d.mts @@ -0,0 +1,29 @@ +//#region src/set/reduce.d.ts +/** + * Reduces a Set to a single value by iterating through its elements and applying a callback function. + * + * This function iterates through all elements of the Set and applies the callback function to each element, + * accumulating the result. If an initial value is provided, it is used as the starting accumulator value. + * If no initial value is provided and the Set is empty, a TypeError is thrown. + * + * @template T - The type of elements in the Set. + * @template A - The type of the accumulator. + * @param {Set} set - The Set to reduce. + * @param {(accumulator: A, value: T, value2: T, set: Set) => A} callback - A function that processes each element and updates the accumulator. + * @param {A} [initialValue] - The initial value for the accumulator. If not provided, the first element in the Set is used. + * @returns {A} The final accumulated value. + * @throws {TypeError} If the Set is empty and no initial value is provided. + * + * @example + * const set = new Set([1, 2, 3]); + * const result = reduce(set, (acc, value) => acc + value, 0); + * // result will be: 6 + * + * @example + * const set = new Set([10, 20]); + * const result = reduce(set, (acc, value) => acc + value); + * // result will be: 30 (starts with first value 10) + */ +declare function reduce(set: Set, callback: (accumulator: A, value: T, value2: T, set: Set) => A, initialValue?: A): A; +//#endregion +export { reduce }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/set/reduce.d.ts b/tools/ui/node_modules/es-toolkit/dist/set/reduce.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4fa7ba15e5b8e0bd5e99d47951172e8cf3f635f1 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/reduce.d.ts @@ -0,0 +1,29 @@ +//#region src/set/reduce.d.ts +/** + * Reduces a Set to a single value by iterating through its elements and applying a callback function. + * + * This function iterates through all elements of the Set and applies the callback function to each element, + * accumulating the result. If an initial value is provided, it is used as the starting accumulator value. + * If no initial value is provided and the Set is empty, a TypeError is thrown. + * + * @template T - The type of elements in the Set. + * @template A - The type of the accumulator. + * @param {Set} set - The Set to reduce. + * @param {(accumulator: A, value: T, value2: T, set: Set) => A} callback - A function that processes each element and updates the accumulator. + * @param {A} [initialValue] - The initial value for the accumulator. If not provided, the first element in the Set is used. + * @returns {A} The final accumulated value. + * @throws {TypeError} If the Set is empty and no initial value is provided. + * + * @example + * const set = new Set([1, 2, 3]); + * const result = reduce(set, (acc, value) => acc + value, 0); + * // result will be: 6 + * + * @example + * const set = new Set([10, 20]); + * const result = reduce(set, (acc, value) => acc + value); + * // result will be: 30 (starts with first value 10) + */ +declare function reduce(set: Set, callback: (accumulator: A, value: T, value2: T, set: Set) => A, initialValue?: A): A; +//#endregion +export { reduce }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/set/reduce.js b/tools/ui/node_modules/es-toolkit/dist/set/reduce.js new file mode 100644 index 0000000000000000000000000000000000000000..ce50afd30d7f0a9d840f99a04294c6c51db5177e --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/reduce.js @@ -0,0 +1,35 @@ +//#region src/set/reduce.ts +/** +* Reduces a Set to a single value by iterating through its elements and applying a callback function. +* +* This function iterates through all elements of the Set and applies the callback function to each element, +* accumulating the result. If an initial value is provided, it is used as the starting accumulator value. +* If no initial value is provided and the Set is empty, a TypeError is thrown. +* +* @template T - The type of elements in the Set. +* @template A - The type of the accumulator. +* @param {Set} set - The Set to reduce. +* @param {(accumulator: A, value: T, value2: T, set: Set) => A} callback - A function that processes each element and updates the accumulator. +* @param {A} [initialValue] - The initial value for the accumulator. If not provided, the first element in the Set is used. +* @returns {A} The final accumulated value. +* @throws {TypeError} If the Set is empty and no initial value is provided. +* +* @example +* const set = new Set([1, 2, 3]); +* const result = reduce(set, (acc, value) => acc + value, 0); +* // result will be: 6 +* +* @example +* const set = new Set([10, 20]); +* const result = reduce(set, (acc, value) => acc + value); +* // result will be: 30 (starts with first value 10) +*/ +function reduce(set, callback, initialValue) { + if (initialValue == null && set.size === 0) throw new TypeError("Reduce of empty set with no initial value"); + let accumulator = initialValue; + for (const value of set) if (accumulator == null) accumulator = value; + else accumulator = callback(accumulator, value, value, set); + return accumulator; +} +//#endregion +exports.reduce = reduce; diff --git a/tools/ui/node_modules/es-toolkit/dist/set/reduce.mjs b/tools/ui/node_modules/es-toolkit/dist/set/reduce.mjs new file mode 100644 index 0000000000000000000000000000000000000000..fcd5ce503143cfb337165e8ef0d7f0a1abd2d18a --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/reduce.mjs @@ -0,0 +1,35 @@ +//#region src/set/reduce.ts +/** +* Reduces a Set to a single value by iterating through its elements and applying a callback function. +* +* This function iterates through all elements of the Set and applies the callback function to each element, +* accumulating the result. If an initial value is provided, it is used as the starting accumulator value. +* If no initial value is provided and the Set is empty, a TypeError is thrown. +* +* @template T - The type of elements in the Set. +* @template A - The type of the accumulator. +* @param {Set} set - The Set to reduce. +* @param {(accumulator: A, value: T, value2: T, set: Set) => A} callback - A function that processes each element and updates the accumulator. +* @param {A} [initialValue] - The initial value for the accumulator. If not provided, the first element in the Set is used. +* @returns {A} The final accumulated value. +* @throws {TypeError} If the Set is empty and no initial value is provided. +* +* @example +* const set = new Set([1, 2, 3]); +* const result = reduce(set, (acc, value) => acc + value, 0); +* // result will be: 6 +* +* @example +* const set = new Set([10, 20]); +* const result = reduce(set, (acc, value) => acc + value); +* // result will be: 30 (starts with first value 10) +*/ +function reduce(set, callback, initialValue) { + if (initialValue == null && set.size === 0) throw new TypeError("Reduce of empty set with no initial value"); + let accumulator = initialValue; + for (const value of set) if (accumulator == null) accumulator = value; + else accumulator = callback(accumulator, value, value, set); + return accumulator; +} +//#endregion +export { reduce }; diff --git a/tools/ui/node_modules/es-toolkit/dist/set/some.d.mts b/tools/ui/node_modules/es-toolkit/dist/set/some.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..d0f7ec0b95235b7a77d93eccfffb7526c32b032c --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/some.d.mts @@ -0,0 +1,24 @@ +//#region src/set/some.d.ts +/** + * Tests whether at least one element in a Set satisfies the provided predicate function. + * + * This function iterates through the elements of the Set and checks if the predicate function + * returns true for at least one element. It returns true if any element satisfies the predicate, + * and false otherwise. + * + * @template T - The type of elements in the Set. + * @param {Set} set - The Set to test. + * @param {(value: T, value2: T, set: Set) => boolean} doesMatch - A predicate function that tests each element. + * @returns {boolean} true if at least one element satisfies the predicate, false otherwise. + * + * @example + * const set = new Set([1, 2, 3]); + * const result = some(set, (value) => value > 2); + * // result will be: true + * + * const result2 = some(set, (value) => value > 5); + * // result2 will be: false + */ +declare function some(set: Set, doesMatch: (value: T, value2: T, set: Set) => boolean): boolean; +//#endregion +export { some }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/set/some.d.ts b/tools/ui/node_modules/es-toolkit/dist/set/some.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d0f7ec0b95235b7a77d93eccfffb7526c32b032c --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/some.d.ts @@ -0,0 +1,24 @@ +//#region src/set/some.d.ts +/** + * Tests whether at least one element in a Set satisfies the provided predicate function. + * + * This function iterates through the elements of the Set and checks if the predicate function + * returns true for at least one element. It returns true if any element satisfies the predicate, + * and false otherwise. + * + * @template T - The type of elements in the Set. + * @param {Set} set - The Set to test. + * @param {(value: T, value2: T, set: Set) => boolean} doesMatch - A predicate function that tests each element. + * @returns {boolean} true if at least one element satisfies the predicate, false otherwise. + * + * @example + * const set = new Set([1, 2, 3]); + * const result = some(set, (value) => value > 2); + * // result will be: true + * + * const result2 = some(set, (value) => value > 5); + * // result2 will be: false + */ +declare function some(set: Set, doesMatch: (value: T, value2: T, set: Set) => boolean): boolean; +//#endregion +export { some }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/set/some.js b/tools/ui/node_modules/es-toolkit/dist/set/some.js new file mode 100644 index 0000000000000000000000000000000000000000..08475dd8aed9a078eab6069eca3652865b34bcc0 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/some.js @@ -0,0 +1,27 @@ +//#region src/set/some.ts +/** +* Tests whether at least one element in a Set satisfies the provided predicate function. +* +* This function iterates through the elements of the Set and checks if the predicate function +* returns true for at least one element. It returns true if any element satisfies the predicate, +* and false otherwise. +* +* @template T - The type of elements in the Set. +* @param {Set} set - The Set to test. +* @param {(value: T, value2: T, set: Set) => boolean} doesMatch - A predicate function that tests each element. +* @returns {boolean} true if at least one element satisfies the predicate, false otherwise. +* +* @example +* const set = new Set([1, 2, 3]); +* const result = some(set, (value) => value > 2); +* // result will be: true +* +* const result2 = some(set, (value) => value > 5); +* // result2 will be: false +*/ +function some(set, doesMatch) { + for (const value of set) if (doesMatch(value, value, set)) return true; + return false; +} +//#endregion +exports.some = some; diff --git a/tools/ui/node_modules/es-toolkit/dist/set/some.mjs b/tools/ui/node_modules/es-toolkit/dist/set/some.mjs new file mode 100644 index 0000000000000000000000000000000000000000..9ac78f47c3e32cc36a2128b5b21b98f33b9c79a2 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/set/some.mjs @@ -0,0 +1,27 @@ +//#region src/set/some.ts +/** +* Tests whether at least one element in a Set satisfies the provided predicate function. +* +* This function iterates through the elements of the Set and checks if the predicate function +* returns true for at least one element. It returns true if any element satisfies the predicate, +* and false otherwise. +* +* @template T - The type of elements in the Set. +* @param {Set} set - The Set to test. +* @param {(value: T, value2: T, set: Set) => boolean} doesMatch - A predicate function that tests each element. +* @returns {boolean} true if at least one element satisfies the predicate, false otherwise. +* +* @example +* const set = new Set([1, 2, 3]); +* const result = some(set, (value) => value > 2); +* // result will be: true +* +* const result2 = some(set, (value) => value > 5); +* // result2 will be: false +*/ +function some(set, doesMatch) { + for (const value of set) if (doesMatch(value, value, set)) return true; + return false; +} +//#endregion +export { some }; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/camelCase.d.mts b/tools/ui/node_modules/es-toolkit/dist/string/camelCase.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..2e8bddde7d4091bdb956451f28501673a7781ea2 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/camelCase.d.mts @@ -0,0 +1,20 @@ +//#region src/string/camelCase.d.ts +/** + * Converts a string to camel case. + * + * Camel case is the naming convention in which the first word is written in lowercase and + * each subsequent word begins with a capital letter, concatenated without any separator characters. + * + * @param {string} str - The string that is to be changed to camel case. + * @returns {string} - The converted string to camel case. + * + * @example + * const convertedStr1 = camelCase('camelCase') // returns 'camelCase' + * const convertedStr2 = camelCase('some whitespace') // returns 'someWhitespace' + * const convertedStr3 = camelCase('hyphen-text') // returns 'hyphenText' + * const convertedStr4 = camelCase('HTTPRequest') // returns 'httpRequest' + * const convertedStr5 = camelCase('Keep unicode 😅') // returns 'keepUnicode😅' + */ +declare function camelCase(str: string): string; +//#endregion +export { camelCase }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/camelCase.d.ts b/tools/ui/node_modules/es-toolkit/dist/string/camelCase.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2e8bddde7d4091bdb956451f28501673a7781ea2 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/camelCase.d.ts @@ -0,0 +1,20 @@ +//#region src/string/camelCase.d.ts +/** + * Converts a string to camel case. + * + * Camel case is the naming convention in which the first word is written in lowercase and + * each subsequent word begins with a capital letter, concatenated without any separator characters. + * + * @param {string} str - The string that is to be changed to camel case. + * @returns {string} - The converted string to camel case. + * + * @example + * const convertedStr1 = camelCase('camelCase') // returns 'camelCase' + * const convertedStr2 = camelCase('some whitespace') // returns 'someWhitespace' + * const convertedStr3 = camelCase('hyphen-text') // returns 'hyphenText' + * const convertedStr4 = camelCase('HTTPRequest') // returns 'httpRequest' + * const convertedStr5 = camelCase('Keep unicode 😅') // returns 'keepUnicode😅' + */ +declare function camelCase(str: string): string; +//#endregion +export { camelCase }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/camelCase.js b/tools/ui/node_modules/es-toolkit/dist/string/camelCase.js new file mode 100644 index 0000000000000000000000000000000000000000..c7effffc04ea181b803e0a557e8e182a5a1bc50d --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/camelCase.js @@ -0,0 +1,27 @@ +const require_capitalize = require("./capitalize.js"); +const require_words = require("./words.js"); +//#region src/string/camelCase.ts +/** +* Converts a string to camel case. +* +* Camel case is the naming convention in which the first word is written in lowercase and +* each subsequent word begins with a capital letter, concatenated without any separator characters. +* +* @param {string} str - The string that is to be changed to camel case. +* @returns {string} - The converted string to camel case. +* +* @example +* const convertedStr1 = camelCase('camelCase') // returns 'camelCase' +* const convertedStr2 = camelCase('some whitespace') // returns 'someWhitespace' +* const convertedStr3 = camelCase('hyphen-text') // returns 'hyphenText' +* const convertedStr4 = camelCase('HTTPRequest') // returns 'httpRequest' +* const convertedStr5 = camelCase('Keep unicode 😅') // returns 'keepUnicode😅' +*/ +function camelCase(str) { + const words$1 = require_words.words(str); + if (words$1.length === 0) return ""; + const [first, ...rest] = words$1; + return `${first.toLowerCase()}${rest.map((word) => require_capitalize.capitalize(word)).join("")}`; +} +//#endregion +exports.camelCase = camelCase; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/camelCase.mjs b/tools/ui/node_modules/es-toolkit/dist/string/camelCase.mjs new file mode 100644 index 0000000000000000000000000000000000000000..88861102bda5420a3ec91141ef69726d7122a297 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/camelCase.mjs @@ -0,0 +1,27 @@ +import { capitalize } from "./capitalize.mjs"; +import { words } from "./words.mjs"; +//#region src/string/camelCase.ts +/** +* Converts a string to camel case. +* +* Camel case is the naming convention in which the first word is written in lowercase and +* each subsequent word begins with a capital letter, concatenated without any separator characters. +* +* @param {string} str - The string that is to be changed to camel case. +* @returns {string} - The converted string to camel case. +* +* @example +* const convertedStr1 = camelCase('camelCase') // returns 'camelCase' +* const convertedStr2 = camelCase('some whitespace') // returns 'someWhitespace' +* const convertedStr3 = camelCase('hyphen-text') // returns 'hyphenText' +* const convertedStr4 = camelCase('HTTPRequest') // returns 'httpRequest' +* const convertedStr5 = camelCase('Keep unicode 😅') // returns 'keepUnicode😅' +*/ +function camelCase(str) { + const words$1 = words(str); + if (words$1.length === 0) return ""; + const [first, ...rest] = words$1; + return `${first.toLowerCase()}${rest.map((word) => capitalize(word)).join("")}`; +} +//#endregion +export { camelCase }; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/capitalize.d.mts b/tools/ui/node_modules/es-toolkit/dist/string/capitalize.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..964bc04f717d072e66b5092af89d112e38b488fd --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/capitalize.d.mts @@ -0,0 +1,16 @@ +//#region src/string/capitalize.d.ts +/** + * Converts the first character of string to upper case and the remaining to lower case. + * + * @template T - Literal type of the string. + * @param {T} str - The string to be converted to uppercase. + * @returns {Capitalize} - The capitalized string. + * + * @example + * const result = capitalize('fred') // returns 'Fred' + * const result2 = capitalize('FRED') // returns 'Fred' + */ +declare function capitalize(str: T): Capitalize; +type Capitalize = T extends `${infer F}${infer R}` ? `${Uppercase}${Lowercase}` : T; +//#endregion +export { capitalize }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/capitalize.d.ts b/tools/ui/node_modules/es-toolkit/dist/string/capitalize.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..964bc04f717d072e66b5092af89d112e38b488fd --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/capitalize.d.ts @@ -0,0 +1,16 @@ +//#region src/string/capitalize.d.ts +/** + * Converts the first character of string to upper case and the remaining to lower case. + * + * @template T - Literal type of the string. + * @param {T} str - The string to be converted to uppercase. + * @returns {Capitalize} - The capitalized string. + * + * @example + * const result = capitalize('fred') // returns 'Fred' + * const result2 = capitalize('FRED') // returns 'Fred' + */ +declare function capitalize(str: T): Capitalize; +type Capitalize = T extends `${infer F}${infer R}` ? `${Uppercase}${Lowercase}` : T; +//#endregion +export { capitalize }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/capitalize.js b/tools/ui/node_modules/es-toolkit/dist/string/capitalize.js new file mode 100644 index 0000000000000000000000000000000000000000..c0796d36bf3eeec1fb4eef41056c84c4cf31b28b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/capitalize.js @@ -0,0 +1,17 @@ +//#region src/string/capitalize.ts +/** +* Converts the first character of string to upper case and the remaining to lower case. +* +* @template T - Literal type of the string. +* @param {T} str - The string to be converted to uppercase. +* @returns {Capitalize} - The capitalized string. +* +* @example +* const result = capitalize('fred') // returns 'Fred' +* const result2 = capitalize('FRED') // returns 'Fred' +*/ +function capitalize(str) { + return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase(); +} +//#endregion +exports.capitalize = capitalize; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/capitalize.mjs b/tools/ui/node_modules/es-toolkit/dist/string/capitalize.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4dfd22f77e1d07488366930e43070ea12525ea3a --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/capitalize.mjs @@ -0,0 +1,17 @@ +//#region src/string/capitalize.ts +/** +* Converts the first character of string to upper case and the remaining to lower case. +* +* @template T - Literal type of the string. +* @param {T} str - The string to be converted to uppercase. +* @returns {Capitalize} - The capitalized string. +* +* @example +* const result = capitalize('fred') // returns 'Fred' +* const result2 = capitalize('FRED') // returns 'Fred' +*/ +function capitalize(str) { + return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase(); +} +//#endregion +export { capitalize }; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/constantCase.d.mts b/tools/ui/node_modules/es-toolkit/dist/string/constantCase.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..043517e04b630cb34dad1cf1918b35d6cdef2ceb --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/constantCase.d.mts @@ -0,0 +1,18 @@ +//#region src/string/constantCase.d.ts +/** + * Converts a string to constant case. + * + * Constant case is a naming convention where each word is written in uppercase letters and separated by an underscore (`_`). For example, `CONSTANT_CASE`. + * + * @param {string} str - The string that is to be changed to constant case. + * @returns {string} - The converted string to constant case. + * + * @example + * const convertedStr1 = constantCase('camelCase') // returns 'CAMEL_CASE' + * const convertedStr2 = constantCase('some whitespace') // returns 'SOME_WHITESPACE' + * const convertedStr3 = constantCase('hyphen-text') // returns 'HYPHEN_TEXT' + * const convertedStr4 = constantCase('HTTPRequest') // returns 'HTTP_REQUEST' + */ +declare function constantCase(str: string): string; +//#endregion +export { constantCase }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/constantCase.d.ts b/tools/ui/node_modules/es-toolkit/dist/string/constantCase.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..043517e04b630cb34dad1cf1918b35d6cdef2ceb --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/constantCase.d.ts @@ -0,0 +1,18 @@ +//#region src/string/constantCase.d.ts +/** + * Converts a string to constant case. + * + * Constant case is a naming convention where each word is written in uppercase letters and separated by an underscore (`_`). For example, `CONSTANT_CASE`. + * + * @param {string} str - The string that is to be changed to constant case. + * @returns {string} - The converted string to constant case. + * + * @example + * const convertedStr1 = constantCase('camelCase') // returns 'CAMEL_CASE' + * const convertedStr2 = constantCase('some whitespace') // returns 'SOME_WHITESPACE' + * const convertedStr3 = constantCase('hyphen-text') // returns 'HYPHEN_TEXT' + * const convertedStr4 = constantCase('HTTPRequest') // returns 'HTTP_REQUEST' + */ +declare function constantCase(str: string): string; +//#endregion +export { constantCase }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/constantCase.js b/tools/ui/node_modules/es-toolkit/dist/string/constantCase.js new file mode 100644 index 0000000000000000000000000000000000000000..5ce23388f1a03541649e48f36ebab855012a466b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/constantCase.js @@ -0,0 +1,21 @@ +const require_words = require("./words.js"); +//#region src/string/constantCase.ts +/** +* Converts a string to constant case. +* +* Constant case is a naming convention where each word is written in uppercase letters and separated by an underscore (`_`). For example, `CONSTANT_CASE`. +* +* @param {string} str - The string that is to be changed to constant case. +* @returns {string} - The converted string to constant case. +* +* @example +* const convertedStr1 = constantCase('camelCase') // returns 'CAMEL_CASE' +* const convertedStr2 = constantCase('some whitespace') // returns 'SOME_WHITESPACE' +* const convertedStr3 = constantCase('hyphen-text') // returns 'HYPHEN_TEXT' +* const convertedStr4 = constantCase('HTTPRequest') // returns 'HTTP_REQUEST' +*/ +function constantCase(str) { + return require_words.words(str).map((word) => word.toUpperCase()).join("_"); +} +//#endregion +exports.constantCase = constantCase; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/constantCase.mjs b/tools/ui/node_modules/es-toolkit/dist/string/constantCase.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5e4ffd70ffd2f939bf9c207ceb7b213bffd2c720 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/constantCase.mjs @@ -0,0 +1,21 @@ +import { words } from "./words.mjs"; +//#region src/string/constantCase.ts +/** +* Converts a string to constant case. +* +* Constant case is a naming convention where each word is written in uppercase letters and separated by an underscore (`_`). For example, `CONSTANT_CASE`. +* +* @param {string} str - The string that is to be changed to constant case. +* @returns {string} - The converted string to constant case. +* +* @example +* const convertedStr1 = constantCase('camelCase') // returns 'CAMEL_CASE' +* const convertedStr2 = constantCase('some whitespace') // returns 'SOME_WHITESPACE' +* const convertedStr3 = constantCase('hyphen-text') // returns 'HYPHEN_TEXT' +* const convertedStr4 = constantCase('HTTPRequest') // returns 'HTTP_REQUEST' +*/ +function constantCase(str) { + return words(str).map((word) => word.toUpperCase()).join("_"); +} +//#endregion +export { constantCase }; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/deburr.d.mts b/tools/ui/node_modules/es-toolkit/dist/string/deburr.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..48731900140062854fc776602b1c1bffc4a735af --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/deburr.d.mts @@ -0,0 +1,23 @@ +//#region src/string/deburr.d.ts +/** + * Converts a string by replacing special characters and diacritical marks with their ASCII equivalents. + * For example, "Crème brûlée" becomes "Creme brulee". + * + * @param {string} str - The input string to be deburred. + * @returns {string} - The deburred string with special characters replaced by their ASCII equivalents. + * + * @example + * // Basic usage: + * deburr('Æthelred') // returns 'Aethelred' + * + * @example + * // Handling diacritical marks: + * deburr('München') // returns 'Munchen' + * + * @example + * // Special characters: + * deburr('Crème brûlée') // returns 'Creme brulee' + */ +declare function deburr(str: string): string; +//#endregion +export { deburr }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/deburr.d.ts b/tools/ui/node_modules/es-toolkit/dist/string/deburr.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..48731900140062854fc776602b1c1bffc4a735af --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/deburr.d.ts @@ -0,0 +1,23 @@ +//#region src/string/deburr.d.ts +/** + * Converts a string by replacing special characters and diacritical marks with their ASCII equivalents. + * For example, "Crème brûlée" becomes "Creme brulee". + * + * @param {string} str - The input string to be deburred. + * @returns {string} - The deburred string with special characters replaced by their ASCII equivalents. + * + * @example + * // Basic usage: + * deburr('Æthelred') // returns 'Aethelred' + * + * @example + * // Handling diacritical marks: + * deburr('München') // returns 'Munchen' + * + * @example + * // Special characters: + * deburr('Crème brûlée') // returns 'Creme brulee' + */ +declare function deburr(str: string): string; +//#endregion +export { deburr }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/deburr.js b/tools/ui/node_modules/es-toolkit/dist/string/deburr.js new file mode 100644 index 0000000000000000000000000000000000000000..39dcbd75d09bfe8e1364a311a37c44496ebecac8 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/deburr.js @@ -0,0 +1,63 @@ +//#region src/string/deburr.ts +const deburrMap = new Map([ + ["Æ", "Ae"], + ["Ð", "D"], + ["Ø", "O"], + ["Þ", "Th"], + ["ß", "ss"], + ["æ", "ae"], + ["ð", "d"], + ["ø", "o"], + ["þ", "th"], + ["Đ", "D"], + ["đ", "d"], + ["Ħ", "H"], + ["ħ", "h"], + ["ı", "i"], + ["IJ", "IJ"], + ["ij", "ij"], + ["ĸ", "k"], + ["Ŀ", "L"], + ["ŀ", "l"], + ["Ł", "L"], + ["ł", "l"], + ["ʼn", "'n"], + ["Ŋ", "N"], + ["ŋ", "n"], + ["Œ", "Oe"], + ["œ", "oe"], + ["Ŧ", "T"], + ["ŧ", "t"], + ["ſ", "s"] +]); +/** +* Converts a string by replacing special characters and diacritical marks with their ASCII equivalents. +* For example, "Crème brûlée" becomes "Creme brulee". +* +* @param {string} str - The input string to be deburred. +* @returns {string} - The deburred string with special characters replaced by their ASCII equivalents. +* +* @example +* // Basic usage: +* deburr('Æthelred') // returns 'Aethelred' +* +* @example +* // Handling diacritical marks: +* deburr('München') // returns 'Munchen' +* +* @example +* // Special characters: +* deburr('Crème brûlée') // returns 'Creme brulee' +*/ +function deburr(str) { + str = str.normalize("NFD"); + let result = ""; + for (let i = 0; i < str.length; i++) { + const char = str[i]; + if (char >= "̀" && char <= "ͯ" || char >= "︠" && char <= "︣") continue; + result += deburrMap.get(char) ?? char; + } + return result; +} +//#endregion +exports.deburr = deburr; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/deburr.mjs b/tools/ui/node_modules/es-toolkit/dist/string/deburr.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e15db9ec92da87c8e1d2ad42ae021bb072ae0983 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/deburr.mjs @@ -0,0 +1,63 @@ +//#region src/string/deburr.ts +const deburrMap = new Map([ + ["Æ", "Ae"], + ["Ð", "D"], + ["Ø", "O"], + ["Þ", "Th"], + ["ß", "ss"], + ["æ", "ae"], + ["ð", "d"], + ["ø", "o"], + ["þ", "th"], + ["Đ", "D"], + ["đ", "d"], + ["Ħ", "H"], + ["ħ", "h"], + ["ı", "i"], + ["IJ", "IJ"], + ["ij", "ij"], + ["ĸ", "k"], + ["Ŀ", "L"], + ["ŀ", "l"], + ["Ł", "L"], + ["ł", "l"], + ["ʼn", "'n"], + ["Ŋ", "N"], + ["ŋ", "n"], + ["Œ", "Oe"], + ["œ", "oe"], + ["Ŧ", "T"], + ["ŧ", "t"], + ["ſ", "s"] +]); +/** +* Converts a string by replacing special characters and diacritical marks with their ASCII equivalents. +* For example, "Crème brûlée" becomes "Creme brulee". +* +* @param {string} str - The input string to be deburred. +* @returns {string} - The deburred string with special characters replaced by their ASCII equivalents. +* +* @example +* // Basic usage: +* deburr('Æthelred') // returns 'Aethelred' +* +* @example +* // Handling diacritical marks: +* deburr('München') // returns 'Munchen' +* +* @example +* // Special characters: +* deburr('Crème brûlée') // returns 'Creme brulee' +*/ +function deburr(str) { + str = str.normalize("NFD"); + let result = ""; + for (let i = 0; i < str.length; i++) { + const char = str[i]; + if (char >= "̀" && char <= "ͯ" || char >= "︠" && char <= "︣") continue; + result += deburrMap.get(char) ?? char; + } + return result; +} +//#endregion +export { deburr }; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/escape.d.mts b/tools/ui/node_modules/es-toolkit/dist/string/escape.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..dde201c4009a2aa0eeb75e055e52a0d68ef48e5e --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/escape.d.mts @@ -0,0 +1,17 @@ +//#region src/string/escape.d.ts +/** + * Converts the characters "&", "<", ">", '"', and "'" in `str` to their corresponding HTML entities. + * For example, "<" becomes "<". + * + * @param {string} str The string to escape. + * @returns {string} Returns the escaped string. + * + * @example + * escape('This is a
element.'); // returns 'This is a <div> element.' + * escape('This is a "quote"'); // returns 'This is a "quote"' + * escape("This is a 'quote'"); // returns 'This is a 'quote'' + * escape('This is a & symbol'); // returns 'This is a & symbol' + */ +declare function escape(str: string): string; +//#endregion +export { escape }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/escape.d.ts b/tools/ui/node_modules/es-toolkit/dist/string/escape.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dde201c4009a2aa0eeb75e055e52a0d68ef48e5e --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/escape.d.ts @@ -0,0 +1,17 @@ +//#region src/string/escape.d.ts +/** + * Converts the characters "&", "<", ">", '"', and "'" in `str` to their corresponding HTML entities. + * For example, "<" becomes "<". + * + * @param {string} str The string to escape. + * @returns {string} Returns the escaped string. + * + * @example + * escape('This is a
element.'); // returns 'This is a <div> element.' + * escape('This is a "quote"'); // returns 'This is a "quote"' + * escape("This is a 'quote'"); // returns 'This is a 'quote'' + * escape('This is a & symbol'); // returns 'This is a & symbol' + */ +declare function escape(str: string): string; +//#endregion +export { escape }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/escape.js b/tools/ui/node_modules/es-toolkit/dist/string/escape.js new file mode 100644 index 0000000000000000000000000000000000000000..bef6ffe48229de165bdea4e5a26e5a050b50b129 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/escape.js @@ -0,0 +1,26 @@ +//#region src/string/escape.ts +const htmlEscapes = { + "&": "&", + "<": "<", + ">": ">", + "\"": """, + "'": "'" +}; +/** +* Converts the characters "&", "<", ">", '"', and "'" in `str` to their corresponding HTML entities. +* For example, "<" becomes "<". +* +* @param {string} str The string to escape. +* @returns {string} Returns the escaped string. +* +* @example +* escape('This is a
element.'); // returns 'This is a <div> element.' +* escape('This is a "quote"'); // returns 'This is a "quote"' +* escape("This is a 'quote'"); // returns 'This is a 'quote'' +* escape('This is a & symbol'); // returns 'This is a & symbol' +*/ +function escape(str) { + return str.replace(/[&<>"']/g, (match) => htmlEscapes[match]); +} +//#endregion +exports.escape = escape; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/escape.mjs b/tools/ui/node_modules/es-toolkit/dist/string/escape.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a98199c44ee39f2f601cd26e8bca77b20d8d8d04 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/escape.mjs @@ -0,0 +1,26 @@ +//#region src/string/escape.ts +const htmlEscapes = { + "&": "&", + "<": "<", + ">": ">", + "\"": """, + "'": "'" +}; +/** +* Converts the characters "&", "<", ">", '"', and "'" in `str` to their corresponding HTML entities. +* For example, "<" becomes "<". +* +* @param {string} str The string to escape. +* @returns {string} Returns the escaped string. +* +* @example +* escape('This is a
element.'); // returns 'This is a <div> element.' +* escape('This is a "quote"'); // returns 'This is a "quote"' +* escape("This is a 'quote'"); // returns 'This is a 'quote'' +* escape('This is a & symbol'); // returns 'This is a & symbol' +*/ +function escape(str) { + return str.replace(/[&<>"']/g, (match) => htmlEscapes[match]); +} +//#endregion +export { escape }; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/escapeRegExp.d.mts b/tools/ui/node_modules/es-toolkit/dist/string/escapeRegExp.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..c4021c0fe7b99eb9e1340229280b2399ca3548a0 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/escapeRegExp.d.mts @@ -0,0 +1,15 @@ +//#region src/string/escapeRegExp.d.ts +/** + * Escapes the RegExp special characters "^", "$", "\\", ".", "*", "+", "?", "(", ")", "[", "]", "{", "}", and "|" in `str`. + * + * @param {string} str The string to escape. + * @returns {string} Returns the escaped string. + * + * @example + * import { escapeRegExp } from 'es-toolkit/string'; + * + * escapeRegExp('[es-toolkit](https://es-toolkit.dev/)'); // returns '\[es-toolkit\]\(https://es-toolkit\.dev/\)' + */ +declare function escapeRegExp(str: string): string; +//#endregion +export { escapeRegExp }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/escapeRegExp.d.ts b/tools/ui/node_modules/es-toolkit/dist/string/escapeRegExp.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c4021c0fe7b99eb9e1340229280b2399ca3548a0 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/escapeRegExp.d.ts @@ -0,0 +1,15 @@ +//#region src/string/escapeRegExp.d.ts +/** + * Escapes the RegExp special characters "^", "$", "\\", ".", "*", "+", "?", "(", ")", "[", "]", "{", "}", and "|" in `str`. + * + * @param {string} str The string to escape. + * @returns {string} Returns the escaped string. + * + * @example + * import { escapeRegExp } from 'es-toolkit/string'; + * + * escapeRegExp('[es-toolkit](https://es-toolkit.dev/)'); // returns '\[es-toolkit\]\(https://es-toolkit\.dev/\)' + */ +declare function escapeRegExp(str: string): string; +//#endregion +export { escapeRegExp }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/escapeRegExp.js b/tools/ui/node_modules/es-toolkit/dist/string/escapeRegExp.js new file mode 100644 index 0000000000000000000000000000000000000000..63f24aa667f85b0f2dce464b2e259f72c8f4a4ab --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/escapeRegExp.js @@ -0,0 +1,17 @@ +//#region src/string/escapeRegExp.ts +/** +* Escapes the RegExp special characters "^", "$", "\\", ".", "*", "+", "?", "(", ")", "[", "]", "{", "}", and "|" in `str`. +* +* @param {string} str The string to escape. +* @returns {string} Returns the escaped string. +* +* @example +* import { escapeRegExp } from 'es-toolkit/string'; +* +* escapeRegExp('[es-toolkit](https://es-toolkit.dev/)'); // returns '\[es-toolkit\]\(https://es-toolkit\.dev/\)' +*/ +function escapeRegExp(str) { + return str.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&"); +} +//#endregion +exports.escapeRegExp = escapeRegExp; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/escapeRegExp.mjs b/tools/ui/node_modules/es-toolkit/dist/string/escapeRegExp.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c0019261fac0296732b6d0073d9303adf64a4d15 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/escapeRegExp.mjs @@ -0,0 +1,17 @@ +//#region src/string/escapeRegExp.ts +/** +* Escapes the RegExp special characters "^", "$", "\\", ".", "*", "+", "?", "(", ")", "[", "]", "{", "}", and "|" in `str`. +* +* @param {string} str The string to escape. +* @returns {string} Returns the escaped string. +* +* @example +* import { escapeRegExp } from 'es-toolkit/string'; +* +* escapeRegExp('[es-toolkit](https://es-toolkit.dev/)'); // returns '\[es-toolkit\]\(https://es-toolkit\.dev/\)' +*/ +function escapeRegExp(str) { + return str.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&"); +} +//#endregion +export { escapeRegExp }; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/index.d.mts b/tools/ui/node_modules/es-toolkit/dist/string/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..6f778d125020f7faab5f261c61f9bdda6da8bf63 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/index.d.mts @@ -0,0 +1,22 @@ +import { camelCase } from "./camelCase.mjs"; +import { capitalize } from "./capitalize.mjs"; +import { constantCase } from "./constantCase.mjs"; +import { deburr } from "./deburr.mjs"; +import { escape } from "./escape.mjs"; +import { escapeRegExp } from "./escapeRegExp.mjs"; +import { kebabCase } from "./kebabCase.mjs"; +import { lowerCase } from "./lowerCase.mjs"; +import { lowerFirst } from "./lowerFirst.mjs"; +import { pad } from "./pad.mjs"; +import { pascalCase } from "./pascalCase.mjs"; +import { reverseString } from "./reverseString.mjs"; +import { snakeCase } from "./snakeCase.mjs"; +import { startCase } from "./startCase.mjs"; +import { trim } from "./trim.mjs"; +import { trimEnd } from "./trimEnd.mjs"; +import { trimStart } from "./trimStart.mjs"; +import { unescape } from "./unescape.mjs"; +import { upperCase } from "./upperCase.mjs"; +import { upperFirst } from "./upperFirst.mjs"; +import { words } from "./words.mjs"; +export { camelCase, capitalize, constantCase, deburr, escape, escapeRegExp, kebabCase, lowerCase, lowerFirst, pad, pascalCase, reverseString, snakeCase, startCase, trim, trimEnd, trimStart, unescape, upperCase, upperFirst, words }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/index.d.ts b/tools/ui/node_modules/es-toolkit/dist/string/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6ba883b4da09f907fda6bd8ea31b57fc19bd3688 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/index.d.ts @@ -0,0 +1,22 @@ +import { camelCase } from "./camelCase.js"; +import { capitalize } from "./capitalize.js"; +import { constantCase } from "./constantCase.js"; +import { deburr } from "./deburr.js"; +import { escape } from "./escape.js"; +import { escapeRegExp } from "./escapeRegExp.js"; +import { kebabCase } from "./kebabCase.js"; +import { lowerCase } from "./lowerCase.js"; +import { lowerFirst } from "./lowerFirst.js"; +import { pad } from "./pad.js"; +import { pascalCase } from "./pascalCase.js"; +import { reverseString } from "./reverseString.js"; +import { snakeCase } from "./snakeCase.js"; +import { startCase } from "./startCase.js"; +import { trim } from "./trim.js"; +import { trimEnd } from "./trimEnd.js"; +import { trimStart } from "./trimStart.js"; +import { unescape } from "./unescape.js"; +import { upperCase } from "./upperCase.js"; +import { upperFirst } from "./upperFirst.js"; +import { words } from "./words.js"; +export { camelCase, capitalize, constantCase, deburr, escape, escapeRegExp, kebabCase, lowerCase, lowerFirst, pad, pascalCase, reverseString, snakeCase, startCase, trim, trimEnd, trimStart, unescape, upperCase, upperFirst, words }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/index.js b/tools/ui/node_modules/es-toolkit/dist/string/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1a01215cd675deb4fdb96f266169efde31bd5b19 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/index.js @@ -0,0 +1,43 @@ +Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); +const require_capitalize = require("./capitalize.js"); +const require_words = require("./words.js"); +const require_camelCase = require("./camelCase.js"); +const require_snakeCase = require("./snakeCase.js"); +const require_constantCase = require("./constantCase.js"); +const require_deburr = require("./deburr.js"); +const require_escape = require("./escape.js"); +const require_escapeRegExp = require("./escapeRegExp.js"); +const require_kebabCase = require("./kebabCase.js"); +const require_lowerCase = require("./lowerCase.js"); +const require_lowerFirst = require("./lowerFirst.js"); +const require_pad = require("./pad.js"); +const require_pascalCase = require("./pascalCase.js"); +const require_reverseString = require("./reverseString.js"); +const require_startCase = require("./startCase.js"); +const require_trimEnd = require("./trimEnd.js"); +const require_trimStart = require("./trimStart.js"); +const require_trim = require("./trim.js"); +const require_unescape = require("./unescape.js"); +const require_upperCase = require("./upperCase.js"); +const require_upperFirst = require("./upperFirst.js"); +exports.camelCase = require_camelCase.camelCase; +exports.capitalize = require_capitalize.capitalize; +exports.constantCase = require_constantCase.constantCase; +exports.deburr = require_deburr.deburr; +exports.escape = require_escape.escape; +exports.escapeRegExp = require_escapeRegExp.escapeRegExp; +exports.kebabCase = require_kebabCase.kebabCase; +exports.lowerCase = require_lowerCase.lowerCase; +exports.lowerFirst = require_lowerFirst.lowerFirst; +exports.pad = require_pad.pad; +exports.pascalCase = require_pascalCase.pascalCase; +exports.reverseString = require_reverseString.reverseString; +exports.snakeCase = require_snakeCase.snakeCase; +exports.startCase = require_startCase.startCase; +exports.trim = require_trim.trim; +exports.trimEnd = require_trimEnd.trimEnd; +exports.trimStart = require_trimStart.trimStart; +exports.unescape = require_unescape.unescape; +exports.upperCase = require_upperCase.upperCase; +exports.upperFirst = require_upperFirst.upperFirst; +exports.words = require_words.words; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/index.mjs b/tools/ui/node_modules/es-toolkit/dist/string/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..83bb4a4807475176a843f95f15768d603b80d58c --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/index.mjs @@ -0,0 +1,22 @@ +import { capitalize } from "./capitalize.mjs"; +import { words } from "./words.mjs"; +import { camelCase } from "./camelCase.mjs"; +import { snakeCase } from "./snakeCase.mjs"; +import { constantCase } from "./constantCase.mjs"; +import { deburr } from "./deburr.mjs"; +import { escape } from "./escape.mjs"; +import { escapeRegExp } from "./escapeRegExp.mjs"; +import { kebabCase } from "./kebabCase.mjs"; +import { lowerCase } from "./lowerCase.mjs"; +import { lowerFirst } from "./lowerFirst.mjs"; +import { pad } from "./pad.mjs"; +import { pascalCase } from "./pascalCase.mjs"; +import { reverseString } from "./reverseString.mjs"; +import { startCase } from "./startCase.mjs"; +import { trimEnd } from "./trimEnd.mjs"; +import { trimStart } from "./trimStart.mjs"; +import { trim } from "./trim.mjs"; +import { unescape } from "./unescape.mjs"; +import { upperCase } from "./upperCase.mjs"; +import { upperFirst } from "./upperFirst.mjs"; +export { camelCase, capitalize, constantCase, deburr, escape, escapeRegExp, kebabCase, lowerCase, lowerFirst, pad, pascalCase, reverseString, snakeCase, startCase, trim, trimEnd, trimStart, unescape, upperCase, upperFirst, words }; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/kebabCase.d.mts b/tools/ui/node_modules/es-toolkit/dist/string/kebabCase.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..c0f394f973f3b55d6569ec05f73d2608668edd75 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/kebabCase.d.mts @@ -0,0 +1,18 @@ +//#region src/string/kebabCase.d.ts +/** + * Converts a string to kebab case. + * + * Kebab case is the naming convention in which each word is written in lowercase and separated by a dash (-) character. + * + * @param {string} str - The string that is to be changed to kebab case. + * @returns {string} - The converted string to kebab case. + * + * @example + * const convertedStr1 = kebabCase('camelCase') // returns 'camel-case' + * const convertedStr2 = kebabCase('some whitespace') // returns 'some-whitespace' + * const convertedStr3 = kebabCase('hyphen-text') // returns 'hyphen-text' + * const convertedStr4 = kebabCase('HTTPRequest') // returns 'http-request' + */ +declare function kebabCase(str: string): string; +//#endregion +export { kebabCase }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/kebabCase.d.ts b/tools/ui/node_modules/es-toolkit/dist/string/kebabCase.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c0f394f973f3b55d6569ec05f73d2608668edd75 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/kebabCase.d.ts @@ -0,0 +1,18 @@ +//#region src/string/kebabCase.d.ts +/** + * Converts a string to kebab case. + * + * Kebab case is the naming convention in which each word is written in lowercase and separated by a dash (-) character. + * + * @param {string} str - The string that is to be changed to kebab case. + * @returns {string} - The converted string to kebab case. + * + * @example + * const convertedStr1 = kebabCase('camelCase') // returns 'camel-case' + * const convertedStr2 = kebabCase('some whitespace') // returns 'some-whitespace' + * const convertedStr3 = kebabCase('hyphen-text') // returns 'hyphen-text' + * const convertedStr4 = kebabCase('HTTPRequest') // returns 'http-request' + */ +declare function kebabCase(str: string): string; +//#endregion +export { kebabCase }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/kebabCase.js b/tools/ui/node_modules/es-toolkit/dist/string/kebabCase.js new file mode 100644 index 0000000000000000000000000000000000000000..f63d548790d17621cc27b7709cfcb2bdba168792 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/kebabCase.js @@ -0,0 +1,21 @@ +const require_words = require("./words.js"); +//#region src/string/kebabCase.ts +/** +* Converts a string to kebab case. +* +* Kebab case is the naming convention in which each word is written in lowercase and separated by a dash (-) character. +* +* @param {string} str - The string that is to be changed to kebab case. +* @returns {string} - The converted string to kebab case. +* +* @example +* const convertedStr1 = kebabCase('camelCase') // returns 'camel-case' +* const convertedStr2 = kebabCase('some whitespace') // returns 'some-whitespace' +* const convertedStr3 = kebabCase('hyphen-text') // returns 'hyphen-text' +* const convertedStr4 = kebabCase('HTTPRequest') // returns 'http-request' +*/ +function kebabCase(str) { + return require_words.words(str).map((word) => word.toLowerCase()).join("-"); +} +//#endregion +exports.kebabCase = kebabCase; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/kebabCase.mjs b/tools/ui/node_modules/es-toolkit/dist/string/kebabCase.mjs new file mode 100644 index 0000000000000000000000000000000000000000..87ddd5ed17950e002de13dc85e2a3fb2b71b8a05 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/kebabCase.mjs @@ -0,0 +1,21 @@ +import { words } from "./words.mjs"; +//#region src/string/kebabCase.ts +/** +* Converts a string to kebab case. +* +* Kebab case is the naming convention in which each word is written in lowercase and separated by a dash (-) character. +* +* @param {string} str - The string that is to be changed to kebab case. +* @returns {string} - The converted string to kebab case. +* +* @example +* const convertedStr1 = kebabCase('camelCase') // returns 'camel-case' +* const convertedStr2 = kebabCase('some whitespace') // returns 'some-whitespace' +* const convertedStr3 = kebabCase('hyphen-text') // returns 'hyphen-text' +* const convertedStr4 = kebabCase('HTTPRequest') // returns 'http-request' +*/ +function kebabCase(str) { + return words(str).map((word) => word.toLowerCase()).join("-"); +} +//#endregion +export { kebabCase }; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/lowerCase.d.mts b/tools/ui/node_modules/es-toolkit/dist/string/lowerCase.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..5f3f0f033a68671c3501a942416725983a71ab35 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/lowerCase.d.mts @@ -0,0 +1,18 @@ +//#region src/string/lowerCase.d.ts +/** + * Converts a string to lower case. + * + * Lower case is the naming convention in which each word is written in lowercase and separated by an space ( ) character. + * + * @param {string} str - The string that is to be changed to lower case. + * @returns {string} - The converted string to lower case. + * + * @example + * const convertedStr1 = lowerCase('camelCase') // returns 'camel case' + * const convertedStr2 = lowerCase('some whitespace') // returns 'some whitespace' + * const convertedStr3 = lowerCase('hyphen-text') // returns 'hyphen text' + * const convertedStr4 = lowerCase('HTTPRequest') // returns 'http request' + */ +declare function lowerCase(str: string): string; +//#endregion +export { lowerCase }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/lowerCase.d.ts b/tools/ui/node_modules/es-toolkit/dist/string/lowerCase.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5f3f0f033a68671c3501a942416725983a71ab35 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/lowerCase.d.ts @@ -0,0 +1,18 @@ +//#region src/string/lowerCase.d.ts +/** + * Converts a string to lower case. + * + * Lower case is the naming convention in which each word is written in lowercase and separated by an space ( ) character. + * + * @param {string} str - The string that is to be changed to lower case. + * @returns {string} - The converted string to lower case. + * + * @example + * const convertedStr1 = lowerCase('camelCase') // returns 'camel case' + * const convertedStr2 = lowerCase('some whitespace') // returns 'some whitespace' + * const convertedStr3 = lowerCase('hyphen-text') // returns 'hyphen text' + * const convertedStr4 = lowerCase('HTTPRequest') // returns 'http request' + */ +declare function lowerCase(str: string): string; +//#endregion +export { lowerCase }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/lowerCase.js b/tools/ui/node_modules/es-toolkit/dist/string/lowerCase.js new file mode 100644 index 0000000000000000000000000000000000000000..bc1f9c690cd615725d725e5d6ecd6a11bd6a2898 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/lowerCase.js @@ -0,0 +1,21 @@ +const require_words = require("./words.js"); +//#region src/string/lowerCase.ts +/** +* Converts a string to lower case. +* +* Lower case is the naming convention in which each word is written in lowercase and separated by an space ( ) character. +* +* @param {string} str - The string that is to be changed to lower case. +* @returns {string} - The converted string to lower case. +* +* @example +* const convertedStr1 = lowerCase('camelCase') // returns 'camel case' +* const convertedStr2 = lowerCase('some whitespace') // returns 'some whitespace' +* const convertedStr3 = lowerCase('hyphen-text') // returns 'hyphen text' +* const convertedStr4 = lowerCase('HTTPRequest') // returns 'http request' +*/ +function lowerCase(str) { + return require_words.words(str).map((word) => word.toLowerCase()).join(" "); +} +//#endregion +exports.lowerCase = lowerCase; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/lowerCase.mjs b/tools/ui/node_modules/es-toolkit/dist/string/lowerCase.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d70288a7d58d4717b0016da6147ff72c5695a117 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/lowerCase.mjs @@ -0,0 +1,21 @@ +import { words } from "./words.mjs"; +//#region src/string/lowerCase.ts +/** +* Converts a string to lower case. +* +* Lower case is the naming convention in which each word is written in lowercase and separated by an space ( ) character. +* +* @param {string} str - The string that is to be changed to lower case. +* @returns {string} - The converted string to lower case. +* +* @example +* const convertedStr1 = lowerCase('camelCase') // returns 'camel case' +* const convertedStr2 = lowerCase('some whitespace') // returns 'some whitespace' +* const convertedStr3 = lowerCase('hyphen-text') // returns 'hyphen text' +* const convertedStr4 = lowerCase('HTTPRequest') // returns 'http request' +*/ +function lowerCase(str) { + return words(str).map((word) => word.toLowerCase()).join(" "); +} +//#endregion +export { lowerCase }; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/lowerFirst.d.mts b/tools/ui/node_modules/es-toolkit/dist/string/lowerFirst.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..006dc007f11bdc8214c9820bced864afcf8bd607 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/lowerFirst.d.mts @@ -0,0 +1,15 @@ +//#region src/string/lowerFirst.d.ts +/** + * Converts the first character of string to lower case. + * + * @param {string} str - The string that is to be changed + * @returns {string} - The converted string. + * + * @example + * const convertedStr1 = lowerCase('fred') // returns 'fred' + * const convertedStr2 = lowerCase('Fred') // returns 'fred' + * const convertedStr3 = lowerCase('FRED') // returns 'fRED' + */ +declare function lowerFirst(str: string): string; +//#endregion +export { lowerFirst }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/lowerFirst.d.ts b/tools/ui/node_modules/es-toolkit/dist/string/lowerFirst.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..006dc007f11bdc8214c9820bced864afcf8bd607 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/lowerFirst.d.ts @@ -0,0 +1,15 @@ +//#region src/string/lowerFirst.d.ts +/** + * Converts the first character of string to lower case. + * + * @param {string} str - The string that is to be changed + * @returns {string} - The converted string. + * + * @example + * const convertedStr1 = lowerCase('fred') // returns 'fred' + * const convertedStr2 = lowerCase('Fred') // returns 'fred' + * const convertedStr3 = lowerCase('FRED') // returns 'fRED' + */ +declare function lowerFirst(str: string): string; +//#endregion +export { lowerFirst }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/lowerFirst.js b/tools/ui/node_modules/es-toolkit/dist/string/lowerFirst.js new file mode 100644 index 0000000000000000000000000000000000000000..e57448994b8ae0f091cf8b1740c77182c7422776 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/lowerFirst.js @@ -0,0 +1,17 @@ +//#region src/string/lowerFirst.ts +/** +* Converts the first character of string to lower case. +* +* @param {string} str - The string that is to be changed +* @returns {string} - The converted string. +* +* @example +* const convertedStr1 = lowerCase('fred') // returns 'fred' +* const convertedStr2 = lowerCase('Fred') // returns 'fred' +* const convertedStr3 = lowerCase('FRED') // returns 'fRED' +*/ +function lowerFirst(str) { + return str.substring(0, 1).toLowerCase() + str.substring(1); +} +//#endregion +exports.lowerFirst = lowerFirst; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/lowerFirst.mjs b/tools/ui/node_modules/es-toolkit/dist/string/lowerFirst.mjs new file mode 100644 index 0000000000000000000000000000000000000000..340727e9d212d92bc92e9fd1ce1b2b12e42a6b19 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/lowerFirst.mjs @@ -0,0 +1,17 @@ +//#region src/string/lowerFirst.ts +/** +* Converts the first character of string to lower case. +* +* @param {string} str - The string that is to be changed +* @returns {string} - The converted string. +* +* @example +* const convertedStr1 = lowerCase('fred') // returns 'fred' +* const convertedStr2 = lowerCase('Fred') // returns 'fred' +* const convertedStr3 = lowerCase('FRED') // returns 'fRED' +*/ +function lowerFirst(str) { + return str.substring(0, 1).toLowerCase() + str.substring(1); +} +//#endregion +export { lowerFirst }; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/pad.d.mts b/tools/ui/node_modules/es-toolkit/dist/string/pad.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..d69f57d2108713c3c268c01ddc47e0c9c5a56014 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/pad.d.mts @@ -0,0 +1,20 @@ +//#region src/string/pad.d.ts +/** + * Pads string on the left and right sides if it's shorter than length. Padding characters are truncated if they can't be evenly divided by length. + * If the length is less than or equal to the original string's length, or if the padding character is an empty string, the original string is returned unchanged. + * + * @param {string} str - The string to pad. + * @param {number} [length] - The length of the resulting string once padded. + * @param {string} [chars] - The character(s) to use for padding. + * @returns {string} - The padded string, or the original string if padding is not required. + * + * @example + * const result1 = pad('abc', 8); // result will be ' abc ' + * const result2 = pad('abc', 8, '_-'); // result will be '_-abc_-_' + * const result3 = pad('abc', 3); // result will be 'abc' + * const result4 = pad('abc', 2); // result will be 'abc' + * + */ +declare function pad(str: string, length: number, chars?: string): string; +//#endregion +export { pad }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/pad.d.ts b/tools/ui/node_modules/es-toolkit/dist/string/pad.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d69f57d2108713c3c268c01ddc47e0c9c5a56014 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/pad.d.ts @@ -0,0 +1,20 @@ +//#region src/string/pad.d.ts +/** + * Pads string on the left and right sides if it's shorter than length. Padding characters are truncated if they can't be evenly divided by length. + * If the length is less than or equal to the original string's length, or if the padding character is an empty string, the original string is returned unchanged. + * + * @param {string} str - The string to pad. + * @param {number} [length] - The length of the resulting string once padded. + * @param {string} [chars] - The character(s) to use for padding. + * @returns {string} - The padded string, or the original string if padding is not required. + * + * @example + * const result1 = pad('abc', 8); // result will be ' abc ' + * const result2 = pad('abc', 8, '_-'); // result will be '_-abc_-_' + * const result3 = pad('abc', 3); // result will be 'abc' + * const result4 = pad('abc', 2); // result will be 'abc' + * + */ +declare function pad(str: string, length: number, chars?: string): string; +//#endregion +export { pad }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/pad.js b/tools/ui/node_modules/es-toolkit/dist/string/pad.js new file mode 100644 index 0000000000000000000000000000000000000000..b3c8d44dad802b36e2989148e1289bc07efede75 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/pad.js @@ -0,0 +1,22 @@ +//#region src/string/pad.ts +/** +* Pads string on the left and right sides if it's shorter than length. Padding characters are truncated if they can't be evenly divided by length. +* If the length is less than or equal to the original string's length, or if the padding character is an empty string, the original string is returned unchanged. +* +* @param {string} str - The string to pad. +* @param {number} [length] - The length of the resulting string once padded. +* @param {string} [chars] - The character(s) to use for padding. +* @returns {string} - The padded string, or the original string if padding is not required. +* +* @example +* const result1 = pad('abc', 8); // result will be ' abc ' +* const result2 = pad('abc', 8, '_-'); // result will be '_-abc_-_' +* const result3 = pad('abc', 3); // result will be 'abc' +* const result4 = pad('abc', 2); // result will be 'abc' +* +*/ +function pad(str, length, chars = " ") { + return str.padStart(Math.floor((length - str.length) / 2) + str.length, chars).padEnd(length, chars); +} +//#endregion +exports.pad = pad; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/pad.mjs b/tools/ui/node_modules/es-toolkit/dist/string/pad.mjs new file mode 100644 index 0000000000000000000000000000000000000000..cf5f631c74bdcefaaedada3cc194aac0ef21f371 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/pad.mjs @@ -0,0 +1,22 @@ +//#region src/string/pad.ts +/** +* Pads string on the left and right sides if it's shorter than length. Padding characters are truncated if they can't be evenly divided by length. +* If the length is less than or equal to the original string's length, or if the padding character is an empty string, the original string is returned unchanged. +* +* @param {string} str - The string to pad. +* @param {number} [length] - The length of the resulting string once padded. +* @param {string} [chars] - The character(s) to use for padding. +* @returns {string} - The padded string, or the original string if padding is not required. +* +* @example +* const result1 = pad('abc', 8); // result will be ' abc ' +* const result2 = pad('abc', 8, '_-'); // result will be '_-abc_-_' +* const result3 = pad('abc', 3); // result will be 'abc' +* const result4 = pad('abc', 2); // result will be 'abc' +* +*/ +function pad(str, length, chars = " ") { + return str.padStart(Math.floor((length - str.length) / 2) + str.length, chars).padEnd(length, chars); +} +//#endregion +export { pad }; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/pascalCase.d.mts b/tools/ui/node_modules/es-toolkit/dist/string/pascalCase.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..5178b3b35ae597e832710b775b54b3b814ea40df --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/pascalCase.d.mts @@ -0,0 +1,18 @@ +//#region src/string/pascalCase.d.ts +/** + * Converts a string to Pascal case. + * + * Pascal case is the naming convention in which each word is capitalized and concatenated without any separator characters. + * + * @param {string} str - The string that is to be changed to pascal case. + * @returns {string} - The converted string to Pascal case. + * + * @example + * const convertedStr1 = pascalCase('pascalCase') // returns 'PascalCase' + * const convertedStr2 = pascalCase('some whitespace') // returns 'SomeWhitespace' + * const convertedStr3 = pascalCase('hyphen-text') // returns 'HyphenText' + * const convertedStr4 = pascalCase('HTTPRequest') // returns 'HttpRequest' + */ +declare function pascalCase(str: string): string; +//#endregion +export { pascalCase }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/pascalCase.d.ts b/tools/ui/node_modules/es-toolkit/dist/string/pascalCase.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5178b3b35ae597e832710b775b54b3b814ea40df --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/pascalCase.d.ts @@ -0,0 +1,18 @@ +//#region src/string/pascalCase.d.ts +/** + * Converts a string to Pascal case. + * + * Pascal case is the naming convention in which each word is capitalized and concatenated without any separator characters. + * + * @param {string} str - The string that is to be changed to pascal case. + * @returns {string} - The converted string to Pascal case. + * + * @example + * const convertedStr1 = pascalCase('pascalCase') // returns 'PascalCase' + * const convertedStr2 = pascalCase('some whitespace') // returns 'SomeWhitespace' + * const convertedStr3 = pascalCase('hyphen-text') // returns 'HyphenText' + * const convertedStr4 = pascalCase('HTTPRequest') // returns 'HttpRequest' + */ +declare function pascalCase(str: string): string; +//#endregion +export { pascalCase }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/pascalCase.js b/tools/ui/node_modules/es-toolkit/dist/string/pascalCase.js new file mode 100644 index 0000000000000000000000000000000000000000..b125c9c5190f038a159adad03f9a709b6d8c9193 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/pascalCase.js @@ -0,0 +1,22 @@ +const require_capitalize = require("./capitalize.js"); +const require_words = require("./words.js"); +//#region src/string/pascalCase.ts +/** +* Converts a string to Pascal case. +* +* Pascal case is the naming convention in which each word is capitalized and concatenated without any separator characters. +* +* @param {string} str - The string that is to be changed to pascal case. +* @returns {string} - The converted string to Pascal case. +* +* @example +* const convertedStr1 = pascalCase('pascalCase') // returns 'PascalCase' +* const convertedStr2 = pascalCase('some whitespace') // returns 'SomeWhitespace' +* const convertedStr3 = pascalCase('hyphen-text') // returns 'HyphenText' +* const convertedStr4 = pascalCase('HTTPRequest') // returns 'HttpRequest' +*/ +function pascalCase(str) { + return require_words.words(str).map((word) => require_capitalize.capitalize(word)).join(""); +} +//#endregion +exports.pascalCase = pascalCase; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/pascalCase.mjs b/tools/ui/node_modules/es-toolkit/dist/string/pascalCase.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3038d3a63f8190dee0479c0165b1160b29e7f20d --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/pascalCase.mjs @@ -0,0 +1,22 @@ +import { capitalize } from "./capitalize.mjs"; +import { words } from "./words.mjs"; +//#region src/string/pascalCase.ts +/** +* Converts a string to Pascal case. +* +* Pascal case is the naming convention in which each word is capitalized and concatenated without any separator characters. +* +* @param {string} str - The string that is to be changed to pascal case. +* @returns {string} - The converted string to Pascal case. +* +* @example +* const convertedStr1 = pascalCase('pascalCase') // returns 'PascalCase' +* const convertedStr2 = pascalCase('some whitespace') // returns 'SomeWhitespace' +* const convertedStr3 = pascalCase('hyphen-text') // returns 'HyphenText' +* const convertedStr4 = pascalCase('HTTPRequest') // returns 'HttpRequest' +*/ +function pascalCase(str) { + return words(str).map((word) => capitalize(word)).join(""); +} +//#endregion +export { pascalCase }; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/reverseString.d.mts b/tools/ui/node_modules/es-toolkit/dist/string/reverseString.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..1356fc2241c4eaeb857ed1e45cd1d8d5407f5e7f --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/reverseString.d.mts @@ -0,0 +1,17 @@ +//#region src/string/reverseString.d.ts +/** + * Reverses a given string. + * + * This function takes a string as input and returns a new string that is the reverse of the input. + * + * @param {string} value - The string that is to be reversed. + * @returns {string} - The reversed string. + * + * @example + * const reversedStr1 = reverseString('hello') // returns 'olleh' + * const reversedStr2 = reverseString('PascalCase') // returns 'esaClacsaP' + * const reversedStr3 = reverseString('foo 😄 bar') // returns 'rab 😄 oof' + */ +declare function reverseString(value: string): string; +//#endregion +export { reverseString }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/reverseString.d.ts b/tools/ui/node_modules/es-toolkit/dist/string/reverseString.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1356fc2241c4eaeb857ed1e45cd1d8d5407f5e7f --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/reverseString.d.ts @@ -0,0 +1,17 @@ +//#region src/string/reverseString.d.ts +/** + * Reverses a given string. + * + * This function takes a string as input and returns a new string that is the reverse of the input. + * + * @param {string} value - The string that is to be reversed. + * @returns {string} - The reversed string. + * + * @example + * const reversedStr1 = reverseString('hello') // returns 'olleh' + * const reversedStr2 = reverseString('PascalCase') // returns 'esaClacsaP' + * const reversedStr3 = reverseString('foo 😄 bar') // returns 'rab 😄 oof' + */ +declare function reverseString(value: string): string; +//#endregion +export { reverseString }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/reverseString.js b/tools/ui/node_modules/es-toolkit/dist/string/reverseString.js new file mode 100644 index 0000000000000000000000000000000000000000..c3a63230679a08a0af7a23dbe9cb5a6179f73943 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/reverseString.js @@ -0,0 +1,19 @@ +//#region src/string/reverseString.ts +/** +* Reverses a given string. +* +* This function takes a string as input and returns a new string that is the reverse of the input. +* +* @param {string} value - The string that is to be reversed. +* @returns {string} - The reversed string. +* +* @example +* const reversedStr1 = reverseString('hello') // returns 'olleh' +* const reversedStr2 = reverseString('PascalCase') // returns 'esaClacsaP' +* const reversedStr3 = reverseString('foo 😄 bar') // returns 'rab 😄 oof' +*/ +function reverseString(value) { + return [...value].reverse().join(""); +} +//#endregion +exports.reverseString = reverseString; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/reverseString.mjs b/tools/ui/node_modules/es-toolkit/dist/string/reverseString.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4bbaefb552312cbdc7856ab1850a81608da3ea38 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/reverseString.mjs @@ -0,0 +1,19 @@ +//#region src/string/reverseString.ts +/** +* Reverses a given string. +* +* This function takes a string as input and returns a new string that is the reverse of the input. +* +* @param {string} value - The string that is to be reversed. +* @returns {string} - The reversed string. +* +* @example +* const reversedStr1 = reverseString('hello') // returns 'olleh' +* const reversedStr2 = reverseString('PascalCase') // returns 'esaClacsaP' +* const reversedStr3 = reverseString('foo 😄 bar') // returns 'rab 😄 oof' +*/ +function reverseString(value) { + return [...value].reverse().join(""); +} +//#endregion +export { reverseString }; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/snakeCase.d.mts b/tools/ui/node_modules/es-toolkit/dist/string/snakeCase.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..bcb0d578b68999447563b5dbfb4cb773b9db5a4f --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/snakeCase.d.mts @@ -0,0 +1,18 @@ +//#region src/string/snakeCase.d.ts +/** + * Converts a string to snake case. + * + * Snake case is the naming convention in which each word is written in lowercase and separated by an underscore (_) character. + * + * @param {string} str - The string that is to be changed to snake case. + * @returns {string} - The converted string to snake case. + * + * @example + * const convertedStr1 = snakeCase('camelCase') // returns 'camel_case' + * const convertedStr2 = snakeCase('some whitespace') // returns 'some_whitespace' + * const convertedStr3 = snakeCase('hyphen-text') // returns 'hyphen_text' + * const convertedStr4 = snakeCase('HTTPRequest') // returns 'http_request' + */ +declare function snakeCase(str: string): string; +//#endregion +export { snakeCase }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/snakeCase.d.ts b/tools/ui/node_modules/es-toolkit/dist/string/snakeCase.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bcb0d578b68999447563b5dbfb4cb773b9db5a4f --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/snakeCase.d.ts @@ -0,0 +1,18 @@ +//#region src/string/snakeCase.d.ts +/** + * Converts a string to snake case. + * + * Snake case is the naming convention in which each word is written in lowercase and separated by an underscore (_) character. + * + * @param {string} str - The string that is to be changed to snake case. + * @returns {string} - The converted string to snake case. + * + * @example + * const convertedStr1 = snakeCase('camelCase') // returns 'camel_case' + * const convertedStr2 = snakeCase('some whitespace') // returns 'some_whitespace' + * const convertedStr3 = snakeCase('hyphen-text') // returns 'hyphen_text' + * const convertedStr4 = snakeCase('HTTPRequest') // returns 'http_request' + */ +declare function snakeCase(str: string): string; +//#endregion +export { snakeCase }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/snakeCase.js b/tools/ui/node_modules/es-toolkit/dist/string/snakeCase.js new file mode 100644 index 0000000000000000000000000000000000000000..6a0b518b474163eed70801aedaf89c2dbce01123 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/snakeCase.js @@ -0,0 +1,21 @@ +const require_words = require("./words.js"); +//#region src/string/snakeCase.ts +/** +* Converts a string to snake case. +* +* Snake case is the naming convention in which each word is written in lowercase and separated by an underscore (_) character. +* +* @param {string} str - The string that is to be changed to snake case. +* @returns {string} - The converted string to snake case. +* +* @example +* const convertedStr1 = snakeCase('camelCase') // returns 'camel_case' +* const convertedStr2 = snakeCase('some whitespace') // returns 'some_whitespace' +* const convertedStr3 = snakeCase('hyphen-text') // returns 'hyphen_text' +* const convertedStr4 = snakeCase('HTTPRequest') // returns 'http_request' +*/ +function snakeCase(str) { + return require_words.words(str).map((word) => word.toLowerCase()).join("_"); +} +//#endregion +exports.snakeCase = snakeCase; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/snakeCase.mjs b/tools/ui/node_modules/es-toolkit/dist/string/snakeCase.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5fb00766fa130861f9aa62cc8e049514e26fffd4 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/snakeCase.mjs @@ -0,0 +1,21 @@ +import { words } from "./words.mjs"; +//#region src/string/snakeCase.ts +/** +* Converts a string to snake case. +* +* Snake case is the naming convention in which each word is written in lowercase and separated by an underscore (_) character. +* +* @param {string} str - The string that is to be changed to snake case. +* @returns {string} - The converted string to snake case. +* +* @example +* const convertedStr1 = snakeCase('camelCase') // returns 'camel_case' +* const convertedStr2 = snakeCase('some whitespace') // returns 'some_whitespace' +* const convertedStr3 = snakeCase('hyphen-text') // returns 'hyphen_text' +* const convertedStr4 = snakeCase('HTTPRequest') // returns 'http_request' +*/ +function snakeCase(str) { + return words(str).map((word) => word.toLowerCase()).join("_"); +} +//#endregion +export { snakeCase }; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/startCase.d.mts b/tools/ui/node_modules/es-toolkit/dist/string/startCase.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..4cabadf45ea819c388e68f92dd74a4a4e32d51ff --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/startCase.d.mts @@ -0,0 +1,17 @@ +//#region src/string/startCase.d.ts +/** + * Converts the first character of each word in a string to uppercase and the remaining characters to lowercase. + * + * Start case is the naming convention in which each word is written with an initial capital letter. + * @param {string} str - The string to convert. + * @returns {string} The converted string. + * + * @example + * const result1 = startCase('hello world'); // result will be 'Hello World' + * const result2 = startCase('HELLO WORLD'); // result will be 'Hello World' + * const result3 = startCase('hello-world'); // result will be 'Hello World' + * const result4 = startCase('hello_world'); // result will be 'Hello World' + */ +declare function startCase(str: string): string; +//#endregion +export { startCase }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/startCase.d.ts b/tools/ui/node_modules/es-toolkit/dist/string/startCase.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4cabadf45ea819c388e68f92dd74a4a4e32d51ff --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/startCase.d.ts @@ -0,0 +1,17 @@ +//#region src/string/startCase.d.ts +/** + * Converts the first character of each word in a string to uppercase and the remaining characters to lowercase. + * + * Start case is the naming convention in which each word is written with an initial capital letter. + * @param {string} str - The string to convert. + * @returns {string} The converted string. + * + * @example + * const result1 = startCase('hello world'); // result will be 'Hello World' + * const result2 = startCase('HELLO WORLD'); // result will be 'Hello World' + * const result3 = startCase('hello-world'); // result will be 'Hello World' + * const result4 = startCase('hello_world'); // result will be 'Hello World' + */ +declare function startCase(str: string): string; +//#endregion +export { startCase }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/startCase.js b/tools/ui/node_modules/es-toolkit/dist/string/startCase.js new file mode 100644 index 0000000000000000000000000000000000000000..6e1a467d83f6dad50ed17c0553aea8facdc1cc0a --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/startCase.js @@ -0,0 +1,27 @@ +const require_words = require("./words.js"); +//#region src/string/startCase.ts +/** +* Converts the first character of each word in a string to uppercase and the remaining characters to lowercase. +* +* Start case is the naming convention in which each word is written with an initial capital letter. +* @param {string} str - The string to convert. +* @returns {string} The converted string. +* +* @example +* const result1 = startCase('hello world'); // result will be 'Hello World' +* const result2 = startCase('HELLO WORLD'); // result will be 'Hello World' +* const result3 = startCase('hello-world'); // result will be 'Hello World' +* const result4 = startCase('hello_world'); // result will be 'Hello World' +*/ +function startCase(str) { + const words$1 = require_words.words(str.trim()); + let result = ""; + for (let i = 0; i < words$1.length; i++) { + const word = words$1[i]; + if (result) result += " "; + result += word[0].toUpperCase() + word.slice(1).toLowerCase(); + } + return result; +} +//#endregion +exports.startCase = startCase; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/startCase.mjs b/tools/ui/node_modules/es-toolkit/dist/string/startCase.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8eb7f016a1cd44425b29b14443be09e4e87e43b3 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/startCase.mjs @@ -0,0 +1,27 @@ +import { words } from "./words.mjs"; +//#region src/string/startCase.ts +/** +* Converts the first character of each word in a string to uppercase and the remaining characters to lowercase. +* +* Start case is the naming convention in which each word is written with an initial capital letter. +* @param {string} str - The string to convert. +* @returns {string} The converted string. +* +* @example +* const result1 = startCase('hello world'); // result will be 'Hello World' +* const result2 = startCase('HELLO WORLD'); // result will be 'Hello World' +* const result3 = startCase('hello-world'); // result will be 'Hello World' +* const result4 = startCase('hello_world'); // result will be 'Hello World' +*/ +function startCase(str) { + const words$1 = words(str.trim()); + let result = ""; + for (let i = 0; i < words$1.length; i++) { + const word = words$1[i]; + if (result) result += " "; + result += word[0].toUpperCase() + word.slice(1).toLowerCase(); + } + return result; +} +//#endregion +export { startCase }; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/trim.d.mts b/tools/ui/node_modules/es-toolkit/dist/string/trim.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..220f3cffe7fb548a8fe4aebbd7a085fe248b6d09 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/trim.d.mts @@ -0,0 +1,16 @@ +//#region src/string/trim.d.ts +/** + * Removes leading and trailing whitespace or specified characters from a string. + * + * @param {string} str - The string from which characters will be trimmed. + * @param {string | string[]} chars - The character(s) to remove from the string. Can be a single character or an array of characters. + * @returns {string} - The resulting string after the specified characters have been removed. + * + * @example + * trim(" hello "); // "hello" + * trim("--hello--", "-"); // "hello" + * trim("##hello##", ["#", "o"]); // "hell" + */ +declare function trim(str: string, chars?: string | string[]): string; +//#endregion +export { trim }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/trim.d.ts b/tools/ui/node_modules/es-toolkit/dist/string/trim.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..220f3cffe7fb548a8fe4aebbd7a085fe248b6d09 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/trim.d.ts @@ -0,0 +1,16 @@ +//#region src/string/trim.d.ts +/** + * Removes leading and trailing whitespace or specified characters from a string. + * + * @param {string} str - The string from which characters will be trimmed. + * @param {string | string[]} chars - The character(s) to remove from the string. Can be a single character or an array of characters. + * @returns {string} - The resulting string after the specified characters have been removed. + * + * @example + * trim(" hello "); // "hello" + * trim("--hello--", "-"); // "hello" + * trim("##hello##", ["#", "o"]); // "hell" + */ +declare function trim(str: string, chars?: string | string[]): string; +//#endregion +export { trim }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/trim.js b/tools/ui/node_modules/es-toolkit/dist/string/trim.js new file mode 100644 index 0000000000000000000000000000000000000000..df642a0535d96e9a5badc5ad7e6b73a5bd04b36e --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/trim.js @@ -0,0 +1,21 @@ +const require_trimEnd = require("./trimEnd.js"); +const require_trimStart = require("./trimStart.js"); +//#region src/string/trim.ts +/** +* Removes leading and trailing whitespace or specified characters from a string. +* +* @param {string} str - The string from which characters will be trimmed. +* @param {string | string[]} chars - The character(s) to remove from the string. Can be a single character or an array of characters. +* @returns {string} - The resulting string after the specified characters have been removed. +* +* @example +* trim(" hello "); // "hello" +* trim("--hello--", "-"); // "hello" +* trim("##hello##", ["#", "o"]); // "hell" +*/ +function trim(str, chars) { + if (chars === void 0) return str.trim(); + return require_trimStart.trimStart(require_trimEnd.trimEnd(str, chars), chars); +} +//#endregion +exports.trim = trim; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/trim.mjs b/tools/ui/node_modules/es-toolkit/dist/string/trim.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3a41fe4bb64a254ed0ec149f80830e037bc97a43 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/trim.mjs @@ -0,0 +1,21 @@ +import { trimEnd } from "./trimEnd.mjs"; +import { trimStart } from "./trimStart.mjs"; +//#region src/string/trim.ts +/** +* Removes leading and trailing whitespace or specified characters from a string. +* +* @param {string} str - The string from which characters will be trimmed. +* @param {string | string[]} chars - The character(s) to remove from the string. Can be a single character or an array of characters. +* @returns {string} - The resulting string after the specified characters have been removed. +* +* @example +* trim(" hello "); // "hello" +* trim("--hello--", "-"); // "hello" +* trim("##hello##", ["#", "o"]); // "hell" +*/ +function trim(str, chars) { + if (chars === void 0) return str.trim(); + return trimStart(trimEnd(str, chars), chars); +} +//#endregion +export { trim }; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/trimEnd.d.mts b/tools/ui/node_modules/es-toolkit/dist/string/trimEnd.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..d20c89b1af139dd74d029213fb3ba9ac3357a84b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/trimEnd.d.mts @@ -0,0 +1,20 @@ +//#region src/string/trimEnd.d.ts +/** + * Removes trailing whitespace or specified characters from a string. + * + * If `chars` is a string, it should be a single character. To trim a string with multiple characters, + * provide an array instead. + * + * @param {string} str - The string from which trailing characters will be trimmed. + * @param {string | string[]} chars - The character(s) to remove from the end of the string. + * @returns {string} - The resulting string after the specified trailing character has been removed. + * + * @example + * const trimmedStr1 = trimEnd('hello---', '-') // returns 'hello' + * const trimmedStr2 = trimEnd('123000', '0') // returns '123' + * const trimmedStr3 = trimEnd('abcabcabc', 'c') // returns 'abcabcab' + * const trimmedStr4 = trimEnd('trimmedxxx', 'x') // returns 'trimmed' + */ +declare function trimEnd(str: string, chars?: string | string[]): string; +//#endregion +export { trimEnd }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/trimEnd.d.ts b/tools/ui/node_modules/es-toolkit/dist/string/trimEnd.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d20c89b1af139dd74d029213fb3ba9ac3357a84b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/trimEnd.d.ts @@ -0,0 +1,20 @@ +//#region src/string/trimEnd.d.ts +/** + * Removes trailing whitespace or specified characters from a string. + * + * If `chars` is a string, it should be a single character. To trim a string with multiple characters, + * provide an array instead. + * + * @param {string} str - The string from which trailing characters will be trimmed. + * @param {string | string[]} chars - The character(s) to remove from the end of the string. + * @returns {string} - The resulting string after the specified trailing character has been removed. + * + * @example + * const trimmedStr1 = trimEnd('hello---', '-') // returns 'hello' + * const trimmedStr2 = trimEnd('123000', '0') // returns '123' + * const trimmedStr3 = trimEnd('abcabcabc', 'c') // returns 'abcabcab' + * const trimmedStr4 = trimEnd('trimmedxxx', 'x') // returns 'trimmed' + */ +declare function trimEnd(str: string, chars?: string | string[]): string; +//#endregion +export { trimEnd }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/trimEnd.js b/tools/ui/node_modules/es-toolkit/dist/string/trimEnd.js new file mode 100644 index 0000000000000000000000000000000000000000..02296750a2fb803ca81c069b3269ac269cafca5e --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/trimEnd.js @@ -0,0 +1,31 @@ +//#region src/string/trimEnd.ts +/** +* Removes trailing whitespace or specified characters from a string. +* +* If `chars` is a string, it should be a single character. To trim a string with multiple characters, +* provide an array instead. +* +* @param {string} str - The string from which trailing characters will be trimmed. +* @param {string | string[]} chars - The character(s) to remove from the end of the string. +* @returns {string} - The resulting string after the specified trailing character has been removed. +* +* @example +* const trimmedStr1 = trimEnd('hello---', '-') // returns 'hello' +* const trimmedStr2 = trimEnd('123000', '0') // returns '123' +* const trimmedStr3 = trimEnd('abcabcabc', 'c') // returns 'abcabcab' +* const trimmedStr4 = trimEnd('trimmedxxx', 'x') // returns 'trimmed' +*/ +function trimEnd(str, chars) { + if (chars === void 0) return str.trimEnd(); + let endIndex = str.length; + switch (typeof chars) { + case "string": + if (chars.length !== 1) throw new Error(`The 'chars' parameter should be a single character string.`); + while (endIndex > 0 && str[endIndex - 1] === chars) endIndex--; + break; + case "object": while (endIndex > 0 && chars.includes(str[endIndex - 1])) endIndex--; + } + return str.substring(0, endIndex); +} +//#endregion +exports.trimEnd = trimEnd; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/trimEnd.mjs b/tools/ui/node_modules/es-toolkit/dist/string/trimEnd.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6a552c21b7ce5af6387b9430b4ba7e58862842cf --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/trimEnd.mjs @@ -0,0 +1,31 @@ +//#region src/string/trimEnd.ts +/** +* Removes trailing whitespace or specified characters from a string. +* +* If `chars` is a string, it should be a single character. To trim a string with multiple characters, +* provide an array instead. +* +* @param {string} str - The string from which trailing characters will be trimmed. +* @param {string | string[]} chars - The character(s) to remove from the end of the string. +* @returns {string} - The resulting string after the specified trailing character has been removed. +* +* @example +* const trimmedStr1 = trimEnd('hello---', '-') // returns 'hello' +* const trimmedStr2 = trimEnd('123000', '0') // returns '123' +* const trimmedStr3 = trimEnd('abcabcabc', 'c') // returns 'abcabcab' +* const trimmedStr4 = trimEnd('trimmedxxx', 'x') // returns 'trimmed' +*/ +function trimEnd(str, chars) { + if (chars === void 0) return str.trimEnd(); + let endIndex = str.length; + switch (typeof chars) { + case "string": + if (chars.length !== 1) throw new Error(`The 'chars' parameter should be a single character string.`); + while (endIndex > 0 && str[endIndex - 1] === chars) endIndex--; + break; + case "object": while (endIndex > 0 && chars.includes(str[endIndex - 1])) endIndex--; + } + return str.substring(0, endIndex); +} +//#endregion +export { trimEnd }; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/trimStart.d.mts b/tools/ui/node_modules/es-toolkit/dist/string/trimStart.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..6a53c6af11f918036e59822d98ead335c04d5d5a --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/trimStart.d.mts @@ -0,0 +1,20 @@ +//#region src/string/trimStart.d.ts +/** + * Removes leading whitespace or specified characters from a string. + * + * If `chars` is a string, it should be a single character. To trim a string with multiple characters, + * provide an array instead. + * + * @param {string} str - The string from which leading characters will be trimmed. + * @param {string | string[]} chars - The character(s) to remove from the start of the string. + * @returns {string} - The resulting string after the specified leading character has been removed. + * + * @example + * const trimmedStr1 = trimStart('---hello', '-') // returns 'hello' + * const trimmedStr2 = trimStart('000123', '0') // returns '123' + * const trimmedStr3 = trimStart('abcabcabc', 'a') // returns 'bcabcabc' + * const trimmedStr4 = trimStart('xxxtrimmed', 'x') // returns 'trimmed' + */ +declare function trimStart(str: string, chars?: string | string[]): string; +//#endregion +export { trimStart }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/trimStart.d.ts b/tools/ui/node_modules/es-toolkit/dist/string/trimStart.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6a53c6af11f918036e59822d98ead335c04d5d5a --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/trimStart.d.ts @@ -0,0 +1,20 @@ +//#region src/string/trimStart.d.ts +/** + * Removes leading whitespace or specified characters from a string. + * + * If `chars` is a string, it should be a single character. To trim a string with multiple characters, + * provide an array instead. + * + * @param {string} str - The string from which leading characters will be trimmed. + * @param {string | string[]} chars - The character(s) to remove from the start of the string. + * @returns {string} - The resulting string after the specified leading character has been removed. + * + * @example + * const trimmedStr1 = trimStart('---hello', '-') // returns 'hello' + * const trimmedStr2 = trimStart('000123', '0') // returns '123' + * const trimmedStr3 = trimStart('abcabcabc', 'a') // returns 'bcabcabc' + * const trimmedStr4 = trimStart('xxxtrimmed', 'x') // returns 'trimmed' + */ +declare function trimStart(str: string, chars?: string | string[]): string; +//#endregion +export { trimStart }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/trimStart.js b/tools/ui/node_modules/es-toolkit/dist/string/trimStart.js new file mode 100644 index 0000000000000000000000000000000000000000..fa16a141da0735ec7152747bf0e434d9e72f61f0 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/trimStart.js @@ -0,0 +1,30 @@ +//#region src/string/trimStart.ts +/** +* Removes leading whitespace or specified characters from a string. +* +* If `chars` is a string, it should be a single character. To trim a string with multiple characters, +* provide an array instead. +* +* @param {string} str - The string from which leading characters will be trimmed. +* @param {string | string[]} chars - The character(s) to remove from the start of the string. +* @returns {string} - The resulting string after the specified leading character has been removed. +* +* @example +* const trimmedStr1 = trimStart('---hello', '-') // returns 'hello' +* const trimmedStr2 = trimStart('000123', '0') // returns '123' +* const trimmedStr3 = trimStart('abcabcabc', 'a') // returns 'bcabcabc' +* const trimmedStr4 = trimStart('xxxtrimmed', 'x') // returns 'trimmed' +*/ +function trimStart(str, chars) { + if (chars === void 0) return str.trimStart(); + let startIndex = 0; + switch (typeof chars) { + case "string": + while (startIndex < str.length && str[startIndex] === chars) startIndex++; + break; + case "object": while (startIndex < str.length && chars.includes(str[startIndex])) startIndex++; + } + return str.substring(startIndex); +} +//#endregion +exports.trimStart = trimStart; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/trimStart.mjs b/tools/ui/node_modules/es-toolkit/dist/string/trimStart.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5a0ec9059764cb52e3f418b5e4297cf0147af270 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/trimStart.mjs @@ -0,0 +1,30 @@ +//#region src/string/trimStart.ts +/** +* Removes leading whitespace or specified characters from a string. +* +* If `chars` is a string, it should be a single character. To trim a string with multiple characters, +* provide an array instead. +* +* @param {string} str - The string from which leading characters will be trimmed. +* @param {string | string[]} chars - The character(s) to remove from the start of the string. +* @returns {string} - The resulting string after the specified leading character has been removed. +* +* @example +* const trimmedStr1 = trimStart('---hello', '-') // returns 'hello' +* const trimmedStr2 = trimStart('000123', '0') // returns '123' +* const trimmedStr3 = trimStart('abcabcabc', 'a') // returns 'bcabcabc' +* const trimmedStr4 = trimStart('xxxtrimmed', 'x') // returns 'trimmed' +*/ +function trimStart(str, chars) { + if (chars === void 0) return str.trimStart(); + let startIndex = 0; + switch (typeof chars) { + case "string": + while (startIndex < str.length && str[startIndex] === chars) startIndex++; + break; + case "object": while (startIndex < str.length && chars.includes(str[startIndex])) startIndex++; + } + return str.substring(startIndex); +} +//#endregion +export { trimStart }; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/unescape.d.mts b/tools/ui/node_modules/es-toolkit/dist/string/unescape.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..6dc7095299331b33446a73056ec03d401e553f77 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/unescape.d.mts @@ -0,0 +1,17 @@ +//#region src/string/unescape.d.ts +/** + * Converts the HTML entities `&`, `<`, `>`, `"`, and `'` in `str` to their corresponding characters. + * It is the inverse of `escape`. + * + * @param {string} str The string to unescape. + * @returns {string} Returns the unescaped string. + * + * @example + * unescape('This is a <div> element.'); // returns 'This is a
element.' + * unescape('This is a "quote"'); // returns 'This is a "quote"' + * unescape('This is a 'quote''); // returns 'This is a 'quote'' + * unescape('This is a & symbol'); // returns 'This is a & symbol' + */ +declare function unescape(str: string): string; +//#endregion +export { unescape }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/unescape.d.ts b/tools/ui/node_modules/es-toolkit/dist/string/unescape.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6dc7095299331b33446a73056ec03d401e553f77 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/unescape.d.ts @@ -0,0 +1,17 @@ +//#region src/string/unescape.d.ts +/** + * Converts the HTML entities `&`, `<`, `>`, `"`, and `'` in `str` to their corresponding characters. + * It is the inverse of `escape`. + * + * @param {string} str The string to unescape. + * @returns {string} Returns the unescaped string. + * + * @example + * unescape('This is a <div> element.'); // returns 'This is a
element.' + * unescape('This is a "quote"'); // returns 'This is a "quote"' + * unescape('This is a 'quote''); // returns 'This is a 'quote'' + * unescape('This is a & symbol'); // returns 'This is a & symbol' + */ +declare function unescape(str: string): string; +//#endregion +export { unescape }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/unescape.js b/tools/ui/node_modules/es-toolkit/dist/string/unescape.js new file mode 100644 index 0000000000000000000000000000000000000000..bb357c438d7061ee503456cfd95ad3c486c208ed --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/unescape.js @@ -0,0 +1,26 @@ +//#region src/string/unescape.ts +const htmlUnescapes = { + "&": "&", + "<": "<", + ">": ">", + """: "\"", + "'": "'" +}; +/** +* Converts the HTML entities `&`, `<`, `>`, `"`, and `'` in `str` to their corresponding characters. +* It is the inverse of `escape`. +* +* @param {string} str The string to unescape. +* @returns {string} Returns the unescaped string. +* +* @example +* unescape('This is a <div> element.'); // returns 'This is a
element.' +* unescape('This is a "quote"'); // returns 'This is a "quote"' +* unescape('This is a 'quote''); // returns 'This is a 'quote'' +* unescape('This is a & symbol'); // returns 'This is a & symbol' +*/ +function unescape(str) { + return str.replace(/&(?:amp|lt|gt|quot|#(0+)?39);/g, (match) => htmlUnescapes[match] || "'"); +} +//#endregion +exports.unescape = unescape; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/unescape.mjs b/tools/ui/node_modules/es-toolkit/dist/string/unescape.mjs new file mode 100644 index 0000000000000000000000000000000000000000..bba1eb5d33ccbc6abfea182b7676985638de5819 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/unescape.mjs @@ -0,0 +1,26 @@ +//#region src/string/unescape.ts +const htmlUnescapes = { + "&": "&", + "<": "<", + ">": ">", + """: "\"", + "'": "'" +}; +/** +* Converts the HTML entities `&`, `<`, `>`, `"`, and `'` in `str` to their corresponding characters. +* It is the inverse of `escape`. +* +* @param {string} str The string to unescape. +* @returns {string} Returns the unescaped string. +* +* @example +* unescape('This is a <div> element.'); // returns 'This is a
element.' +* unescape('This is a "quote"'); // returns 'This is a "quote"' +* unescape('This is a 'quote''); // returns 'This is a 'quote'' +* unescape('This is a & symbol'); // returns 'This is a & symbol' +*/ +function unescape(str) { + return str.replace(/&(?:amp|lt|gt|quot|#(0+)?39);/g, (match) => htmlUnescapes[match] || "'"); +} +//#endregion +export { unescape }; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/upperCase.d.mts b/tools/ui/node_modules/es-toolkit/dist/string/upperCase.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..dcf6fd600ac20d26fd13cbd71bf70c53fffae24e --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/upperCase.d.mts @@ -0,0 +1,18 @@ +//#region src/string/upperCase.d.ts +/** + * Converts a string to upper case. + * + * Upper case is the naming convention in which each word is written in uppercase and separated by an space ( ) character. + * + * @param {string} str - The string that is to be changed to upper case. + * @returns {string} - The converted string to upper case. + * + * @example + * const convertedStr1 = upperCase('camelCase') // returns 'CAMEL CASE' + * const convertedStr2 = upperCase('some whitespace') // returns 'SOME WHITESPACE' + * const convertedStr3 = upperCase('hyphen-text') // returns 'HYPHEN TEXT' + * const convertedStr4 = upperCase('HTTPRequest') // returns 'HTTP REQUEST' + */ +declare function upperCase(str: string): string; +//#endregion +export { upperCase }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/upperCase.d.ts b/tools/ui/node_modules/es-toolkit/dist/string/upperCase.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dcf6fd600ac20d26fd13cbd71bf70c53fffae24e --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/upperCase.d.ts @@ -0,0 +1,18 @@ +//#region src/string/upperCase.d.ts +/** + * Converts a string to upper case. + * + * Upper case is the naming convention in which each word is written in uppercase and separated by an space ( ) character. + * + * @param {string} str - The string that is to be changed to upper case. + * @returns {string} - The converted string to upper case. + * + * @example + * const convertedStr1 = upperCase('camelCase') // returns 'CAMEL CASE' + * const convertedStr2 = upperCase('some whitespace') // returns 'SOME WHITESPACE' + * const convertedStr3 = upperCase('hyphen-text') // returns 'HYPHEN TEXT' + * const convertedStr4 = upperCase('HTTPRequest') // returns 'HTTP REQUEST' + */ +declare function upperCase(str: string): string; +//#endregion +export { upperCase }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/upperCase.js b/tools/ui/node_modules/es-toolkit/dist/string/upperCase.js new file mode 100644 index 0000000000000000000000000000000000000000..0d5c5e3159f57681aefdc951e13e6bc15bc6710f --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/upperCase.js @@ -0,0 +1,27 @@ +const require_words = require("./words.js"); +//#region src/string/upperCase.ts +/** +* Converts a string to upper case. +* +* Upper case is the naming convention in which each word is written in uppercase and separated by an space ( ) character. +* +* @param {string} str - The string that is to be changed to upper case. +* @returns {string} - The converted string to upper case. +* +* @example +* const convertedStr1 = upperCase('camelCase') // returns 'CAMEL CASE' +* const convertedStr2 = upperCase('some whitespace') // returns 'SOME WHITESPACE' +* const convertedStr3 = upperCase('hyphen-text') // returns 'HYPHEN TEXT' +* const convertedStr4 = upperCase('HTTPRequest') // returns 'HTTP REQUEST' +*/ +function upperCase(str) { + const words$1 = require_words.words(str); + let result = ""; + for (let i = 0; i < words$1.length; i++) { + result += words$1[i].toUpperCase(); + if (i < words$1.length - 1) result += " "; + } + return result; +} +//#endregion +exports.upperCase = upperCase; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/upperCase.mjs b/tools/ui/node_modules/es-toolkit/dist/string/upperCase.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d38b9dd6c76ec5549181d6117b92e073968d65bf --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/upperCase.mjs @@ -0,0 +1,27 @@ +import { words } from "./words.mjs"; +//#region src/string/upperCase.ts +/** +* Converts a string to upper case. +* +* Upper case is the naming convention in which each word is written in uppercase and separated by an space ( ) character. +* +* @param {string} str - The string that is to be changed to upper case. +* @returns {string} - The converted string to upper case. +* +* @example +* const convertedStr1 = upperCase('camelCase') // returns 'CAMEL CASE' +* const convertedStr2 = upperCase('some whitespace') // returns 'SOME WHITESPACE' +* const convertedStr3 = upperCase('hyphen-text') // returns 'HYPHEN TEXT' +* const convertedStr4 = upperCase('HTTPRequest') // returns 'HTTP REQUEST' +*/ +function upperCase(str) { + const words$1 = words(str); + let result = ""; + for (let i = 0; i < words$1.length; i++) { + result += words$1[i].toUpperCase(); + if (i < words$1.length - 1) result += " "; + } + return result; +} +//#endregion +export { upperCase }; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/upperFirst.d.mts b/tools/ui/node_modules/es-toolkit/dist/string/upperFirst.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..582caf58608384ac26850786ab763cb305884dc7 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/upperFirst.d.mts @@ -0,0 +1,15 @@ +//#region src/string/upperFirst.d.ts +/** + * Converts the first character of string to upper case. + * + * @param {string} str - The string that is to be changed + * @returns {string} - The converted string. + * + * @example + * const convertedStr1 = upperFirst('fred') // returns 'Fred' + * const convertedStr2 = upperFirst('Fred') // returns 'Fred' + * const convertedStr3 = upperFirst('FRED') // returns 'FRED' + */ +declare function upperFirst(str: string): string; +//#endregion +export { upperFirst }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/upperFirst.d.ts b/tools/ui/node_modules/es-toolkit/dist/string/upperFirst.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..582caf58608384ac26850786ab763cb305884dc7 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/upperFirst.d.ts @@ -0,0 +1,15 @@ +//#region src/string/upperFirst.d.ts +/** + * Converts the first character of string to upper case. + * + * @param {string} str - The string that is to be changed + * @returns {string} - The converted string. + * + * @example + * const convertedStr1 = upperFirst('fred') // returns 'Fred' + * const convertedStr2 = upperFirst('Fred') // returns 'Fred' + * const convertedStr3 = upperFirst('FRED') // returns 'FRED' + */ +declare function upperFirst(str: string): string; +//#endregion +export { upperFirst }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/upperFirst.js b/tools/ui/node_modules/es-toolkit/dist/string/upperFirst.js new file mode 100644 index 0000000000000000000000000000000000000000..a8e7faa5df976d9912cd824db73c49206b03135a --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/upperFirst.js @@ -0,0 +1,17 @@ +//#region src/string/upperFirst.ts +/** +* Converts the first character of string to upper case. +* +* @param {string} str - The string that is to be changed +* @returns {string} - The converted string. +* +* @example +* const convertedStr1 = upperFirst('fred') // returns 'Fred' +* const convertedStr2 = upperFirst('Fred') // returns 'Fred' +* const convertedStr3 = upperFirst('FRED') // returns 'FRED' +*/ +function upperFirst(str) { + return str.substring(0, 1).toUpperCase() + str.substring(1); +} +//#endregion +exports.upperFirst = upperFirst; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/upperFirst.mjs b/tools/ui/node_modules/es-toolkit/dist/string/upperFirst.mjs new file mode 100644 index 0000000000000000000000000000000000000000..df0922a78249062d57d92ef2ee9d82ec38b6d57a --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/upperFirst.mjs @@ -0,0 +1,17 @@ +//#region src/string/upperFirst.ts +/** +* Converts the first character of string to upper case. +* +* @param {string} str - The string that is to be changed +* @returns {string} - The converted string. +* +* @example +* const convertedStr1 = upperFirst('fred') // returns 'Fred' +* const convertedStr2 = upperFirst('Fred') // returns 'Fred' +* const convertedStr3 = upperFirst('FRED') // returns 'FRED' +*/ +function upperFirst(str) { + return str.substring(0, 1).toUpperCase() + str.substring(1); +} +//#endregion +export { upperFirst }; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/words.d.mts b/tools/ui/node_modules/es-toolkit/dist/string/words.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..d7c5dee6b54b691078f84b6cb12efb465297350f --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/words.d.mts @@ -0,0 +1,39 @@ +//#region src/string/words.d.ts +/** + * Regular expression pattern to split strings into words for various case conversions + * + * This pattern matches sequences of characters in a string, considering the following cases: + * - Sequences of two or more uppercase letters followed by an uppercase letter and lowercase letters or digits (for acronyms) + * - Sequences of one uppercase letter optionally followed by lowercase letters and digits + * - Single uppercase letters + * - Sequences of digits + * - Emojis and other Unicode characters + * + * The resulting match can be used to convert camelCase, snake_case, kebab-case, and other mixed formats into + * a consistent format like snake case. It also supports emojis and other Unicode characters. + * + * @example + * const matches = 'camelCaseHTTPRequest🚀'.match(CASE_SPLIT_PATTERN); + * // matches: ['camel', 'Case', 'HTTP', 'Request', '🚀'] + */ +declare const CASE_SPLIT_PATTERN: RegExp; +/** + * Splits `string` into an array of its words, treating spaces and punctuation marks as separators. + * + * @param {string} str The string to inspect. + * @param {RegExp | string} [pattern] The pattern to match words. + * @returns {string[]} Returns the words of `string`. + * + * @example + * words('fred, barney, & pebbles'); + * // => ['fred', 'barney', 'pebbles'] + * + * words('camelCaseHTTPRequest🚀'); + * // => ['camel', 'Case', 'HTTP', 'Request', '🚀'] + * + * words('Lunedì 18 Set') + * // => ['Lunedì', '18', 'Set'] + */ +declare function words(str: string): string[]; +//#endregion +export { words }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/words.d.ts b/tools/ui/node_modules/es-toolkit/dist/string/words.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d7c5dee6b54b691078f84b6cb12efb465297350f --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/words.d.ts @@ -0,0 +1,39 @@ +//#region src/string/words.d.ts +/** + * Regular expression pattern to split strings into words for various case conversions + * + * This pattern matches sequences of characters in a string, considering the following cases: + * - Sequences of two or more uppercase letters followed by an uppercase letter and lowercase letters or digits (for acronyms) + * - Sequences of one uppercase letter optionally followed by lowercase letters and digits + * - Single uppercase letters + * - Sequences of digits + * - Emojis and other Unicode characters + * + * The resulting match can be used to convert camelCase, snake_case, kebab-case, and other mixed formats into + * a consistent format like snake case. It also supports emojis and other Unicode characters. + * + * @example + * const matches = 'camelCaseHTTPRequest🚀'.match(CASE_SPLIT_PATTERN); + * // matches: ['camel', 'Case', 'HTTP', 'Request', '🚀'] + */ +declare const CASE_SPLIT_PATTERN: RegExp; +/** + * Splits `string` into an array of its words, treating spaces and punctuation marks as separators. + * + * @param {string} str The string to inspect. + * @param {RegExp | string} [pattern] The pattern to match words. + * @returns {string[]} Returns the words of `string`. + * + * @example + * words('fred, barney, & pebbles'); + * // => ['fred', 'barney', 'pebbles'] + * + * words('camelCaseHTTPRequest🚀'); + * // => ['camel', 'Case', 'HTTP', 'Request', '🚀'] + * + * words('Lunedì 18 Set') + * // => ['Lunedì', '18', 'Set'] + */ +declare function words(str: string): string[]; +//#endregion +export { words }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/string/words.js b/tools/ui/node_modules/es-toolkit/dist/string/words.js new file mode 100644 index 0000000000000000000000000000000000000000..7bade530624573b19fa1d43c9f8e7993f75d4fdd --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/words.js @@ -0,0 +1,41 @@ +//#region src/string/words.ts +/** +* Regular expression pattern to split strings into words for various case conversions +* +* This pattern matches sequences of characters in a string, considering the following cases: +* - Sequences of two or more uppercase letters followed by an uppercase letter and lowercase letters or digits (for acronyms) +* - Sequences of one uppercase letter optionally followed by lowercase letters and digits +* - Single uppercase letters +* - Sequences of digits +* - Emojis and other Unicode characters +* +* The resulting match can be used to convert camelCase, snake_case, kebab-case, and other mixed formats into +* a consistent format like snake case. It also supports emojis and other Unicode characters. +* +* @example +* const matches = 'camelCaseHTTPRequest🚀'.match(CASE_SPLIT_PATTERN); +* // matches: ['camel', 'Case', 'HTTP', 'Request', '🚀'] +*/ +const CASE_SPLIT_PATTERN = /\p{Lu}?\p{Ll}+|[0-9]+|\p{Lu}+(?!\p{Ll})|\p{Emoji_Presentation}|\p{Extended_Pictographic}|\p{L}+/gu; +/** +* Splits `string` into an array of its words, treating spaces and punctuation marks as separators. +* +* @param {string} str The string to inspect. +* @param {RegExp | string} [pattern] The pattern to match words. +* @returns {string[]} Returns the words of `string`. +* +* @example +* words('fred, barney, & pebbles'); +* // => ['fred', 'barney', 'pebbles'] +* +* words('camelCaseHTTPRequest🚀'); +* // => ['camel', 'Case', 'HTTP', 'Request', '🚀'] +* +* words('Lunedì 18 Set') +* // => ['Lunedì', '18', 'Set'] +*/ +function words(str) { + return Array.from(str.match(CASE_SPLIT_PATTERN) ?? []); +} +//#endregion +exports.words = words; diff --git a/tools/ui/node_modules/es-toolkit/dist/string/words.mjs b/tools/ui/node_modules/es-toolkit/dist/string/words.mjs new file mode 100644 index 0000000000000000000000000000000000000000..66d1e88f1ad7d2036f27020d9844ad24887d673c --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/string/words.mjs @@ -0,0 +1,41 @@ +//#region src/string/words.ts +/** +* Regular expression pattern to split strings into words for various case conversions +* +* This pattern matches sequences of characters in a string, considering the following cases: +* - Sequences of two or more uppercase letters followed by an uppercase letter and lowercase letters or digits (for acronyms) +* - Sequences of one uppercase letter optionally followed by lowercase letters and digits +* - Single uppercase letters +* - Sequences of digits +* - Emojis and other Unicode characters +* +* The resulting match can be used to convert camelCase, snake_case, kebab-case, and other mixed formats into +* a consistent format like snake case. It also supports emojis and other Unicode characters. +* +* @example +* const matches = 'camelCaseHTTPRequest🚀'.match(CASE_SPLIT_PATTERN); +* // matches: ['camel', 'Case', 'HTTP', 'Request', '🚀'] +*/ +const CASE_SPLIT_PATTERN = /\p{Lu}?\p{Ll}+|[0-9]+|\p{Lu}+(?!\p{Ll})|\p{Emoji_Presentation}|\p{Extended_Pictographic}|\p{L}+/gu; +/** +* Splits `string` into an array of its words, treating spaces and punctuation marks as separators. +* +* @param {string} str The string to inspect. +* @param {RegExp | string} [pattern] The pattern to match words. +* @returns {string[]} Returns the words of `string`. +* +* @example +* words('fred, barney, & pebbles'); +* // => ['fred', 'barney', 'pebbles'] +* +* words('camelCaseHTTPRequest🚀'); +* // => ['camel', 'Case', 'HTTP', 'Request', '🚀'] +* +* words('Lunedì 18 Set') +* // => ['Lunedì', '18', 'Set'] +*/ +function words(str) { + return Array.from(str.match(CASE_SPLIT_PATTERN) ?? []); +} +//#endregion +export { words }; diff --git a/tools/ui/node_modules/es-toolkit/dist/util/attempt.d.mts b/tools/ui/node_modules/es-toolkit/dist/util/attempt.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..2eab71ec25eb4c565fbc7a97d345fb29bf7b9fa8 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/util/attempt.d.mts @@ -0,0 +1,43 @@ +//#region src/util/attempt.d.ts +/** + * Attempt to execute a function and return the result or error. + * Returns a tuple where: + * - On success: [null, Result] - First element is null, second is the result + * - On error: [Error, null] - First element is the caught error, second is null + * + * @template {unknown} T - The type of the result of the function. + * @template {unknown} E - The type of the error that can be thrown by the function. + * @param {() => T} func - The function to execute. + * @returns {[null, T] | [E, null]} A tuple containing either [null, result] or [error, null]. + * + * @example + * // Successful execution + * const [error, result] = attempt(() => 42); + * // [null, 42] + * + * // Failed execution + * const [error, result] = attempt(() => { + * throw new Error('Something went wrong'); + * }); + * // [Error, null] + * + * // With type parameter + * const [error, names] = attempt(() => ['Alice', 'Bob']); + * // [null, ['Alice', 'Bob']] + * + * @note + * Important: This function is not suitable for async functions (functions that return a `Promise`). + * When passing an async function, it will return `[null, Promise]`, but won't catch any + * errors if the Promise is rejected later. + * + * For handling async functions, use the `attemptAsync` function instead: + * ``` + * const [error, data] = await attemptAsync(async () => { + * const response = await fetch('https://api.example.com/data'); + * return response.json(); + * }); + * ``` + */ +declare function attempt(func: () => T): [null, T] | [E, null]; +//#endregion +export { attempt }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/util/attempt.d.ts b/tools/ui/node_modules/es-toolkit/dist/util/attempt.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2eab71ec25eb4c565fbc7a97d345fb29bf7b9fa8 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/util/attempt.d.ts @@ -0,0 +1,43 @@ +//#region src/util/attempt.d.ts +/** + * Attempt to execute a function and return the result or error. + * Returns a tuple where: + * - On success: [null, Result] - First element is null, second is the result + * - On error: [Error, null] - First element is the caught error, second is null + * + * @template {unknown} T - The type of the result of the function. + * @template {unknown} E - The type of the error that can be thrown by the function. + * @param {() => T} func - The function to execute. + * @returns {[null, T] | [E, null]} A tuple containing either [null, result] or [error, null]. + * + * @example + * // Successful execution + * const [error, result] = attempt(() => 42); + * // [null, 42] + * + * // Failed execution + * const [error, result] = attempt(() => { + * throw new Error('Something went wrong'); + * }); + * // [Error, null] + * + * // With type parameter + * const [error, names] = attempt(() => ['Alice', 'Bob']); + * // [null, ['Alice', 'Bob']] + * + * @note + * Important: This function is not suitable for async functions (functions that return a `Promise`). + * When passing an async function, it will return `[null, Promise]`, but won't catch any + * errors if the Promise is rejected later. + * + * For handling async functions, use the `attemptAsync` function instead: + * ``` + * const [error, data] = await attemptAsync(async () => { + * const response = await fetch('https://api.example.com/data'); + * return response.json(); + * }); + * ``` + */ +declare function attempt(func: () => T): [null, T] | [E, null]; +//#endregion +export { attempt }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/util/attempt.js b/tools/ui/node_modules/es-toolkit/dist/util/attempt.js new file mode 100644 index 0000000000000000000000000000000000000000..f19bffdf34239b1ba103dedd093a2865c9b3d20b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/util/attempt.js @@ -0,0 +1,49 @@ +//#region src/util/attempt.ts +/** +* Attempt to execute a function and return the result or error. +* Returns a tuple where: +* - On success: [null, Result] - First element is null, second is the result +* - On error: [Error, null] - First element is the caught error, second is null +* +* @template {unknown} T - The type of the result of the function. +* @template {unknown} E - The type of the error that can be thrown by the function. +* @param {() => T} func - The function to execute. +* @returns {[null, T] | [E, null]} A tuple containing either [null, result] or [error, null]. +* +* @example +* // Successful execution +* const [error, result] = attempt(() => 42); +* // [null, 42] +* +* // Failed execution +* const [error, result] = attempt(() => { +* throw new Error('Something went wrong'); +* }); +* // [Error, null] +* +* // With type parameter +* const [error, names] = attempt(() => ['Alice', 'Bob']); +* // [null, ['Alice', 'Bob']] +* +* @note +* Important: This function is not suitable for async functions (functions that return a `Promise`). +* When passing an async function, it will return `[null, Promise]`, but won't catch any +* errors if the Promise is rejected later. +* +* For handling async functions, use the `attemptAsync` function instead: +* ``` +* const [error, data] = await attemptAsync(async () => { +* const response = await fetch('https://api.example.com/data'); +* return response.json(); +* }); +* ``` +*/ +function attempt(func) { + try { + return [null, func()]; + } catch (error) { + return [error, null]; + } +} +//#endregion +exports.attempt = attempt; diff --git a/tools/ui/node_modules/es-toolkit/dist/util/attempt.mjs b/tools/ui/node_modules/es-toolkit/dist/util/attempt.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e79fcebee0b0687922c0296e586f02b67e3210ff --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/util/attempt.mjs @@ -0,0 +1,49 @@ +//#region src/util/attempt.ts +/** +* Attempt to execute a function and return the result or error. +* Returns a tuple where: +* - On success: [null, Result] - First element is null, second is the result +* - On error: [Error, null] - First element is the caught error, second is null +* +* @template {unknown} T - The type of the result of the function. +* @template {unknown} E - The type of the error that can be thrown by the function. +* @param {() => T} func - The function to execute. +* @returns {[null, T] | [E, null]} A tuple containing either [null, result] or [error, null]. +* +* @example +* // Successful execution +* const [error, result] = attempt(() => 42); +* // [null, 42] +* +* // Failed execution +* const [error, result] = attempt(() => { +* throw new Error('Something went wrong'); +* }); +* // [Error, null] +* +* // With type parameter +* const [error, names] = attempt(() => ['Alice', 'Bob']); +* // [null, ['Alice', 'Bob']] +* +* @note +* Important: This function is not suitable for async functions (functions that return a `Promise`). +* When passing an async function, it will return `[null, Promise]`, but won't catch any +* errors if the Promise is rejected later. +* +* For handling async functions, use the `attemptAsync` function instead: +* ``` +* const [error, data] = await attemptAsync(async () => { +* const response = await fetch('https://api.example.com/data'); +* return response.json(); +* }); +* ``` +*/ +function attempt(func) { + try { + return [null, func()]; + } catch (error) { + return [error, null]; + } +} +//#endregion +export { attempt }; diff --git a/tools/ui/node_modules/es-toolkit/dist/util/attemptAsync.d.mts b/tools/ui/node_modules/es-toolkit/dist/util/attemptAsync.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..7658f8d05325b08270f6f4c1856a568c142e1560 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/util/attemptAsync.d.mts @@ -0,0 +1,36 @@ +//#region src/util/attemptAsync.d.ts +/** + * Attempt to execute an async function and return the result or error. + * Returns a Promise that resolves to a tuple where: + * - On success: [null, Result] - First element is null, second is the result + * - On error: [Error, null] - First element is the caught error, second is null + * + * @template {unknown} T - The type of the result of the async function. + * @template {unknown} E - The type of the error that can be thrown by the async function. + * @param {() => Promise} func - The async function to execute. + * @returns {Promise<[null, T] | [E, null]>} A Promise that resolves to a tuple containing either [null, result] or [error, null]. + * + * @example + * // Successful execution + * const [error, data] = await attemptAsync(async () => { + * const response = await fetch('https://api.example.com/data'); + * return response.json(); + * }); + * // If successful: [null, { ... data ... }] + * + * // Failed execution + * const [error, data] = await attemptAsync(async () => { + * throw new Error('Network error'); + * }); + * // [Error, null] + * + * // With type parameter + * const [error, users] = await attemptAsync(async () => { + * const response = await fetch('https://api.example.com/users'); + * return response.json(); + * }); + * // users is typed as User[] + */ +declare function attemptAsync(func: () => Promise): Promise<[null, T] | [E, null]>; +//#endregion +export { attemptAsync }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/util/attemptAsync.d.ts b/tools/ui/node_modules/es-toolkit/dist/util/attemptAsync.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7658f8d05325b08270f6f4c1856a568c142e1560 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/util/attemptAsync.d.ts @@ -0,0 +1,36 @@ +//#region src/util/attemptAsync.d.ts +/** + * Attempt to execute an async function and return the result or error. + * Returns a Promise that resolves to a tuple where: + * - On success: [null, Result] - First element is null, second is the result + * - On error: [Error, null] - First element is the caught error, second is null + * + * @template {unknown} T - The type of the result of the async function. + * @template {unknown} E - The type of the error that can be thrown by the async function. + * @param {() => Promise} func - The async function to execute. + * @returns {Promise<[null, T] | [E, null]>} A Promise that resolves to a tuple containing either [null, result] or [error, null]. + * + * @example + * // Successful execution + * const [error, data] = await attemptAsync(async () => { + * const response = await fetch('https://api.example.com/data'); + * return response.json(); + * }); + * // If successful: [null, { ... data ... }] + * + * // Failed execution + * const [error, data] = await attemptAsync(async () => { + * throw new Error('Network error'); + * }); + * // [Error, null] + * + * // With type parameter + * const [error, users] = await attemptAsync(async () => { + * const response = await fetch('https://api.example.com/users'); + * return response.json(); + * }); + * // users is typed as User[] + */ +declare function attemptAsync(func: () => Promise): Promise<[null, T] | [E, null]>; +//#endregion +export { attemptAsync }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/util/attemptAsync.js b/tools/ui/node_modules/es-toolkit/dist/util/attemptAsync.js new file mode 100644 index 0000000000000000000000000000000000000000..a0e2918b19de31a8007d6d04a016b68d3ef8ccb1 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/util/attemptAsync.js @@ -0,0 +1,42 @@ +//#region src/util/attemptAsync.ts +/** +* Attempt to execute an async function and return the result or error. +* Returns a Promise that resolves to a tuple where: +* - On success: [null, Result] - First element is null, second is the result +* - On error: [Error, null] - First element is the caught error, second is null +* +* @template {unknown} T - The type of the result of the async function. +* @template {unknown} E - The type of the error that can be thrown by the async function. +* @param {() => Promise} func - The async function to execute. +* @returns {Promise<[null, T] | [E, null]>} A Promise that resolves to a tuple containing either [null, result] or [error, null]. +* +* @example +* // Successful execution +* const [error, data] = await attemptAsync(async () => { +* const response = await fetch('https://api.example.com/data'); +* return response.json(); +* }); +* // If successful: [null, { ... data ... }] +* +* // Failed execution +* const [error, data] = await attemptAsync(async () => { +* throw new Error('Network error'); +* }); +* // [Error, null] +* +* // With type parameter +* const [error, users] = await attemptAsync(async () => { +* const response = await fetch('https://api.example.com/users'); +* return response.json(); +* }); +* // users is typed as User[] +*/ +async function attemptAsync(func) { + try { + return [null, await func()]; + } catch (error) { + return [error, null]; + } +} +//#endregion +exports.attemptAsync = attemptAsync; diff --git a/tools/ui/node_modules/es-toolkit/dist/util/attemptAsync.mjs b/tools/ui/node_modules/es-toolkit/dist/util/attemptAsync.mjs new file mode 100644 index 0000000000000000000000000000000000000000..96eb39f6a02753f8344ee56a2da917aaa2d55dd8 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/util/attemptAsync.mjs @@ -0,0 +1,42 @@ +//#region src/util/attemptAsync.ts +/** +* Attempt to execute an async function and return the result or error. +* Returns a Promise that resolves to a tuple where: +* - On success: [null, Result] - First element is null, second is the result +* - On error: [Error, null] - First element is the caught error, second is null +* +* @template {unknown} T - The type of the result of the async function. +* @template {unknown} E - The type of the error that can be thrown by the async function. +* @param {() => Promise} func - The async function to execute. +* @returns {Promise<[null, T] | [E, null]>} A Promise that resolves to a tuple containing either [null, result] or [error, null]. +* +* @example +* // Successful execution +* const [error, data] = await attemptAsync(async () => { +* const response = await fetch('https://api.example.com/data'); +* return response.json(); +* }); +* // If successful: [null, { ... data ... }] +* +* // Failed execution +* const [error, data] = await attemptAsync(async () => { +* throw new Error('Network error'); +* }); +* // [Error, null] +* +* // With type parameter +* const [error, users] = await attemptAsync(async () => { +* const response = await fetch('https://api.example.com/users'); +* return response.json(); +* }); +* // users is typed as User[] +*/ +async function attemptAsync(func) { + try { + return [null, await func()]; + } catch (error) { + return [error, null]; + } +} +//#endregion +export { attemptAsync }; diff --git a/tools/ui/node_modules/es-toolkit/dist/util/index.d.mts b/tools/ui/node_modules/es-toolkit/dist/util/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..1db6a6fabd1da91d82a5d03a9d9bc01e2be983ce --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/util/index.d.mts @@ -0,0 +1,4 @@ +import { attempt } from "./attempt.mjs"; +import { attemptAsync } from "./attemptAsync.mjs"; +import { invariant } from "./invariant.mjs"; +export { invariant as assert, attempt, attemptAsync, invariant }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/util/index.d.ts b/tools/ui/node_modules/es-toolkit/dist/util/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..107c04e49c40249e11fd7ee23d2d4c5c23b1705b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/util/index.d.ts @@ -0,0 +1,4 @@ +import { attempt } from "./attempt.js"; +import { attemptAsync } from "./attemptAsync.js"; +import { invariant } from "./invariant.js"; +export { invariant as assert, attempt, attemptAsync, invariant }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/util/index.js b/tools/ui/node_modules/es-toolkit/dist/util/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d5b27b3c37d82ed7f0440160f05c06a290e1fe5b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/util/index.js @@ -0,0 +1,8 @@ +Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); +const require_attempt = require("./attempt.js"); +const require_attemptAsync = require("./attemptAsync.js"); +const require_invariant = require("./invariant.js"); +exports.assert = require_invariant.invariant; +exports.attempt = require_attempt.attempt; +exports.attemptAsync = require_attemptAsync.attemptAsync; +exports.invariant = require_invariant.invariant; diff --git a/tools/ui/node_modules/es-toolkit/dist/util/index.mjs b/tools/ui/node_modules/es-toolkit/dist/util/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..01f24053750f2d0e8e49e8d7993411c594aeb724 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/util/index.mjs @@ -0,0 +1,4 @@ +import { attempt } from "./attempt.mjs"; +import { attemptAsync } from "./attemptAsync.mjs"; +import { invariant } from "./invariant.mjs"; +export { invariant as assert, attempt, attemptAsync, invariant }; diff --git a/tools/ui/node_modules/es-toolkit/dist/util/invariant.d.mts b/tools/ui/node_modules/es-toolkit/dist/util/invariant.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..58564315ffee0b281c55aca892f14405752d8cc0 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/util/invariant.d.mts @@ -0,0 +1,41 @@ +//#region src/util/invariant.d.ts +/** + * Asserts that a given condition is true. If the condition is false, an error is thrown with the provided message. + * + * @param {unknown} condition - The condition to evaluate. + * @param {string} message - The error message to throw if the condition is false. + * @returns {void} Returns void if the condition is true. + * @throws {Error} Throws an error if the condition is false. + * + * @example + * // This call will succeed without any errors + * invariant(true, 'This should not throw'); + * + * // This call will fail and throw an error with the message 'This should throw' + * invariant(false, 'This should throw'); + */ +declare function invariant(condition: unknown, message: string): asserts condition; +/** + * Asserts that a given condition is true. If the condition is false, an error is thrown with the provided error. + * + * @param {unknown} condition - The condition to evaluate. + * @param {Error} error - The error to throw if the condition is false. + * @returns {void} Returns void if the condition is true. + * @throws {Error} Throws an error if the condition is false. + * + * @example + * // This call will succeed without any errors + * invariant(true, new Error('This should not throw')); + * + * class CustomError extends Error { + * constructor(message: string) { + * super(message); + * } + * } + * + * // This call will fail and throw an error with the message 'This should throw' + * invariant(false, new CustomError('This should throw')); + */ +declare function invariant(condition: unknown, error: Error): asserts condition; +//#endregion +export { invariant }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/util/invariant.d.ts b/tools/ui/node_modules/es-toolkit/dist/util/invariant.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..58564315ffee0b281c55aca892f14405752d8cc0 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/util/invariant.d.ts @@ -0,0 +1,41 @@ +//#region src/util/invariant.d.ts +/** + * Asserts that a given condition is true. If the condition is false, an error is thrown with the provided message. + * + * @param {unknown} condition - The condition to evaluate. + * @param {string} message - The error message to throw if the condition is false. + * @returns {void} Returns void if the condition is true. + * @throws {Error} Throws an error if the condition is false. + * + * @example + * // This call will succeed without any errors + * invariant(true, 'This should not throw'); + * + * // This call will fail and throw an error with the message 'This should throw' + * invariant(false, 'This should throw'); + */ +declare function invariant(condition: unknown, message: string): asserts condition; +/** + * Asserts that a given condition is true. If the condition is false, an error is thrown with the provided error. + * + * @param {unknown} condition - The condition to evaluate. + * @param {Error} error - The error to throw if the condition is false. + * @returns {void} Returns void if the condition is true. + * @throws {Error} Throws an error if the condition is false. + * + * @example + * // This call will succeed without any errors + * invariant(true, new Error('This should not throw')); + * + * class CustomError extends Error { + * constructor(message: string) { + * super(message); + * } + * } + * + * // This call will fail and throw an error with the message 'This should throw' + * invariant(false, new CustomError('This should throw')); + */ +declare function invariant(condition: unknown, error: Error): asserts condition; +//#endregion +export { invariant }; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/dist/util/invariant.js b/tools/ui/node_modules/es-toolkit/dist/util/invariant.js new file mode 100644 index 0000000000000000000000000000000000000000..c12a88b0bd4364741905bf4210d4fcd7fbb98290 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/util/invariant.js @@ -0,0 +1,32 @@ +//#region src/util/invariant.ts +/** +* Asserts that a given condition is true. If the condition is false, an error is thrown with the provided message. +* +* @param {unknown} condition - The condition to evaluate. +* @param {string | Error} [message] - The error message to throw if the condition is false. +* @returns {void} Returns void if the condition is true. +* @throws {Error} Throws an error if the condition is false. +* +* @example +* // This call will succeed without any errors +* invariant(true, 'This should not throw'); +* +* // This call will fail and throw an error with the message 'This should throw' +* invariant(false, 'This should throw'); +* +* // Example of using invariant with a condition +* invariant(condition, 'Expected condition is false'); +* +* // Ensure that the value is neither null nor undefined +* invariant(value !== null && value !== undefined, 'Value should not be null or undefined'); +* +* // Example of using invariant to check if a number is positive +* invariant(number > 0, 'Number must be positive'); +*/ +function invariant(condition, message) { + if (condition) return; + if (typeof message === "string") throw new Error(message); + throw message; +} +//#endregion +exports.invariant = invariant; diff --git a/tools/ui/node_modules/es-toolkit/dist/util/invariant.mjs b/tools/ui/node_modules/es-toolkit/dist/util/invariant.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b1222cc00412ad7e355e8d80c8e66f93537ab785 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/dist/util/invariant.mjs @@ -0,0 +1,32 @@ +//#region src/util/invariant.ts +/** +* Asserts that a given condition is true. If the condition is false, an error is thrown with the provided message. +* +* @param {unknown} condition - The condition to evaluate. +* @param {string | Error} [message] - The error message to throw if the condition is false. +* @returns {void} Returns void if the condition is true. +* @throws {Error} Throws an error if the condition is false. +* +* @example +* // This call will succeed without any errors +* invariant(true, 'This should not throw'); +* +* // This call will fail and throw an error with the message 'This should throw' +* invariant(false, 'This should throw'); +* +* // Example of using invariant with a condition +* invariant(condition, 'Expected condition is false'); +* +* // Ensure that the value is neither null nor undefined +* invariant(value !== null && value !== undefined, 'Value should not be null or undefined'); +* +* // Example of using invariant to check if a number is positive +* invariant(number > 0, 'Number must be positive'); +*/ +function invariant(condition, message) { + if (condition) return; + if (typeof message === "string") throw new Error(message); + throw message; +} +//#endregion +export { invariant }; diff --git a/tools/ui/node_modules/es-toolkit/error.d.ts b/tools/ui/node_modules/es-toolkit/error.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f7a1860cd1aafe67bf356bdbd632aeefb8641850 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/error.d.ts @@ -0,0 +1 @@ +export * from './dist/error'; diff --git a/tools/ui/node_modules/es-toolkit/error.js b/tools/ui/node_modules/es-toolkit/error.js new file mode 100644 index 0000000000000000000000000000000000000000..a0622781fa0280789d1f051d7515c360415f16c1 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/error.js @@ -0,0 +1 @@ +module.exports = require('./dist/error'); diff --git a/tools/ui/node_modules/es-toolkit/function.d.ts b/tools/ui/node_modules/es-toolkit/function.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dcaa4f32957550ec4cfba5ca9915fe7027cd8f9a --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/function.d.ts @@ -0,0 +1 @@ +export * from './dist/function'; diff --git a/tools/ui/node_modules/es-toolkit/function.js b/tools/ui/node_modules/es-toolkit/function.js new file mode 100644 index 0000000000000000000000000000000000000000..0c83faae0f7f1929c9434c5f9cce910298baa60e --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/function.js @@ -0,0 +1 @@ +module.exports = require('./dist/function'); diff --git a/tools/ui/node_modules/es-toolkit/map.d.ts b/tools/ui/node_modules/es-toolkit/map.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cb0f048595fb92815c45fc86dbf6fae71ea2d460 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/map.d.ts @@ -0,0 +1 @@ +export * from './dist/map'; diff --git a/tools/ui/node_modules/es-toolkit/map.js b/tools/ui/node_modules/es-toolkit/map.js new file mode 100644 index 0000000000000000000000000000000000000000..48a47ffcbcd25e63d65494aab6baba1051595f9f --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/map.js @@ -0,0 +1 @@ +module.exports = require('./dist/map'); diff --git a/tools/ui/node_modules/es-toolkit/math.d.ts b/tools/ui/node_modules/es-toolkit/math.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ce522bf11d9052ee56964dec547b6dbb351bbaa4 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/math.d.ts @@ -0,0 +1 @@ +export * from './dist/math'; diff --git a/tools/ui/node_modules/es-toolkit/math.js b/tools/ui/node_modules/es-toolkit/math.js new file mode 100644 index 0000000000000000000000000000000000000000..c7098fafaf44901c551cce4818b7c03ec856222d --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/math.js @@ -0,0 +1 @@ +module.exports = require('./dist/math'); diff --git a/tools/ui/node_modules/es-toolkit/object.d.ts b/tools/ui/node_modules/es-toolkit/object.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8e09c58566af0b3375b32f4b15686153f4c0763a --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/object.d.ts @@ -0,0 +1 @@ +export * from './dist/object'; diff --git a/tools/ui/node_modules/es-toolkit/object.js b/tools/ui/node_modules/es-toolkit/object.js new file mode 100644 index 0000000000000000000000000000000000000000..306e005ed8ca460b46fd5b2887895b57caeef359 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/object.js @@ -0,0 +1 @@ +module.exports = require('./dist/object'); diff --git a/tools/ui/node_modules/es-toolkit/package.json b/tools/ui/node_modules/es-toolkit/package.json new file mode 100644 index 0000000000000000000000000000000000000000..096ea98d154e609697c1a70a57a3fd289f22748b --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/package.json @@ -0,0 +1,406 @@ +{ + "name": "es-toolkit", + "version": "1.47.0", + "description": "A state-of-the-art, high-performance JavaScript utility library with a small bundle size and strong type annotations.", + "homepage": "https://es-toolkit.dev", + "bugs": "https://github.com/toss/es-toolkit/issues", + "repository": { + "type": "git", + "url": "https://github.com/toss/es-toolkit.git" + }, + "license": "MIT", + "sideEffects": false, + "packageManager": "yarn@4.12.0", + "exports": { + ".": { + "import": { + "types": "./dist/index.d.mts", + "default": "./dist/index.mjs" + }, + "require": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + }, + "./array": { + "import": { + "types": "./dist/array/index.d.mts", + "default": "./dist/array/index.mjs" + }, + "require": { + "types": "./dist/array/index.d.ts", + "default": "./dist/array/index.js" + } + }, + "./compat": { + "import": { + "types": "./dist/compat/index.d.mts", + "default": "./dist/compat/index.mjs" + }, + "require": { + "types": "./dist/compat/index.d.ts", + "default": "./dist/compat/index.js" + } + }, + "./compat/*": { + "default": { + "types": "./compat/*.d.ts", + "default": "./compat/*.js" + } + }, + "./server": { + "import": { + "types": "./dist/server/index.d.mts", + "default": "./dist/server/index.mjs" + }, + "require": { + "types": "./dist/server/index.d.ts", + "default": "./dist/server/index.js" + } + }, + "./error": { + "import": { + "types": "./dist/error/index.d.mts", + "default": "./dist/error/index.mjs" + }, + "require": { + "types": "./dist/error/index.d.ts", + "default": "./dist/error/index.js" + } + }, + "./function": { + "import": { + "types": "./dist/function/index.d.mts", + "default": "./dist/function/index.mjs" + }, + "require": { + "types": "./dist/function/index.d.ts", + "default": "./dist/function/index.js" + } + }, + "./map": { + "import": { + "types": "./dist/map/index.d.mts", + "default": "./dist/map/index.mjs" + }, + "require": { + "types": "./dist/map/index.d.ts", + "default": "./dist/map/index.js" + } + }, + "./math": { + "import": { + "types": "./dist/math/index.d.mts", + "default": "./dist/math/index.mjs" + }, + "require": { + "types": "./dist/math/index.d.ts", + "default": "./dist/math/index.js" + } + }, + "./object": { + "import": { + "types": "./dist/object/index.d.mts", + "default": "./dist/object/index.mjs" + }, + "require": { + "types": "./dist/object/index.d.ts", + "default": "./dist/object/index.js" + } + }, + "./predicate": { + "import": { + "types": "./dist/predicate/index.d.mts", + "default": "./dist/predicate/index.mjs" + }, + "require": { + "types": "./dist/predicate/index.d.ts", + "default": "./dist/predicate/index.js" + } + }, + "./promise": { + "import": { + "types": "./dist/promise/index.d.mts", + "default": "./dist/promise/index.mjs" + }, + "require": { + "types": "./dist/promise/index.d.ts", + "default": "./dist/promise/index.js" + } + }, + "./set": { + "import": { + "types": "./dist/set/index.d.mts", + "default": "./dist/set/index.mjs" + }, + "require": { + "types": "./dist/set/index.d.ts", + "default": "./dist/set/index.js" + } + }, + "./string": { + "import": { + "types": "./dist/string/index.d.mts", + "default": "./dist/string/index.mjs" + }, + "require": { + "types": "./dist/string/index.d.ts", + "default": "./dist/string/index.js" + } + }, + "./util": { + "import": { + "types": "./dist/util/index.d.mts", + "default": "./dist/util/index.mjs" + }, + "require": { + "types": "./dist/util/index.d.ts", + "default": "./dist/util/index.js" + } + }, + "./package.json": "./package.json" + }, + "files": [ + "dist", + "compat", + "*.d.ts", + "array.js", + "compat.js", + "error.js", + "function.js", + "map.js", + "math.js", + "object.js", + "predicate.js", + "promise.js", + "set.js", + "string.js", + "server.js", + "util.js" + ], + "workspaces": [ + "docs", + "benchmarks" + ], + "scripts": { + "bench": "vitest bench", + "build": "tsdown && ./.scripts/postbuild.sh", + "format": "prettier --write .", + "gen:bundle-size": "node ./.scripts/generate-bundle-size.mjs", + "lint": "eslint --config eslint.config.mjs --concurrency=auto", + "packlint": "packlint sort -R", + "prepack": "yarn build", + "test": "vitest --coverage --typecheck", + "transform": "jscodeshift -t ./.scripts/tests/transform-lodash-test.ts $0 && prettier --write $0", + "typecheck": "tsc --noEmit" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.15.3", + "@changesets/changelog-github": "^0.5.0", + "@changesets/cli": "^2.27.1", + "@eslint/js": "^9.39.2", + "@trivago/prettier-plugin-sort-imports": "^4.3.0", + "@types/broken-link-checker": "^0", + "@types/jscodeshift": "^0.12.0", + "@types/lodash": "^4.17.20", + "@types/node": "^24.10.9", + "@types/tar": "^6.1.13", + "@typescript-eslint/parser": "^8.26.1", + "@vitest/coverage-istanbul": "^4.0.17", + "@vitest/eslint-plugin": "^1.6.6", + "@vue/compiler-sfc": "^3.5.10", + "broken-link-checker": "^0.7.8", + "eslint": "^9.39.2", + "eslint-config-prettier": "^9.1.0", + "eslint-plugin-no-for-of-array": "^0.0.1", + "eslint-plugin-prettier": "^5.2.1", + "eslint-plugin-vue": "^9.28.0", + "execa": "^9.3.0", + "globals": "^15.9.0", + "happy-dom": "^16.7.3", + "jscodeshift": "^17.0.0", + "packlint": "^0.2.4", + "prettier": "^3.2.5", + "prettier-plugin-sort-re-exports": "^0.1.0", + "tar": "^6", + "tsdown": "^0.22.0", + "tslib": "^2.6.3", + "tsx": "^4.19.0", + "typescript": "^5.8.2", + "typescript-eslint": "^8.6.0", + "vercel": "^41.4.1", + "vitest": "^4.0.17" + }, + "publishConfig": { + "access": "public", + "main": "./dist/index.js", + "browser": "./dist/browser.global.js", + "module": "./dist/index.mjs", + "exports": { + ".": { + "import": { + "types": "./dist/index.d.mts", + "default": "./dist/index.mjs" + }, + "require": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + }, + "./array": { + "import": { + "types": "./dist/array/index.d.mts", + "default": "./dist/array/index.mjs" + }, + "require": { + "types": "./dist/array/index.d.ts", + "default": "./dist/array/index.js" + } + }, + "./compat": { + "import": { + "types": "./dist/compat/index.d.mts", + "default": "./dist/compat/index.mjs" + }, + "require": { + "types": "./dist/compat/index.d.ts", + "default": "./dist/compat/index.js" + } + }, + "./compat/*": { + "default": { + "types": "./compat/*.d.ts", + "default": "./compat/*.js" + } + }, + "./server": { + "import": { + "types": "./dist/server/index.d.mts", + "default": "./dist/server/index.mjs" + }, + "require": { + "types": "./dist/server/index.d.ts", + "default": "./dist/server/index.js" + } + }, + "./error": { + "import": { + "types": "./dist/error/index.d.mts", + "default": "./dist/error/index.mjs" + }, + "require": { + "types": "./dist/error/index.d.ts", + "default": "./dist/error/index.js" + } + }, + "./function": { + "import": { + "types": "./dist/function/index.d.mts", + "default": "./dist/function/index.mjs" + }, + "require": { + "types": "./dist/function/index.d.ts", + "default": "./dist/function/index.js" + } + }, + "./map": { + "import": { + "types": "./dist/map/index.d.mts", + "default": "./dist/map/index.mjs" + }, + "require": { + "types": "./dist/map/index.d.ts", + "default": "./dist/map/index.js" + } + }, + "./math": { + "import": { + "types": "./dist/math/index.d.mts", + "default": "./dist/math/index.mjs" + }, + "require": { + "types": "./dist/math/index.d.ts", + "default": "./dist/math/index.js" + } + }, + "./object": { + "import": { + "types": "./dist/object/index.d.mts", + "default": "./dist/object/index.mjs" + }, + "require": { + "types": "./dist/object/index.d.ts", + "default": "./dist/object/index.js" + } + }, + "./predicate": { + "import": { + "types": "./dist/predicate/index.d.mts", + "default": "./dist/predicate/index.mjs" + }, + "require": { + "types": "./dist/predicate/index.d.ts", + "default": "./dist/predicate/index.js" + } + }, + "./promise": { + "import": { + "types": "./dist/promise/index.d.mts", + "default": "./dist/promise/index.mjs" + }, + "require": { + "types": "./dist/promise/index.d.ts", + "default": "./dist/promise/index.js" + } + }, + "./set": { + "import": { + "types": "./dist/set/index.d.mts", + "default": "./dist/set/index.mjs" + }, + "require": { + "types": "./dist/set/index.d.ts", + "default": "./dist/set/index.js" + } + }, + "./string": { + "import": { + "types": "./dist/string/index.d.mts", + "default": "./dist/string/index.mjs" + }, + "require": { + "types": "./dist/string/index.d.ts", + "default": "./dist/string/index.js" + } + }, + "./util": { + "import": { + "types": "./dist/util/index.d.mts", + "default": "./dist/util/index.mjs" + }, + "require": { + "types": "./dist/util/index.d.ts", + "default": "./dist/util/index.js" + } + }, + "./package.json": "./package.json" + }, + "types": "./dist/index.d.ts" + }, + "dependenciesMeta": { + "@trivago/prettier-plugin-sort-imports@4.3.0": { + "unplugged": true + }, + "prettier-plugin-sort-re-exports@0.0.1": { + "unplugged": true + }, + "vitepress-plugin-sandpack@1.1.4": { + "unplugged": true + } + }, + "react-native": "./dist/index.js", + "main": "./dist/index.js", + "browser": "./dist/browser.global.js", + "module": "./dist/index.mjs", + "types": "./dist/index.d.ts" +} \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/predicate.d.ts b/tools/ui/node_modules/es-toolkit/predicate.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7098da4d5f29ee2bb11bd53b463308bd40b03ce1 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/predicate.d.ts @@ -0,0 +1 @@ +export * from './dist/predicate'; diff --git a/tools/ui/node_modules/es-toolkit/predicate.js b/tools/ui/node_modules/es-toolkit/predicate.js new file mode 100644 index 0000000000000000000000000000000000000000..b83b9a1dce79f19c24413091e9853d909450cbc7 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/predicate.js @@ -0,0 +1 @@ +module.exports = require('./dist/predicate'); diff --git a/tools/ui/node_modules/es-toolkit/promise.d.ts b/tools/ui/node_modules/es-toolkit/promise.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7949e354e35609dbbddf40c20d89ec2135f69eda --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/promise.d.ts @@ -0,0 +1 @@ +export * from './dist/promise'; diff --git a/tools/ui/node_modules/es-toolkit/promise.js b/tools/ui/node_modules/es-toolkit/promise.js new file mode 100644 index 0000000000000000000000000000000000000000..ba2509f711f2e560c7932f49e21e48818e4d1090 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/promise.js @@ -0,0 +1 @@ +module.exports = require('./dist/promise'); diff --git a/tools/ui/node_modules/es-toolkit/server.d.ts b/tools/ui/node_modules/es-toolkit/server.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..699fd532abd754877d1fabbe87f0577c659d88c8 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/server.d.ts @@ -0,0 +1 @@ +export * from './dist/server'; diff --git a/tools/ui/node_modules/es-toolkit/server.js b/tools/ui/node_modules/es-toolkit/server.js new file mode 100644 index 0000000000000000000000000000000000000000..0e07caec85575b0c2c74f8ce07048a98e0ff42d4 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/server.js @@ -0,0 +1 @@ +module.exports = require('./dist/server'); diff --git a/tools/ui/node_modules/es-toolkit/set.d.ts b/tools/ui/node_modules/es-toolkit/set.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a384d885057015eeb4ab51dd37c669751fc533a1 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/set.d.ts @@ -0,0 +1 @@ +export * from './dist/set'; diff --git a/tools/ui/node_modules/es-toolkit/set.js b/tools/ui/node_modules/es-toolkit/set.js new file mode 100644 index 0000000000000000000000000000000000000000..a3ccb781c17c8529914b8008364c36d27a4a8ab2 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/set.js @@ -0,0 +1 @@ +module.exports = require('./dist/set'); diff --git a/tools/ui/node_modules/es-toolkit/src/compat/_internal/Equals.d.ts b/tools/ui/node_modules/es-toolkit/src/compat/_internal/Equals.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9e7a6f0419300c331de1da541888d773c137ff4d --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/src/compat/_internal/Equals.d.ts @@ -0,0 +1 @@ +export type Equals = (() => X extends T ? 1 : 2) extends () => X extends U ? 1 : 2 ? true : false; diff --git a/tools/ui/node_modules/es-toolkit/src/compat/_internal/IsWritable.d.ts b/tools/ui/node_modules/es-toolkit/src/compat/_internal/IsWritable.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b11944b7db19ea47b942f66323f091948caeaae1 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/src/compat/_internal/IsWritable.d.ts @@ -0,0 +1,3 @@ +import type { Equals } from './Equals.d.ts'; + +export type IsWritable = Equals<{ [K in keyof T]: T[K] }, { -readonly [K in keyof T]: T[K] }>; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/src/compat/_internal/MutableList.d.ts b/tools/ui/node_modules/es-toolkit/src/compat/_internal/MutableList.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..aa4c4ddf4af0b491112cf396348fc9df3e7e63af --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/src/compat/_internal/MutableList.d.ts @@ -0,0 +1,4 @@ +export interface MutableList { + length: number; + [k: number]: T; +} diff --git a/tools/ui/node_modules/es-toolkit/src/compat/_internal/RejectReadonly.d.ts b/tools/ui/node_modules/es-toolkit/src/compat/_internal/RejectReadonly.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1c1cfb5a45c59058ae3e678ca3a522352660cd90 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/src/compat/_internal/RejectReadonly.d.ts @@ -0,0 +1,4 @@ +import { IsWritable } from './IsWritable.d.ts'; +import { MutableList } from './MutableList.d.ts'; + +export type RejectReadonly> = IsWritable extends true ? T : never; \ No newline at end of file diff --git a/tools/ui/node_modules/es-toolkit/string.d.ts b/tools/ui/node_modules/es-toolkit/string.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1ec83287a31c74868a99a5f299188d76410b6c86 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/string.d.ts @@ -0,0 +1 @@ +export * from './dist/string'; diff --git a/tools/ui/node_modules/es-toolkit/string.js b/tools/ui/node_modules/es-toolkit/string.js new file mode 100644 index 0000000000000000000000000000000000000000..efe8ede140263ea7d9cc02211276da69a0315d42 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/string.js @@ -0,0 +1 @@ +module.exports = require('./dist/string'); diff --git a/tools/ui/node_modules/es-toolkit/util.d.ts b/tools/ui/node_modules/es-toolkit/util.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8d8689f961d2f5a865b1ca7fc51057aa7d6d6b31 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/util.d.ts @@ -0,0 +1 @@ +export * from './dist/util'; diff --git a/tools/ui/node_modules/es-toolkit/util.js b/tools/ui/node_modules/es-toolkit/util.js new file mode 100644 index 0000000000000000000000000000000000000000..9f1ff80880c12a4ffecb659c8f75e2dea4e56eb9 --- /dev/null +++ b/tools/ui/node_modules/es-toolkit/util.js @@ -0,0 +1 @@ +module.exports = require('./dist/util'); diff --git a/tools/ui/node_modules/esbuild/LICENSE.md b/tools/ui/node_modules/esbuild/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..2027e8dcf3787f5aac9fcd835e2b80cb75a39211 --- /dev/null +++ b/tools/ui/node_modules/esbuild/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Evan Wallace + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tools/ui/node_modules/esbuild/README.md b/tools/ui/node_modules/esbuild/README.md new file mode 100644 index 0000000000000000000000000000000000000000..93863d198004eae1c7b17aef26d829dfca4a314f --- /dev/null +++ b/tools/ui/node_modules/esbuild/README.md @@ -0,0 +1,3 @@ +# esbuild + +This is a JavaScript bundler and minifier. See https://github.com/evanw/esbuild and the [JavaScript API documentation](https://esbuild.github.io/api/) for details. diff --git a/tools/ui/node_modules/esbuild/bin/esbuild b/tools/ui/node_modules/esbuild/bin/esbuild new file mode 100644 index 0000000000000000000000000000000000000000..0045b52bdf0f07a10b166f676abcdd2d419325d7 --- /dev/null +++ b/tools/ui/node_modules/esbuild/bin/esbuild @@ -0,0 +1,223 @@ +#!/usr/bin/env node +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); + +// lib/npm/node-platform.ts +var fs = require("fs"); +var os = require("os"); +var path = require("path"); +var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH; +var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild"; +var packageDarwin_arm64 = "@esbuild/darwin-arm64"; +var packageDarwin_x64 = "@esbuild/darwin-x64"; +var knownWindowsPackages = { + "win32 arm64 LE": "@esbuild/win32-arm64", + "win32 ia32 LE": "@esbuild/win32-ia32", + "win32 x64 LE": "@esbuild/win32-x64" +}; +var knownUnixlikePackages = { + "aix ppc64 BE": "@esbuild/aix-ppc64", + "android arm64 LE": "@esbuild/android-arm64", + "darwin arm64 LE": "@esbuild/darwin-arm64", + "darwin x64 LE": "@esbuild/darwin-x64", + "freebsd arm64 LE": "@esbuild/freebsd-arm64", + "freebsd x64 LE": "@esbuild/freebsd-x64", + "linux arm LE": "@esbuild/linux-arm", + "linux arm64 LE": "@esbuild/linux-arm64", + "linux ia32 LE": "@esbuild/linux-ia32", + "linux mips64el LE": "@esbuild/linux-mips64el", + "linux ppc64 LE": "@esbuild/linux-ppc64", + "linux riscv64 LE": "@esbuild/linux-riscv64", + "linux s390x BE": "@esbuild/linux-s390x", + "linux x64 LE": "@esbuild/linux-x64", + "linux loong64 LE": "@esbuild/linux-loong64", + "netbsd arm64 LE": "@esbuild/netbsd-arm64", + "netbsd x64 LE": "@esbuild/netbsd-x64", + "openbsd arm64 LE": "@esbuild/openbsd-arm64", + "openbsd x64 LE": "@esbuild/openbsd-x64", + "sunos x64 LE": "@esbuild/sunos-x64" +}; +var knownWebAssemblyFallbackPackages = { + "android arm LE": "@esbuild/android-arm", + "android x64 LE": "@esbuild/android-x64", + "openharmony arm64 LE": "@esbuild/openharmony-arm64" +}; +function pkgAndSubpathForCurrentPlatform() { + let pkg; + let subpath; + let isWASM2 = false; + let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`; + if (platformKey in knownWindowsPackages) { + pkg = knownWindowsPackages[platformKey]; + subpath = "esbuild.exe"; + } else if (platformKey in knownUnixlikePackages) { + pkg = knownUnixlikePackages[platformKey]; + subpath = "bin/esbuild"; + } else if (platformKey in knownWebAssemblyFallbackPackages) { + pkg = knownWebAssemblyFallbackPackages[platformKey]; + subpath = "bin/esbuild"; + isWASM2 = true; + } else { + throw new Error(`Unsupported platform: ${platformKey}`); + } + return { pkg, subpath, isWASM: isWASM2 }; +} +function pkgForSomeOtherPlatform() { + const libMainJS = require.resolve("esbuild"); + const nodeModulesDirectory = path.dirname(path.dirname(path.dirname(libMainJS))); + if (path.basename(nodeModulesDirectory) === "node_modules") { + for (const unixKey in knownUnixlikePackages) { + try { + const pkg = knownUnixlikePackages[unixKey]; + if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg; + } catch { + } + } + for (const windowsKey in knownWindowsPackages) { + try { + const pkg = knownWindowsPackages[windowsKey]; + if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg; + } catch { + } + } + } + return null; +} +function downloadedBinPath(pkg, subpath) { + const esbuildLibDir = path.dirname(require.resolve("esbuild")); + return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`); +} +function generateBinPath() { + if (isValidBinaryPath(ESBUILD_BINARY_PATH)) { + if (!fs.existsSync(ESBUILD_BINARY_PATH)) { + console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`); + } else { + return { binPath: ESBUILD_BINARY_PATH, isWASM: false }; + } + } + const { pkg, subpath, isWASM: isWASM2 } = pkgAndSubpathForCurrentPlatform(); + let binPath2; + try { + binPath2 = require.resolve(`${pkg}/${subpath}`); + } catch (e) { + binPath2 = downloadedBinPath(pkg, subpath); + if (!fs.existsSync(binPath2)) { + try { + require.resolve(pkg); + } catch { + const otherPkg = pkgForSomeOtherPlatform(); + if (otherPkg) { + let suggestions = ` +Specifically the "${otherPkg}" package is present but this platform +needs the "${pkg}" package instead. People often get into this +situation by installing esbuild on Windows or macOS and copying "node_modules" +into a Docker image that runs Linux, or by copying "node_modules" between +Windows and WSL environments. + +If you are installing with npm, you can try not copying the "node_modules" +directory when you copy the files over, and running "npm ci" or "npm install" +on the destination platform after the copy. Or you could consider using yarn +instead of npm which has built-in support for installing a package on multiple +platforms simultaneously. + +If you are installing with yarn, you can try listing both this platform and the +other platform in your ".yarnrc.yml" file using the "supportedArchitectures" +feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures +Keep in mind that this means multiple copies of esbuild will be present. +`; + if (pkg === packageDarwin_x64 && otherPkg === packageDarwin_arm64 || pkg === packageDarwin_arm64 && otherPkg === packageDarwin_x64) { + suggestions = ` +Specifically the "${otherPkg}" package is present but this platform +needs the "${pkg}" package instead. People often get into this +situation by installing esbuild with npm running inside of Rosetta 2 and then +trying to use it with node running outside of Rosetta 2, or vice versa (Rosetta +2 is Apple's on-the-fly x86_64-to-arm64 translation service). + +If you are installing with npm, you can try ensuring that both npm and node are +not running under Rosetta 2 and then reinstalling esbuild. This likely involves +changing how you installed npm and/or node. For example, installing node with +the universal installer here should work: https://nodejs.org/en/download/. Or +you could consider using yarn instead of npm which has built-in support for +installing a package on multiple platforms simultaneously. + +If you are installing with yarn, you can try listing both "arm64" and "x64" +in your ".yarnrc.yml" file using the "supportedArchitectures" feature: +https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures +Keep in mind that this means multiple copies of esbuild will be present. +`; + } + throw new Error(` +You installed esbuild for another platform than the one you're currently using. +This won't work because esbuild is written with native code and needs to +install a platform-specific binary executable. +${suggestions} +Another alternative is to use the "esbuild-wasm" package instead, which works +the same way on all platforms. But it comes with a heavy performance cost and +can sometimes be 10x slower than the "esbuild" package, so you may also not +want to do that. +`); + } + throw new Error(`The package "${pkg}" could not be found, and is needed by esbuild. + +If you are installing esbuild with npm, make sure that you don't specify the +"--no-optional" or "--omit=optional" flags. The "optionalDependencies" feature +of "package.json" is used by esbuild to install the correct binary executable +for your current platform.`); + } + throw e; + } + } + if (/\.zip\//.test(binPath2)) { + let pnpapi; + try { + pnpapi = require("pnpapi"); + } catch (e) { + } + if (pnpapi) { + const root = pnpapi.getPackageInformation(pnpapi.topLevel).packageLocation; + const binTargetPath = path.join( + root, + "node_modules", + ".cache", + "esbuild", + `pnpapi-${pkg.replace("/", "-")}-${"0.28.1"}-${path.basename(subpath)}` + ); + if (!fs.existsSync(binTargetPath)) { + fs.mkdirSync(path.dirname(binTargetPath), { recursive: true }); + fs.copyFileSync(binPath2, binTargetPath); + fs.chmodSync(binTargetPath, 493); + } + return { binPath: binTargetPath, isWASM: isWASM2 }; + } + } + return { binPath: binPath2, isWASM: isWASM2 }; +} + +// lib/npm/node-shim.ts +var { binPath, isWASM } = generateBinPath(); +if (isWASM) { + require("child_process").execFileSync("node", [binPath].concat(process.argv.slice(2)), { stdio: "inherit" }); +} else { + require("child_process").execFileSync(binPath, process.argv.slice(2), { stdio: "inherit" }); +} diff --git a/tools/ui/node_modules/esbuild/install.js b/tools/ui/node_modules/esbuild/install.js new file mode 100644 index 0000000000000000000000000000000000000000..ee09eff8e0171c301b24f04185878b5761853cde --- /dev/null +++ b/tools/ui/node_modules/esbuild/install.js @@ -0,0 +1,300 @@ +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); + +// lib/npm/node-platform.ts +var fs = require("fs"); +var os = require("os"); +var path = require("path"); +var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH; +var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild"; +var knownWindowsPackages = { + "win32 arm64 LE": "@esbuild/win32-arm64", + "win32 ia32 LE": "@esbuild/win32-ia32", + "win32 x64 LE": "@esbuild/win32-x64" +}; +var knownUnixlikePackages = { + "aix ppc64 BE": "@esbuild/aix-ppc64", + "android arm64 LE": "@esbuild/android-arm64", + "darwin arm64 LE": "@esbuild/darwin-arm64", + "darwin x64 LE": "@esbuild/darwin-x64", + "freebsd arm64 LE": "@esbuild/freebsd-arm64", + "freebsd x64 LE": "@esbuild/freebsd-x64", + "linux arm LE": "@esbuild/linux-arm", + "linux arm64 LE": "@esbuild/linux-arm64", + "linux ia32 LE": "@esbuild/linux-ia32", + "linux mips64el LE": "@esbuild/linux-mips64el", + "linux ppc64 LE": "@esbuild/linux-ppc64", + "linux riscv64 LE": "@esbuild/linux-riscv64", + "linux s390x BE": "@esbuild/linux-s390x", + "linux x64 LE": "@esbuild/linux-x64", + "linux loong64 LE": "@esbuild/linux-loong64", + "netbsd arm64 LE": "@esbuild/netbsd-arm64", + "netbsd x64 LE": "@esbuild/netbsd-x64", + "openbsd arm64 LE": "@esbuild/openbsd-arm64", + "openbsd x64 LE": "@esbuild/openbsd-x64", + "sunos x64 LE": "@esbuild/sunos-x64" +}; +var knownWebAssemblyFallbackPackages = { + "android arm LE": "@esbuild/android-arm", + "android x64 LE": "@esbuild/android-x64", + "openharmony arm64 LE": "@esbuild/openharmony-arm64" +}; +function pkgAndSubpathForCurrentPlatform() { + let pkg; + let subpath; + let isWASM = false; + let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`; + if (platformKey in knownWindowsPackages) { + pkg = knownWindowsPackages[platformKey]; + subpath = "esbuild.exe"; + } else if (platformKey in knownUnixlikePackages) { + pkg = knownUnixlikePackages[platformKey]; + subpath = "bin/esbuild"; + } else if (platformKey in knownWebAssemblyFallbackPackages) { + pkg = knownWebAssemblyFallbackPackages[platformKey]; + subpath = "bin/esbuild"; + isWASM = true; + } else { + throw new Error(`Unsupported platform: ${platformKey}`); + } + return { pkg, subpath, isWASM }; +} +function downloadedBinPath(pkg, subpath) { + const esbuildLibDir = path.dirname(require.resolve("esbuild")); + return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`); +} + +// lib/npm/node-install.ts +var fs2 = require("fs"); +var os2 = require("os"); +var path2 = require("path"); +var zlib = require("zlib"); +var https = require("https"); +var crypto = require("crypto"); +var child_process = require("child_process"); +var packageJSON = require(path2.join(__dirname, "package.json")); +var toPath = path2.join(__dirname, "bin", "esbuild"); +var isToPathJS = true; +function validateBinaryVersion(...command) { + command.push("--version"); + let stdout; + try { + stdout = child_process.execFileSync(command.shift(), command, { + // Without this, this install script strangely crashes with the error + // "EACCES: permission denied, write" but only on Ubuntu Linux when node is + // installed from the Snap Store. This is not a problem when you download + // the official version of node. The problem appears to be that stderr + // (i.e. file descriptor 2) isn't writable? + // + // More info: + // - https://snapcraft.io/ (what the Snap Store is) + // - https://nodejs.org/dist/ (download the official version of node) + // - https://github.com/evanw/esbuild/issues/1711#issuecomment-1027554035 + // + stdio: "pipe" + }).toString().trim(); + } catch (err) { + if (os2.platform() === "darwin" && /_SecTrustEvaluateWithError/.test(err + "")) { + let os3 = "this version of macOS"; + try { + os3 = "macOS " + child_process.execFileSync("sw_vers", ["-productVersion"]).toString().trim(); + } catch { + } + throw new Error(`The "esbuild" package cannot be installed because ${os3} is too outdated. + +The Go compiler (which esbuild relies on) no longer supports ${os3}, +which means the "esbuild" binary executable can't be run. You can either: + + * Update your version of macOS to one that the Go compiler supports + * Use the "esbuild-wasm" package instead of the "esbuild" package + * Build esbuild yourself using an older version of the Go compiler +`); + } + throw err; + } + if (stdout !== packageJSON.version) { + throw new Error(`Expected ${JSON.stringify(packageJSON.version)} but got ${JSON.stringify(stdout)}`); + } +} +function isYarn() { + const { npm_config_user_agent } = process.env; + if (npm_config_user_agent) { + return /\byarn\//.test(npm_config_user_agent); + } + return false; +} +function fetch(url) { + return new Promise((resolve, reject) => { + https.get(url, (res) => { + if ((res.statusCode === 301 || res.statusCode === 302) && res.headers.location) + return fetch(res.headers.location).then(resolve, reject); + if (res.statusCode !== 200) + return reject(new Error(`Server responded with ${res.statusCode}`)); + let chunks = []; + res.on("data", (chunk) => chunks.push(chunk)); + res.on("end", () => resolve(Buffer.concat(chunks))); + }).on("error", reject); + }); +} +function extractFileFromTarGzip(buffer, subpath) { + try { + buffer = zlib.unzipSync(buffer); + } catch (err) { + throw new Error(`Invalid gzip data in archive: ${err && err.message || err}`); + } + let str = (i, n) => String.fromCharCode(...buffer.subarray(i, i + n)).replace(/\0.*$/, ""); + let offset = 0; + subpath = `package/${subpath}`; + while (offset < buffer.length) { + let name = str(offset, 100); + let size = parseInt(str(offset + 124, 12), 8); + offset += 512; + if (!isNaN(size) && size >= 0) { + if (name === subpath) return buffer.subarray(offset, offset + size); + offset += size + 511 & ~511; + } + } + throw new Error(`Could not find ${JSON.stringify(subpath)} in archive`); +} +function installUsingNPM(pkg, subpath, binPath) { + const env = { ...process.env, npm_config_global: void 0 }; + const esbuildLibDir = path2.dirname(require.resolve("esbuild")); + const installDir = path2.join(esbuildLibDir, "npm-install"); + fs2.mkdirSync(installDir); + try { + fs2.writeFileSync(path2.join(installDir, "package.json"), "{}"); + child_process.execSync( + `npm install --loglevel=error --prefer-offline --no-audit --progress=false ${pkg}@${packageJSON.version}`, + { cwd: installDir, stdio: "pipe", env } + ); + const installedBinPath = path2.join(installDir, "node_modules", pkg, subpath); + binaryIntegrityCheck(pkg, subpath, fs2.readFileSync(installedBinPath)); + fs2.renameSync(installedBinPath, binPath); + } finally { + try { + removeRecursive(installDir); + } catch { + } + } +} +function removeRecursive(dir) { + for (const entry of fs2.readdirSync(dir)) { + const entryPath = path2.join(dir, entry); + let stats; + try { + stats = fs2.lstatSync(entryPath); + } catch { + continue; + } + if (stats.isDirectory()) removeRecursive(entryPath); + else fs2.unlinkSync(entryPath); + } + fs2.rmdirSync(dir); +} +function applyManualBinaryPathOverride(overridePath) { + const pathString = JSON.stringify(overridePath); + fs2.writeFileSync(toPath, `#!/usr/bin/env node +require('child_process').execFileSync(${pathString}, process.argv.slice(2), { stdio: 'inherit' }); +`); + const libMain = path2.join(__dirname, "lib", "main.js"); + const code = fs2.readFileSync(libMain, "utf8"); + fs2.writeFileSync(libMain, `var ESBUILD_BINARY_PATH = ${pathString}; +${code}`); +} +function maybeOptimizePackage(binPath, isWASM) { + if (os2.platform() !== "win32" && !isYarn() && !isWASM) { + const tempPath = path2.join(__dirname, "bin-esbuild"); + try { + fs2.linkSync(binPath, tempPath); + fs2.renameSync(tempPath, toPath); + isToPathJS = false; + fs2.unlinkSync(tempPath); + } catch { + } + } +} +function binaryIntegrityCheck(pkg, subpath, bytes) { + const hash = crypto.createHash("sha256").update(bytes).digest("hex"); + const key = `${pkg}/${subpath}`; + const expected = packageJSON["esbuild.binaryHashes"][key]; + if (!expected) throw new Error(`Missing hash for "${key}"`); + if (hash !== expected) throw new Error(`"${hash.slice(0, 8)}..." doesn't match "${expected.slice(0, 8)}..." for "${pkg}"`); +} +async function downloadDirectlyFromNPM(pkg, subpath, binPath) { + const url = `https://registry.npmjs.org/${pkg}/-/${pkg.replace("@esbuild/", "")}-${packageJSON.version}.tgz`; + console.error(`[esbuild] Trying to download ${JSON.stringify(url)}`); + try { + const bytes = extractFileFromTarGzip(await fetch(url), subpath); + binaryIntegrityCheck(pkg, subpath, bytes); + fs2.writeFileSync(binPath, bytes); + fs2.chmodSync(binPath, 493); + } catch (e) { + console.error(`[esbuild] Failed to download ${JSON.stringify(url)}: ${e && e.message || e}`); + throw e; + } +} +async function checkAndPreparePackage() { + if (isValidBinaryPath(ESBUILD_BINARY_PATH)) { + if (!fs2.existsSync(ESBUILD_BINARY_PATH)) { + console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`); + } else { + applyManualBinaryPathOverride(ESBUILD_BINARY_PATH); + return; + } + } + const { pkg, subpath, isWASM } = pkgAndSubpathForCurrentPlatform(); + let binPath; + try { + binPath = require.resolve(`${pkg}/${subpath}`); + } catch (e) { + console.error(`[esbuild] Failed to find package "${pkg}" on the file system + +This can happen if you use the "--no-optional" flag. The "optionalDependencies" +package.json feature is used by esbuild to install the correct binary executable +for your current platform. This install script will now attempt to work around +this. If that fails, you need to remove the "--no-optional" flag to use esbuild. +`); + if (isWASM) throw new Error(`Failed to install package "${pkg}"`); + binPath = downloadedBinPath(pkg, subpath); + try { + console.error(`[esbuild] Trying to install package "${pkg}" using npm`); + installUsingNPM(pkg, subpath, binPath); + } catch (e2) { + console.error(`[esbuild] Failed to install package "${pkg}" using npm: ${e2 && e2.message || e2}`); + try { + await downloadDirectlyFromNPM(pkg, subpath, binPath); + } catch (e3) { + throw new Error(`Failed to install package "${pkg}"`); + } + } + } + maybeOptimizePackage(binPath, isWASM); +} +checkAndPreparePackage().then(() => { + if (isToPathJS) { + validateBinaryVersion(process.execPath, toPath); + } else { + validateBinaryVersion(toPath); + } +}); diff --git a/tools/ui/node_modules/esbuild/lib/main.d.ts b/tools/ui/node_modules/esbuild/lib/main.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9e69c39f58b92dda3496b19481468b5057a1084f --- /dev/null +++ b/tools/ui/node_modules/esbuild/lib/main.d.ts @@ -0,0 +1,716 @@ +export type Platform = 'browser' | 'node' | 'neutral' +export type Format = 'iife' | 'cjs' | 'esm' +export type Loader = 'base64' | 'binary' | 'copy' | 'css' | 'dataurl' | 'default' | 'empty' | 'file' | 'js' | 'json' | 'jsx' | 'local-css' | 'text' | 'ts' | 'tsx' +export type LogLevel = 'verbose' | 'debug' | 'info' | 'warning' | 'error' | 'silent' +export type Charset = 'ascii' | 'utf8' +export type Drop = 'console' | 'debugger' +export type AbsPaths = 'code' | 'log' | 'metafile' + +interface CommonOptions { + /** Documentation: https://esbuild.github.io/api/#sourcemap */ + sourcemap?: boolean | 'linked' | 'inline' | 'external' | 'both' + /** Documentation: https://esbuild.github.io/api/#legal-comments */ + legalComments?: 'none' | 'inline' | 'eof' | 'linked' | 'external' + /** Documentation: https://esbuild.github.io/api/#source-root */ + sourceRoot?: string + /** Documentation: https://esbuild.github.io/api/#sources-content */ + sourcesContent?: boolean + + /** Documentation: https://esbuild.github.io/api/#format */ + format?: Format + /** Documentation: https://esbuild.github.io/api/#global-name */ + globalName?: string + /** Documentation: https://esbuild.github.io/api/#target */ + target?: string | string[] + /** Documentation: https://esbuild.github.io/api/#supported */ + supported?: Record + /** Documentation: https://esbuild.github.io/api/#platform */ + platform?: Platform + + /** Documentation: https://esbuild.github.io/api/#mangle-props */ + mangleProps?: RegExp + /** Documentation: https://esbuild.github.io/api/#mangle-props */ + reserveProps?: RegExp + /** Documentation: https://esbuild.github.io/api/#mangle-props */ + mangleQuoted?: boolean + /** Documentation: https://esbuild.github.io/api/#mangle-props */ + mangleCache?: Record + /** Documentation: https://esbuild.github.io/api/#drop */ + drop?: Drop[] + /** Documentation: https://esbuild.github.io/api/#drop-labels */ + dropLabels?: string[] + /** Documentation: https://esbuild.github.io/api/#minify */ + minify?: boolean + /** Documentation: https://esbuild.github.io/api/#minify */ + minifyWhitespace?: boolean + /** Documentation: https://esbuild.github.io/api/#minify */ + minifyIdentifiers?: boolean + /** Documentation: https://esbuild.github.io/api/#minify */ + minifySyntax?: boolean + /** Documentation: https://esbuild.github.io/api/#line-limit */ + lineLimit?: number + /** Documentation: https://esbuild.github.io/api/#charset */ + charset?: Charset + /** Documentation: https://esbuild.github.io/api/#tree-shaking */ + treeShaking?: boolean + /** Documentation: https://esbuild.github.io/api/#ignore-annotations */ + ignoreAnnotations?: boolean + + /** Documentation: https://esbuild.github.io/api/#jsx */ + jsx?: 'transform' | 'preserve' | 'automatic' + /** Documentation: https://esbuild.github.io/api/#jsx-factory */ + jsxFactory?: string + /** Documentation: https://esbuild.github.io/api/#jsx-fragment */ + jsxFragment?: string + /** Documentation: https://esbuild.github.io/api/#jsx-import-source */ + jsxImportSource?: string + /** Documentation: https://esbuild.github.io/api/#jsx-development */ + jsxDev?: boolean + /** Documentation: https://esbuild.github.io/api/#jsx-side-effects */ + jsxSideEffects?: boolean + + /** Documentation: https://esbuild.github.io/api/#define */ + define?: { [key: string]: string } + /** Documentation: https://esbuild.github.io/api/#pure */ + pure?: string[] + /** Documentation: https://esbuild.github.io/api/#keep-names */ + keepNames?: boolean + + /** Documentation: https://esbuild.github.io/api/#abs-paths */ + absPaths?: AbsPaths[] + /** Documentation: https://esbuild.github.io/api/#color */ + color?: boolean + /** Documentation: https://esbuild.github.io/api/#log-level */ + logLevel?: LogLevel + /** Documentation: https://esbuild.github.io/api/#log-limit */ + logLimit?: number + /** Documentation: https://esbuild.github.io/api/#log-override */ + logOverride?: Record + + /** Documentation: https://esbuild.github.io/api/#tsconfig-raw */ + tsconfigRaw?: string | TsconfigRaw +} + +export interface TsconfigRaw { + compilerOptions?: { + alwaysStrict?: boolean + baseUrl?: string + experimentalDecorators?: boolean + importsNotUsedAsValues?: 'remove' | 'preserve' | 'error' + jsx?: 'preserve' | 'react-native' | 'react' | 'react-jsx' | 'react-jsxdev' + jsxFactory?: string + jsxFragmentFactory?: string + jsxImportSource?: string + paths?: Record + preserveValueImports?: boolean + strict?: boolean + target?: string + useDefineForClassFields?: boolean + verbatimModuleSyntax?: boolean + } +} + +export interface BuildOptions extends CommonOptions { + /** Documentation: https://esbuild.github.io/api/#bundle */ + bundle?: boolean + /** Documentation: https://esbuild.github.io/api/#splitting */ + splitting?: boolean + /** Documentation: https://esbuild.github.io/api/#preserve-symlinks */ + preserveSymlinks?: boolean + /** Documentation: https://esbuild.github.io/api/#outfile */ + outfile?: string + /** Documentation: https://esbuild.github.io/api/#metafile */ + metafile?: boolean + /** Documentation: https://esbuild.github.io/api/#outdir */ + outdir?: string + /** Documentation: https://esbuild.github.io/api/#outbase */ + outbase?: string + /** Documentation: https://esbuild.github.io/api/#external */ + external?: string[] + /** Documentation: https://esbuild.github.io/api/#packages */ + packages?: 'bundle' | 'external' + /** Documentation: https://esbuild.github.io/api/#alias */ + alias?: Record + /** Documentation: https://esbuild.github.io/api/#loader */ + loader?: { [ext: string]: Loader } + /** Documentation: https://esbuild.github.io/api/#resolve-extensions */ + resolveExtensions?: string[] + /** Documentation: https://esbuild.github.io/api/#main-fields */ + mainFields?: string[] + /** Documentation: https://esbuild.github.io/api/#conditions */ + conditions?: string[] + /** Documentation: https://esbuild.github.io/api/#write */ + write?: boolean + /** Documentation: https://esbuild.github.io/api/#allow-overwrite */ + allowOverwrite?: boolean + /** Documentation: https://esbuild.github.io/api/#tsconfig */ + tsconfig?: string + /** Documentation: https://esbuild.github.io/api/#out-extension */ + outExtension?: { [ext: string]: string } + /** Documentation: https://esbuild.github.io/api/#public-path */ + publicPath?: string + /** Documentation: https://esbuild.github.io/api/#entry-names */ + entryNames?: string + /** Documentation: https://esbuild.github.io/api/#chunk-names */ + chunkNames?: string + /** Documentation: https://esbuild.github.io/api/#asset-names */ + assetNames?: string + /** Documentation: https://esbuild.github.io/api/#inject */ + inject?: string[] + /** Documentation: https://esbuild.github.io/api/#banner */ + banner?: { [type: string]: string } + /** Documentation: https://esbuild.github.io/api/#footer */ + footer?: { [type: string]: string } + /** Documentation: https://esbuild.github.io/api/#entry-points */ + entryPoints?: (string | { in: string, out: string })[] | Record + /** Documentation: https://esbuild.github.io/api/#stdin */ + stdin?: StdinOptions + /** Documentation: https://esbuild.github.io/plugins/ */ + plugins?: Plugin[] + /** Documentation: https://esbuild.github.io/api/#working-directory */ + absWorkingDir?: string + /** Documentation: https://esbuild.github.io/api/#node-paths */ + nodePaths?: string[]; // The "NODE_PATH" variable from Node.js +} + +export interface StdinOptions { + contents: string | Uint8Array + resolveDir?: string + sourcefile?: string + loader?: Loader +} + +export interface Message { + id: string + pluginName: string + text: string + location: Location | null + notes: Note[] + + /** + * Optional user-specified data that is passed through unmodified. You can + * use this to stash the original error, for example. + */ + detail: any +} + +export interface Note { + text: string + location: Location | null +} + +export interface Location { + file: string + namespace: string + /** 1-based */ + line: number + /** 0-based, in bytes */ + column: number + /** in bytes */ + length: number + lineText: string + suggestion: string +} + +export interface OutputFile { + path: string + contents: Uint8Array + hash: string + /** "contents" as text (changes automatically with "contents") */ + readonly text: string +} + +export interface BuildResult { + errors: Message[] + warnings: Message[] + /** Only when "write: false" */ + outputFiles: OutputFile[] | (ProvidedOptions['write'] extends false ? never : undefined) + /** Only when "metafile: true" */ + metafile: Metafile | (ProvidedOptions['metafile'] extends true ? never : undefined) + /** Only when "mangleCache" is present */ + mangleCache: Record | (ProvidedOptions['mangleCache'] extends Object ? never : undefined) +} + +export interface BuildFailure extends Error { + errors: Message[] + warnings: Message[] +} + +/** Documentation: https://esbuild.github.io/api/#serve-arguments */ +export interface ServeOptions { + port?: number + host?: string + servedir?: string + keyfile?: string + certfile?: string + fallback?: string + cors?: CORSOptions + onRequest?: (args: ServeOnRequestArgs) => void +} + +/** Documentation: https://esbuild.github.io/api/#cors */ +export interface CORSOptions { + origin?: string | string[] +} + +export interface ServeOnRequestArgs { + remoteAddress: string + method: string + path: string + status: number + /** The time to generate the response, not to send it */ + timeInMS: number +} + +/** Documentation: https://esbuild.github.io/api/#serve-return-values */ +export interface ServeResult { + port: number + hosts: string[] +} + +export interface TransformOptions extends CommonOptions { + /** Documentation: https://esbuild.github.io/api/#sourcefile */ + sourcefile?: string + /** Documentation: https://esbuild.github.io/api/#loader */ + loader?: Loader + /** Documentation: https://esbuild.github.io/api/#banner */ + banner?: string + /** Documentation: https://esbuild.github.io/api/#footer */ + footer?: string +} + +export interface TransformResult { + code: string + map: string + warnings: Message[] + /** Only when "mangleCache" is present */ + mangleCache: Record | (ProvidedOptions['mangleCache'] extends Object ? never : undefined) + /** Only when "legalComments" is "external" */ + legalComments: string | (ProvidedOptions['legalComments'] extends 'external' ? never : undefined) +} + +export interface TransformFailure extends Error { + errors: Message[] + warnings: Message[] +} + +export interface Plugin { + name: string + setup: (build: PluginBuild) => (void | Promise) +} + +export interface PluginBuild { + /** Documentation: https://esbuild.github.io/plugins/#build-options */ + initialOptions: BuildOptions + + /** Documentation: https://esbuild.github.io/plugins/#resolve */ + resolve(path: string, options?: ResolveOptions): Promise + + /** Documentation: https://esbuild.github.io/plugins/#on-start */ + onStart(callback: () => + (OnStartResult | null | void | Promise)): void + + /** Documentation: https://esbuild.github.io/plugins/#on-end */ + onEnd(callback: (result: BuildResult) => + (OnEndResult | null | void | Promise)): void + + /** Documentation: https://esbuild.github.io/plugins/#on-resolve */ + onResolve(options: OnResolveOptions, callback: (args: OnResolveArgs) => + (OnResolveResult | null | undefined | Promise)): void + + /** Documentation: https://esbuild.github.io/plugins/#on-load */ + onLoad(options: OnLoadOptions, callback: (args: OnLoadArgs) => + (OnLoadResult | null | undefined | Promise)): void + + /** Documentation: https://esbuild.github.io/plugins/#on-dispose */ + onDispose(callback: () => void): void + + // This is a full copy of the esbuild library in case you need it + esbuild: { + context: typeof context, + build: typeof build, + buildSync: typeof buildSync, + transform: typeof transform, + transformSync: typeof transformSync, + formatMessages: typeof formatMessages, + formatMessagesSync: typeof formatMessagesSync, + analyzeMetafile: typeof analyzeMetafile, + analyzeMetafileSync: typeof analyzeMetafileSync, + initialize: typeof initialize, + version: typeof version, + } +} + +/** Documentation: https://esbuild.github.io/plugins/#resolve-options */ +export interface ResolveOptions { + pluginName?: string + importer?: string + namespace?: string + resolveDir?: string + kind?: ImportKind + pluginData?: any + with?: Record +} + +/** Documentation: https://esbuild.github.io/plugins/#resolve-results */ +export interface ResolveResult { + errors: Message[] + warnings: Message[] + + path: string + external: boolean + sideEffects: boolean + namespace: string + suffix: string + pluginData: any +} + +export interface OnStartResult { + errors?: PartialMessage[] + warnings?: PartialMessage[] +} + +export interface OnEndResult { + errors?: PartialMessage[] + warnings?: PartialMessage[] +} + +/** Documentation: https://esbuild.github.io/plugins/#on-resolve-options */ +export interface OnResolveOptions { + filter: RegExp + namespace?: string +} + +/** Documentation: https://esbuild.github.io/plugins/#on-resolve-arguments */ +export interface OnResolveArgs { + path: string + importer: string + namespace: string + resolveDir: string + kind: ImportKind + pluginData: any + with: Record +} + +export type ImportKind = + | 'entry-point' + + // JS + | 'import-statement' + | 'require-call' + | 'dynamic-import' + | 'require-resolve' + + // CSS + | 'import-rule' + | 'composes-from' + | 'url-token' + +/** Documentation: https://esbuild.github.io/plugins/#on-resolve-results */ +export interface OnResolveResult { + pluginName?: string + + errors?: PartialMessage[] + warnings?: PartialMessage[] + + path?: string + external?: boolean + sideEffects?: boolean + namespace?: string + suffix?: string + pluginData?: any + + watchFiles?: string[] + watchDirs?: string[] +} + +/** Documentation: https://esbuild.github.io/plugins/#on-load-options */ +export interface OnLoadOptions { + filter: RegExp + namespace?: string +} + +/** Documentation: https://esbuild.github.io/plugins/#on-load-arguments */ +export interface OnLoadArgs { + path: string + namespace: string + suffix: string + pluginData: any + with: Record +} + +/** Documentation: https://esbuild.github.io/plugins/#on-load-results */ +export interface OnLoadResult { + pluginName?: string + + errors?: PartialMessage[] + warnings?: PartialMessage[] + + contents?: string | Uint8Array + resolveDir?: string + loader?: Loader + pluginData?: any + + watchFiles?: string[] + watchDirs?: string[] +} + +export interface PartialMessage { + id?: string + pluginName?: string + text?: string + location?: Partial | null + notes?: PartialNote[] + detail?: any +} + +export interface PartialNote { + text?: string + location?: Partial | null +} + +/** Documentation: https://esbuild.github.io/api/#metafile */ +export interface Metafile { + inputs: { + [path: string]: { + bytes: number + imports: { + path: string + kind: ImportKind + external?: boolean + original?: string + with?: Record + }[] + format?: 'cjs' | 'esm' + with?: Record + } + } + outputs: { + [path: string]: { + bytes: number + inputs: { + [path: string]: { + bytesInOutput: number + } + } + imports: { + path: string + kind: ImportKind | 'file-loader' + external?: boolean + }[] + exports: string[] + entryPoint?: string + cssBundle?: string + } + } +} + +export interface FormatMessagesOptions { + kind: 'error' | 'warning' + color?: boolean + terminalWidth?: number +} + +export interface AnalyzeMetafileOptions { + color?: boolean + verbose?: boolean +} + +/** Documentation: https://esbuild.github.io/api/#watch-arguments */ +export interface WatchOptions { + delay?: number // In milliseconds +} + +export interface BuildContext { + /** Documentation: https://esbuild.github.io/api/#rebuild */ + rebuild(): Promise> + + /** Documentation: https://esbuild.github.io/api/#watch */ + watch(options?: WatchOptions): Promise + + /** Documentation: https://esbuild.github.io/api/#serve */ + serve(options?: ServeOptions): Promise + + cancel(): Promise + dispose(): Promise +} + +// This is a TypeScript type-level function which replaces any keys in "In" +// that aren't in "Out" with "never". We use this to reject properties with +// typos in object literals. See: https://stackoverflow.com/questions/49580725 +type SameShape = In & { [Key in Exclude]: never } + +/** + * This function invokes the "esbuild" command-line tool for you. It returns a + * promise that either resolves with a "BuildResult" object or rejects with a + * "BuildFailure" object. + * + * - Works in node: yes + * - Works in browser: yes + * + * Documentation: https://esbuild.github.io/api/#build + */ +export declare function build(options: SameShape): Promise> + +/** + * This is the advanced long-running form of "build" that supports additional + * features such as watch mode and a local development server. + * + * - Works in node: yes + * - Works in browser: no + * + * Documentation: https://esbuild.github.io/api/#build + */ +export declare function context(options: SameShape): Promise> + +/** + * This function transforms a single JavaScript file. It can be used to minify + * JavaScript, convert TypeScript/JSX to JavaScript, or convert newer JavaScript + * to older JavaScript. It returns a promise that is either resolved with a + * "TransformResult" object or rejected with a "TransformFailure" object. + * + * - Works in node: yes + * - Works in browser: yes + * + * Documentation: https://esbuild.github.io/api/#transform + */ +export declare function transform(input: string | Uint8Array, options?: SameShape): Promise> + +/** + * Converts log messages to formatted message strings suitable for printing in + * the terminal. This allows you to reuse the built-in behavior of esbuild's + * log message formatter. This is a batch-oriented API for efficiency. + * + * - Works in node: yes + * - Works in browser: yes + */ +export declare function formatMessages(messages: PartialMessage[], options: FormatMessagesOptions): Promise + +/** + * Pretty-prints an analysis of the metafile JSON to a string. This is just for + * convenience to be able to match esbuild's pretty-printing exactly. If you want + * to customize it, you can just inspect the data in the metafile yourself. + * + * - Works in node: yes + * - Works in browser: yes + * + * Documentation: https://esbuild.github.io/api/#analyze + */ +export declare function analyzeMetafile(metafile: Metafile | string, options?: AnalyzeMetafileOptions): Promise + +/** + * A synchronous version of "build". + * + * - Works in node: yes + * - Works in browser: no + * + * Documentation: https://esbuild.github.io/api/#build + */ +export declare function buildSync(options: SameShape): BuildResult + +/** + * A synchronous version of "transform". + * + * - Works in node: yes + * - Works in browser: no + * + * Documentation: https://esbuild.github.io/api/#transform + */ +export declare function transformSync(input: string | Uint8Array, options?: SameShape): TransformResult + +/** + * A synchronous version of "formatMessages". + * + * - Works in node: yes + * - Works in browser: no + */ +export declare function formatMessagesSync(messages: PartialMessage[], options: FormatMessagesOptions): string[] + +/** + * A synchronous version of "analyzeMetafile". + * + * - Works in node: yes + * - Works in browser: no + * + * Documentation: https://esbuild.github.io/api/#analyze + */ +export declare function analyzeMetafileSync(metafile: Metafile | string, options?: AnalyzeMetafileOptions): string + +/** + * This configures the browser-based version of esbuild. It is necessary to + * call this first and wait for the returned promise to be resolved before + * making other API calls when using esbuild in the browser. + * + * - Works in node: yes + * - Works in browser: yes ("options" is required) + * + * Documentation: https://esbuild.github.io/api/#browser + */ +export declare function initialize(options: InitializeOptions): Promise + +export interface InitializeOptions { + /** + * The URL of the "esbuild.wasm" file. This must be provided when running + * esbuild in the browser. + */ + wasmURL?: string | URL + + /** + * The result of calling "new WebAssembly.Module(buffer)" where "buffer" + * is a typed array or ArrayBuffer containing the binary code of the + * "esbuild.wasm" file. + * + * You can use this as an alternative to "wasmURL" for environments where it's + * not possible to download the WebAssembly module. + */ + wasmModule?: WebAssembly.Module + + /** + * By default esbuild runs the WebAssembly-based browser API in a web worker + * to avoid blocking the UI thread. This can be disabled by setting "worker" + * to false. + */ + worker?: boolean +} + +export let version: string + +// Call this function to terminate esbuild's child process. The child process +// is not terminated and re-created after each API call because it's more +// efficient to keep it around when there are multiple API calls. +// +// In node this happens automatically before the parent node process exits. So +// you only need to call this if you know you will not make any more esbuild +// API calls and you want to clean up resources. +// +// Unlike node, Deno lacks the necessary APIs to clean up child processes +// automatically. You must manually call stop() in Deno when you're done +// using esbuild or Deno will continue running forever. +// +// Another reason you might want to call this is if you are using esbuild from +// within a Deno test. Deno fails tests that create a child process without +// killing it before the test ends, so you have to call this function (and +// await the returned promise) in every Deno test that uses esbuild. +export declare function stop(): Promise + +// Note: These declarations exist to avoid type errors when you omit "dom" from +// "lib" in your "tsconfig.json" file. TypeScript confusingly declares the +// global "WebAssembly" type in "lib.dom.d.ts" even though it has nothing to do +// with the browser DOM and is present in many non-browser JavaScript runtimes +// (e.g. node and deno). Declaring it here allows esbuild's API to be used in +// these scenarios. +// +// There's an open issue about getting this problem corrected (although these +// declarations will need to remain even if this is fixed for backward +// compatibility with older TypeScript versions): +// +// https://github.com/microsoft/TypeScript-DOM-lib-generator/issues/826 +// +declare global { + namespace WebAssembly { + interface Module { + } + } + interface URL { + } +} diff --git a/tools/ui/node_modules/esbuild/lib/main.js b/tools/ui/node_modules/esbuild/lib/main.js new file mode 100644 index 0000000000000000000000000000000000000000..1c23302b938a1164a990027c2e376aae8afc3e5b --- /dev/null +++ b/tools/ui/node_modules/esbuild/lib/main.js @@ -0,0 +1,2532 @@ +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// lib/npm/node.ts +var node_exports = {}; +__export(node_exports, { + analyzeMetafile: () => analyzeMetafile, + analyzeMetafileSync: () => analyzeMetafileSync, + build: () => build, + buildSync: () => buildSync, + context: () => context, + default: () => node_default, + formatMessages: () => formatMessages, + formatMessagesSync: () => formatMessagesSync, + initialize: () => initialize, + stop: () => stop, + transform: () => transform, + transformSync: () => transformSync, + version: () => version +}); +module.exports = __toCommonJS(node_exports); + +// lib/shared/stdio_protocol.ts +function encodePacket(packet) { + let visit = (value) => { + if (value === null) { + bb.write8(0); + } else if (typeof value === "boolean") { + bb.write8(1); + bb.write8(+value); + } else if (typeof value === "number") { + bb.write8(2); + bb.write32(value | 0); + } else if (typeof value === "string") { + bb.write8(3); + bb.write(encodeUTF8(value)); + } else if (value instanceof Uint8Array) { + bb.write8(4); + bb.write(value); + } else if (value instanceof Array) { + bb.write8(5); + bb.write32(value.length); + for (let item of value) { + visit(item); + } + } else { + let keys = Object.keys(value); + bb.write8(6); + bb.write32(keys.length); + for (let key of keys) { + bb.write(encodeUTF8(key)); + visit(value[key]); + } + } + }; + let bb = new ByteBuffer(); + bb.write32(0); + bb.write32(packet.id << 1 | +!packet.isRequest); + visit(packet.value); + writeUInt32LE(bb.buf, bb.len - 4, 0); + return bb.buf.subarray(0, bb.len); +} +function decodePacket(bytes) { + let visit = () => { + switch (bb.read8()) { + case 0: + return null; + case 1: + return !!bb.read8(); + case 2: + return bb.read32(); + case 3: + return decodeUTF8(bb.read()); + case 4: + return bb.read(); + case 5: { + let count = bb.read32(); + let value2 = []; + for (let i = 0; i < count; i++) { + value2.push(visit()); + } + return value2; + } + case 6: { + let count = bb.read32(); + let value2 = {}; + for (let i = 0; i < count; i++) { + value2[decodeUTF8(bb.read())] = visit(); + } + return value2; + } + default: + throw new Error("Invalid packet"); + } + }; + let bb = new ByteBuffer(bytes); + let id = bb.read32(); + let isRequest = (id & 1) === 0; + id >>>= 1; + let value = visit(); + if (bb.ptr !== bytes.length) { + throw new Error("Invalid packet"); + } + return { id, isRequest, value }; +} +var ByteBuffer = class { + constructor(buf = new Uint8Array(1024)) { + this.buf = buf; + this.len = 0; + this.ptr = 0; + } + _write(delta) { + if (this.len + delta > this.buf.length) { + let clone = new Uint8Array((this.len + delta) * 2); + clone.set(this.buf); + this.buf = clone; + } + this.len += delta; + return this.len - delta; + } + write8(value) { + let offset = this._write(1); + this.buf[offset] = value; + } + write32(value) { + let offset = this._write(4); + writeUInt32LE(this.buf, value, offset); + } + write(bytes) { + let offset = this._write(4 + bytes.length); + writeUInt32LE(this.buf, bytes.length, offset); + this.buf.set(bytes, offset + 4); + } + _read(delta) { + if (this.ptr + delta > this.buf.length) { + throw new Error("Invalid packet"); + } + this.ptr += delta; + return this.ptr - delta; + } + read8() { + return this.buf[this._read(1)]; + } + read32() { + return readUInt32LE(this.buf, this._read(4)); + } + read() { + let length = this.read32(); + let bytes = new Uint8Array(length); + let ptr = this._read(bytes.length); + bytes.set(this.buf.subarray(ptr, ptr + length)); + return bytes; + } +}; +var encodeUTF8; +var decodeUTF8; +var encodeInvariant; +if (typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined") { + let encoder = new TextEncoder(); + let decoder = new TextDecoder(); + encodeUTF8 = (text) => encoder.encode(text); + decodeUTF8 = (bytes) => decoder.decode(bytes); + encodeInvariant = 'new TextEncoder().encode("")'; +} else if (typeof Buffer !== "undefined") { + encodeUTF8 = (text) => Buffer.from(text); + decodeUTF8 = (bytes) => { + let { buffer, byteOffset, byteLength } = bytes; + return Buffer.from(buffer, byteOffset, byteLength).toString(); + }; + encodeInvariant = 'Buffer.from("")'; +} else { + throw new Error("No UTF-8 codec found"); +} +if (!(encodeUTF8("") instanceof Uint8Array)) + throw new Error(`Invariant violation: "${encodeInvariant} instanceof Uint8Array" is incorrectly false + +This indicates that your JavaScript environment is broken. You cannot use +esbuild in this environment because esbuild relies on this invariant. This +is not a problem with esbuild. You need to fix your environment instead. +`); +function readUInt32LE(buffer, offset) { + return (buffer[offset++] | buffer[offset++] << 8 | buffer[offset++] << 16 | buffer[offset++] << 24) >>> 0; +} +function writeUInt32LE(buffer, value, offset) { + buffer[offset++] = value; + buffer[offset++] = value >> 8; + buffer[offset++] = value >> 16; + buffer[offset++] = value >> 24; +} + +// lib/shared/uint8array_json_parser.ts +var fromCharCode = String.fromCharCode; +function throwSyntaxError(bytes, index, message) { + const c = bytes[index]; + let line = 1; + let column = 0; + for (let i = 0; i < index; i++) { + if (bytes[i] === 10 /* Newline */) { + line++; + column = 0; + } else { + column++; + } + } + throw new SyntaxError( + message ? message : index === bytes.length ? "Unexpected end of input while parsing JSON" : c >= 32 && c <= 126 ? `Unexpected character ${fromCharCode(c)} in JSON at position ${index} (line ${line}, column ${column})` : `Unexpected byte 0x${c.toString(16)} in JSON at position ${index} (line ${line}, column ${column})` + ); +} +function JSON_parse(bytes) { + if (!(bytes instanceof Uint8Array)) { + throw new Error(`JSON input must be a Uint8Array`); + } + const propertyStack = []; + const objectStack = []; + const stateStack = []; + const length = bytes.length; + let property = null; + let state = 0 /* TopLevel */; + let object; + let i = 0; + while (i < length) { + let c = bytes[i++]; + if (c <= 32 /* Space */) { + continue; + } + let value; + if (state === 2 /* Object */ && property === null && c !== 34 /* Quote */ && c !== 125 /* CloseBrace */) { + throwSyntaxError(bytes, --i); + } + switch (c) { + // True + case 116 /* LowerT */: { + if (bytes[i++] !== 114 /* LowerR */ || bytes[i++] !== 117 /* LowerU */ || bytes[i++] !== 101 /* LowerE */) { + throwSyntaxError(bytes, --i); + } + value = true; + break; + } + // False + case 102 /* LowerF */: { + if (bytes[i++] !== 97 /* LowerA */ || bytes[i++] !== 108 /* LowerL */ || bytes[i++] !== 115 /* LowerS */ || bytes[i++] !== 101 /* LowerE */) { + throwSyntaxError(bytes, --i); + } + value = false; + break; + } + // Null + case 110 /* LowerN */: { + if (bytes[i++] !== 117 /* LowerU */ || bytes[i++] !== 108 /* LowerL */ || bytes[i++] !== 108 /* LowerL */) { + throwSyntaxError(bytes, --i); + } + value = null; + break; + } + // Number begin + case 45 /* Minus */: + case 46 /* Dot */: + case 48 /* Digit0 */: + case 49 /* Digit1 */: + case 50 /* Digit2 */: + case 51 /* Digit3 */: + case 52 /* Digit4 */: + case 53 /* Digit5 */: + case 54 /* Digit6 */: + case 55 /* Digit7 */: + case 56 /* Digit8 */: + case 57 /* Digit9 */: { + let index = i; + value = fromCharCode(c); + c = bytes[i]; + while (true) { + switch (c) { + case 43 /* Plus */: + case 45 /* Minus */: + case 46 /* Dot */: + case 48 /* Digit0 */: + case 49 /* Digit1 */: + case 50 /* Digit2 */: + case 51 /* Digit3 */: + case 52 /* Digit4 */: + case 53 /* Digit5 */: + case 54 /* Digit6 */: + case 55 /* Digit7 */: + case 56 /* Digit8 */: + case 57 /* Digit9 */: + case 101 /* LowerE */: + case 69 /* UpperE */: { + value += fromCharCode(c); + c = bytes[++i]; + continue; + } + } + break; + } + value = +value; + if (isNaN(value)) { + throwSyntaxError(bytes, --index, "Invalid number"); + } + break; + } + // String begin + case 34 /* Quote */: { + value = ""; + while (true) { + if (i >= length) { + throwSyntaxError(bytes, length); + } + c = bytes[i++]; + if (c === 34 /* Quote */) { + break; + } else if (c === 92 /* Backslash */) { + switch (bytes[i++]) { + // Normal escape sequence + case 34 /* Quote */: + value += '"'; + break; + case 47 /* Slash */: + value += "/"; + break; + case 92 /* Backslash */: + value += "\\"; + break; + case 98 /* LowerB */: + value += "\b"; + break; + case 102 /* LowerF */: + value += "\f"; + break; + case 110 /* LowerN */: + value += "\n"; + break; + case 114 /* LowerR */: + value += "\r"; + break; + case 116 /* LowerT */: + value += " "; + break; + // Unicode escape sequence + case 117 /* LowerU */: { + let code = 0; + for (let j = 0; j < 4; j++) { + c = bytes[i++]; + code <<= 4; + if (c >= 48 /* Digit0 */ && c <= 57 /* Digit9 */) code |= c - 48 /* Digit0 */; + else if (c >= 97 /* LowerA */ && c <= 102 /* LowerF */) code |= c + (10 - 97 /* LowerA */); + else if (c >= 65 /* UpperA */ && c <= 70 /* UpperF */) code |= c + (10 - 65 /* UpperA */); + else throwSyntaxError(bytes, --i); + } + value += fromCharCode(code); + break; + } + // Invalid escape sequence + default: + throwSyntaxError(bytes, --i); + break; + } + } else if (c <= 127) { + value += fromCharCode(c); + } else if ((c & 224) === 192) { + value += fromCharCode((c & 31) << 6 | bytes[i++] & 63); + } else if ((c & 240) === 224) { + value += fromCharCode((c & 15) << 12 | (bytes[i++] & 63) << 6 | bytes[i++] & 63); + } else if ((c & 248) == 240) { + let codePoint = (c & 7) << 18 | (bytes[i++] & 63) << 12 | (bytes[i++] & 63) << 6 | bytes[i++] & 63; + if (codePoint > 65535) { + codePoint -= 65536; + value += fromCharCode(codePoint >> 10 & 1023 | 55296); + codePoint = 56320 | codePoint & 1023; + } + value += fromCharCode(codePoint); + } + } + value[0]; + break; + } + // Array begin + case 91 /* OpenBracket */: { + value = []; + propertyStack.push(property); + objectStack.push(object); + stateStack.push(state); + property = null; + object = value; + state = 1 /* Array */; + continue; + } + // Object begin + case 123 /* OpenBrace */: { + value = {}; + propertyStack.push(property); + objectStack.push(object); + stateStack.push(state); + property = null; + object = value; + state = 2 /* Object */; + continue; + } + // Array end + case 93 /* CloseBracket */: { + if (state !== 1 /* Array */) { + throwSyntaxError(bytes, --i); + } + value = object; + property = propertyStack.pop(); + object = objectStack.pop(); + state = stateStack.pop(); + break; + } + // Object end + case 125 /* CloseBrace */: { + if (state !== 2 /* Object */) { + throwSyntaxError(bytes, --i); + } + value = object; + property = propertyStack.pop(); + object = objectStack.pop(); + state = stateStack.pop(); + break; + } + default: { + throwSyntaxError(bytes, --i); + } + } + c = bytes[i]; + while (c <= 32 /* Space */) { + c = bytes[++i]; + } + switch (state) { + case 0 /* TopLevel */: { + if (i === length) { + return value; + } + break; + } + case 1 /* Array */: { + object.push(value); + if (c === 44 /* Comma */) { + i++; + continue; + } + if (c === 93 /* CloseBracket */) { + continue; + } + break; + } + case 2 /* Object */: { + if (property === null) { + property = value; + if (c === 58 /* Colon */) { + i++; + continue; + } + } else { + object[property] = value; + property = null; + if (c === 44 /* Comma */) { + i++; + continue; + } + if (c === 125 /* CloseBrace */) { + continue; + } + } + break; + } + } + break; + } + throwSyntaxError(bytes, i); +} + +// lib/shared/common.ts +var quote = JSON.stringify; +var buildLogLevelDefault = "warning"; +var transformLogLevelDefault = "silent"; +function validateAndJoinStringArray(values, what) { + const toJoin = []; + for (const value of values) { + validateStringValue(value, what); + if (value.indexOf(",") >= 0) throw new Error(`Invalid ${what}: ${value}`); + toJoin.push(value); + } + return toJoin.join(","); +} +var canBeAnything = () => null; +var mustBeBoolean = (value) => typeof value === "boolean" ? null : "a boolean"; +var mustBeString = (value) => typeof value === "string" ? null : "a string"; +var mustBeRegExp = (value) => value instanceof RegExp ? null : "a RegExp object"; +var mustBeInteger = (value) => typeof value === "number" && value === (value | 0) ? null : "an integer"; +var mustBeValidPortNumber = (value) => typeof value === "number" && value === (value | 0) && value >= 0 && value <= 65535 ? null : "a valid port number"; +var mustBeFunction = (value) => typeof value === "function" ? null : "a function"; +var mustBeArray = (value) => Array.isArray(value) ? null : "an array"; +var mustBeArrayOfStrings = (value) => Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "an array of strings"; +var mustBeObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? null : "an object"; +var mustBeEntryPoints = (value) => typeof value === "object" && value !== null ? null : "an array or an object"; +var mustBeWebAssemblyModule = (value) => value instanceof WebAssembly.Module ? null : "a WebAssembly.Module"; +var mustBeObjectOrNull = (value) => typeof value === "object" && !Array.isArray(value) ? null : "an object or null"; +var mustBeStringOrBoolean = (value) => typeof value === "string" || typeof value === "boolean" ? null : "a string or a boolean"; +var mustBeStringOrObject = (value) => typeof value === "string" || typeof value === "object" && value !== null && !Array.isArray(value) ? null : "a string or an object"; +var mustBeStringOrArrayOfStrings = (value) => typeof value === "string" || Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "a string or an array of strings"; +var mustBeStringOrUint8Array = (value) => typeof value === "string" || value instanceof Uint8Array ? null : "a string or a Uint8Array"; +var mustBeStringOrURL = (value) => typeof value === "string" || value instanceof URL ? null : "a string or a URL"; +function getFlag(object, keys, key, mustBeFn) { + let value = object[key]; + keys[key + ""] = true; + if (value === void 0) return void 0; + let mustBe = mustBeFn(value); + if (mustBe !== null) throw new Error(`${quote(key)} must be ${mustBe}`); + return value; +} +function checkForInvalidFlags(object, keys, where) { + for (let key in object) { + if (!(key in keys)) { + throw new Error(`Invalid option ${where}: ${quote(key)}`); + } + } +} +function validateInitializeOptions(options) { + let keys = /* @__PURE__ */ Object.create(null); + let wasmURL = getFlag(options, keys, "wasmURL", mustBeStringOrURL); + let wasmModule = getFlag(options, keys, "wasmModule", mustBeWebAssemblyModule); + let worker = getFlag(options, keys, "worker", mustBeBoolean); + checkForInvalidFlags(options, keys, "in initialize() call"); + return { + wasmURL, + wasmModule, + worker + }; +} +function validateMangleCache(mangleCache) { + let validated; + if (mangleCache !== void 0) { + validated = /* @__PURE__ */ Object.create(null); + for (let key in mangleCache) { + let value = mangleCache[key]; + if (typeof value === "string" || value === false) { + validated[key] = value; + } else { + throw new Error(`Expected ${quote(key)} in mangle cache to map to either a string or false`); + } + } + } + return validated; +} +function pushLogFlags(flags, options, keys, isTTY2, logLevelDefault) { + let color = getFlag(options, keys, "color", mustBeBoolean); + let logLevel = getFlag(options, keys, "logLevel", mustBeString); + let logLimit = getFlag(options, keys, "logLimit", mustBeInteger); + if (color !== void 0) flags.push(`--color=${color}`); + else if (isTTY2) flags.push(`--color=true`); + flags.push(`--log-level=${logLevel || logLevelDefault}`); + flags.push(`--log-limit=${logLimit || 0}`); +} +function validateStringValue(value, what, key) { + if (typeof value !== "string") { + throw new Error(`Expected value for ${what}${key !== void 0 ? " " + quote(key) : ""} to be a string, got ${typeof value} instead`); + } + return value; +} +function pushCommonFlags(flags, options, keys) { + let legalComments = getFlag(options, keys, "legalComments", mustBeString); + let sourceRoot = getFlag(options, keys, "sourceRoot", mustBeString); + let sourcesContent = getFlag(options, keys, "sourcesContent", mustBeBoolean); + let target = getFlag(options, keys, "target", mustBeStringOrArrayOfStrings); + let format = getFlag(options, keys, "format", mustBeString); + let globalName = getFlag(options, keys, "globalName", mustBeString); + let mangleProps = getFlag(options, keys, "mangleProps", mustBeRegExp); + let reserveProps = getFlag(options, keys, "reserveProps", mustBeRegExp); + let mangleQuoted = getFlag(options, keys, "mangleQuoted", mustBeBoolean); + let minify = getFlag(options, keys, "minify", mustBeBoolean); + let minifySyntax = getFlag(options, keys, "minifySyntax", mustBeBoolean); + let minifyWhitespace = getFlag(options, keys, "minifyWhitespace", mustBeBoolean); + let minifyIdentifiers = getFlag(options, keys, "minifyIdentifiers", mustBeBoolean); + let lineLimit = getFlag(options, keys, "lineLimit", mustBeInteger); + let drop = getFlag(options, keys, "drop", mustBeArrayOfStrings); + let dropLabels = getFlag(options, keys, "dropLabels", mustBeArrayOfStrings); + let charset = getFlag(options, keys, "charset", mustBeString); + let treeShaking = getFlag(options, keys, "treeShaking", mustBeBoolean); + let ignoreAnnotations = getFlag(options, keys, "ignoreAnnotations", mustBeBoolean); + let jsx = getFlag(options, keys, "jsx", mustBeString); + let jsxFactory = getFlag(options, keys, "jsxFactory", mustBeString); + let jsxFragment = getFlag(options, keys, "jsxFragment", mustBeString); + let jsxImportSource = getFlag(options, keys, "jsxImportSource", mustBeString); + let jsxDev = getFlag(options, keys, "jsxDev", mustBeBoolean); + let jsxSideEffects = getFlag(options, keys, "jsxSideEffects", mustBeBoolean); + let define = getFlag(options, keys, "define", mustBeObject); + let logOverride = getFlag(options, keys, "logOverride", mustBeObject); + let supported = getFlag(options, keys, "supported", mustBeObject); + let pure = getFlag(options, keys, "pure", mustBeArrayOfStrings); + let keepNames = getFlag(options, keys, "keepNames", mustBeBoolean); + let platform = getFlag(options, keys, "platform", mustBeString); + let tsconfigRaw = getFlag(options, keys, "tsconfigRaw", mustBeStringOrObject); + let absPaths = getFlag(options, keys, "absPaths", mustBeArrayOfStrings); + if (legalComments) flags.push(`--legal-comments=${legalComments}`); + if (sourceRoot !== void 0) flags.push(`--source-root=${sourceRoot}`); + if (sourcesContent !== void 0) flags.push(`--sources-content=${sourcesContent}`); + if (target) flags.push(`--target=${validateAndJoinStringArray(Array.isArray(target) ? target : [target], "target")}`); + if (format) flags.push(`--format=${format}`); + if (globalName) flags.push(`--global-name=${globalName}`); + if (platform) flags.push(`--platform=${platform}`); + if (tsconfigRaw) flags.push(`--tsconfig-raw=${typeof tsconfigRaw === "string" ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`); + if (minify) flags.push("--minify"); + if (minifySyntax) flags.push("--minify-syntax"); + if (minifyWhitespace) flags.push("--minify-whitespace"); + if (minifyIdentifiers) flags.push("--minify-identifiers"); + if (lineLimit) flags.push(`--line-limit=${lineLimit}`); + if (charset) flags.push(`--charset=${charset}`); + if (treeShaking !== void 0) flags.push(`--tree-shaking=${treeShaking}`); + if (ignoreAnnotations) flags.push(`--ignore-annotations`); + if (drop) for (let what of drop) flags.push(`--drop:${validateStringValue(what, "drop")}`); + if (dropLabels) flags.push(`--drop-labels=${validateAndJoinStringArray(dropLabels, "drop label")}`); + if (absPaths) flags.push(`--abs-paths=${validateAndJoinStringArray(absPaths, "abs paths")}`); + if (mangleProps) flags.push(`--mangle-props=${jsRegExpToGoRegExp(mangleProps)}`); + if (reserveProps) flags.push(`--reserve-props=${jsRegExpToGoRegExp(reserveProps)}`); + if (mangleQuoted !== void 0) flags.push(`--mangle-quoted=${mangleQuoted}`); + if (jsx) flags.push(`--jsx=${jsx}`); + if (jsxFactory) flags.push(`--jsx-factory=${jsxFactory}`); + if (jsxFragment) flags.push(`--jsx-fragment=${jsxFragment}`); + if (jsxImportSource) flags.push(`--jsx-import-source=${jsxImportSource}`); + if (jsxDev) flags.push(`--jsx-dev`); + if (jsxSideEffects) flags.push(`--jsx-side-effects`); + if (define) { + for (let key in define) { + if (key.indexOf("=") >= 0) throw new Error(`Invalid define: ${key}`); + flags.push(`--define:${key}=${validateStringValue(define[key], "define", key)}`); + } + } + if (logOverride) { + for (let key in logOverride) { + if (key.indexOf("=") >= 0) throw new Error(`Invalid log override: ${key}`); + flags.push(`--log-override:${key}=${validateStringValue(logOverride[key], "log override", key)}`); + } + } + if (supported) { + for (let key in supported) { + if (key.indexOf("=") >= 0) throw new Error(`Invalid supported: ${key}`); + const value = supported[key]; + if (typeof value !== "boolean") throw new Error(`Expected value for supported ${quote(key)} to be a boolean, got ${typeof value} instead`); + flags.push(`--supported:${key}=${value}`); + } + } + if (pure) for (let fn of pure) flags.push(`--pure:${validateStringValue(fn, "pure")}`); + if (keepNames) flags.push(`--keep-names`); +} +function flagsForBuildOptions(callName, options, isTTY2, logLevelDefault, writeDefault) { + var _a2; + let flags = []; + let entries = []; + let keys = /* @__PURE__ */ Object.create(null); + let stdinContents = null; + let stdinResolveDir = null; + pushLogFlags(flags, options, keys, isTTY2, logLevelDefault); + pushCommonFlags(flags, options, keys); + let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean); + let bundle = getFlag(options, keys, "bundle", mustBeBoolean); + let splitting = getFlag(options, keys, "splitting", mustBeBoolean); + let preserveSymlinks = getFlag(options, keys, "preserveSymlinks", mustBeBoolean); + let metafile = getFlag(options, keys, "metafile", mustBeBoolean); + let outfile = getFlag(options, keys, "outfile", mustBeString); + let outdir = getFlag(options, keys, "outdir", mustBeString); + let outbase = getFlag(options, keys, "outbase", mustBeString); + let tsconfig = getFlag(options, keys, "tsconfig", mustBeString); + let resolveExtensions = getFlag(options, keys, "resolveExtensions", mustBeArrayOfStrings); + let nodePathsInput = getFlag(options, keys, "nodePaths", mustBeArrayOfStrings); + let mainFields = getFlag(options, keys, "mainFields", mustBeArrayOfStrings); + let conditions = getFlag(options, keys, "conditions", mustBeArrayOfStrings); + let external = getFlag(options, keys, "external", mustBeArrayOfStrings); + let packages = getFlag(options, keys, "packages", mustBeString); + let alias = getFlag(options, keys, "alias", mustBeObject); + let loader = getFlag(options, keys, "loader", mustBeObject); + let outExtension = getFlag(options, keys, "outExtension", mustBeObject); + let publicPath = getFlag(options, keys, "publicPath", mustBeString); + let entryNames = getFlag(options, keys, "entryNames", mustBeString); + let chunkNames = getFlag(options, keys, "chunkNames", mustBeString); + let assetNames = getFlag(options, keys, "assetNames", mustBeString); + let inject = getFlag(options, keys, "inject", mustBeArrayOfStrings); + let banner = getFlag(options, keys, "banner", mustBeObject); + let footer = getFlag(options, keys, "footer", mustBeObject); + let entryPoints = getFlag(options, keys, "entryPoints", mustBeEntryPoints); + let absWorkingDir = getFlag(options, keys, "absWorkingDir", mustBeString); + let stdin = getFlag(options, keys, "stdin", mustBeObject); + let write = (_a2 = getFlag(options, keys, "write", mustBeBoolean)) != null ? _a2 : writeDefault; + let allowOverwrite = getFlag(options, keys, "allowOverwrite", mustBeBoolean); + let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject); + keys.plugins = true; + checkForInvalidFlags(options, keys, `in ${callName}() call`); + if (sourcemap) flags.push(`--sourcemap${sourcemap === true ? "" : `=${sourcemap}`}`); + if (bundle) flags.push("--bundle"); + if (allowOverwrite) flags.push("--allow-overwrite"); + if (splitting) flags.push("--splitting"); + if (preserveSymlinks) flags.push("--preserve-symlinks"); + if (metafile) flags.push(`--metafile`); + if (outfile) flags.push(`--outfile=${outfile}`); + if (outdir) flags.push(`--outdir=${outdir}`); + if (outbase) flags.push(`--outbase=${outbase}`); + if (tsconfig) flags.push(`--tsconfig=${tsconfig}`); + if (packages) flags.push(`--packages=${packages}`); + if (resolveExtensions) flags.push(`--resolve-extensions=${validateAndJoinStringArray(resolveExtensions, "resolve extension")}`); + if (publicPath) flags.push(`--public-path=${publicPath}`); + if (entryNames) flags.push(`--entry-names=${entryNames}`); + if (chunkNames) flags.push(`--chunk-names=${chunkNames}`); + if (assetNames) flags.push(`--asset-names=${assetNames}`); + if (mainFields) flags.push(`--main-fields=${validateAndJoinStringArray(mainFields, "main field")}`); + if (conditions) flags.push(`--conditions=${validateAndJoinStringArray(conditions, "condition")}`); + if (external) for (let name of external) flags.push(`--external:${validateStringValue(name, "external")}`); + if (alias) { + for (let old in alias) { + if (old.indexOf("=") >= 0) throw new Error(`Invalid package name in alias: ${old}`); + flags.push(`--alias:${old}=${validateStringValue(alias[old], "alias", old)}`); + } + } + if (banner) { + for (let type in banner) { + if (type.indexOf("=") >= 0) throw new Error(`Invalid banner file type: ${type}`); + flags.push(`--banner:${type}=${validateStringValue(banner[type], "banner", type)}`); + } + } + if (footer) { + for (let type in footer) { + if (type.indexOf("=") >= 0) throw new Error(`Invalid footer file type: ${type}`); + flags.push(`--footer:${type}=${validateStringValue(footer[type], "footer", type)}`); + } + } + if (inject) for (let path3 of inject) flags.push(`--inject:${validateStringValue(path3, "inject")}`); + if (loader) { + for (let ext in loader) { + if (ext.indexOf("=") >= 0) throw new Error(`Invalid loader extension: ${ext}`); + flags.push(`--loader:${ext}=${validateStringValue(loader[ext], "loader", ext)}`); + } + } + if (outExtension) { + for (let ext in outExtension) { + if (ext.indexOf("=") >= 0) throw new Error(`Invalid out extension: ${ext}`); + flags.push(`--out-extension:${ext}=${validateStringValue(outExtension[ext], "out extension", ext)}`); + } + } + if (entryPoints) { + if (Array.isArray(entryPoints)) { + for (let i = 0, n = entryPoints.length; i < n; i++) { + let entryPoint = entryPoints[i]; + if (typeof entryPoint === "object" && entryPoint !== null) { + let entryPointKeys = /* @__PURE__ */ Object.create(null); + let input = getFlag(entryPoint, entryPointKeys, "in", mustBeString); + let output = getFlag(entryPoint, entryPointKeys, "out", mustBeString); + checkForInvalidFlags(entryPoint, entryPointKeys, "in entry point at index " + i); + if (input === void 0) throw new Error('Missing property "in" for entry point at index ' + i); + if (output === void 0) throw new Error('Missing property "out" for entry point at index ' + i); + entries.push([output, input]); + } else { + entries.push(["", validateStringValue(entryPoint, "entry point at index " + i)]); + } + } + } else { + for (let key in entryPoints) { + entries.push([key, validateStringValue(entryPoints[key], "entry point", key)]); + } + } + } + if (stdin) { + let stdinKeys = /* @__PURE__ */ Object.create(null); + let contents = getFlag(stdin, stdinKeys, "contents", mustBeStringOrUint8Array); + let resolveDir = getFlag(stdin, stdinKeys, "resolveDir", mustBeString); + let sourcefile = getFlag(stdin, stdinKeys, "sourcefile", mustBeString); + let loader2 = getFlag(stdin, stdinKeys, "loader", mustBeString); + checkForInvalidFlags(stdin, stdinKeys, 'in "stdin" object'); + if (sourcefile) flags.push(`--sourcefile=${sourcefile}`); + if (loader2) flags.push(`--loader=${loader2}`); + if (resolveDir) stdinResolveDir = resolveDir; + if (typeof contents === "string") stdinContents = encodeUTF8(contents); + else if (contents instanceof Uint8Array) stdinContents = contents; + } + let nodePaths = []; + if (nodePathsInput) { + for (let value of nodePathsInput) { + value += ""; + nodePaths.push(value); + } + } + return { + entries, + flags, + write, + stdinContents, + stdinResolveDir, + absWorkingDir, + nodePaths, + mangleCache: validateMangleCache(mangleCache) + }; +} +function flagsForTransformOptions(callName, options, isTTY2, logLevelDefault) { + let flags = []; + let keys = /* @__PURE__ */ Object.create(null); + pushLogFlags(flags, options, keys, isTTY2, logLevelDefault); + pushCommonFlags(flags, options, keys); + let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean); + let sourcefile = getFlag(options, keys, "sourcefile", mustBeString); + let loader = getFlag(options, keys, "loader", mustBeString); + let banner = getFlag(options, keys, "banner", mustBeString); + let footer = getFlag(options, keys, "footer", mustBeString); + let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject); + checkForInvalidFlags(options, keys, `in ${callName}() call`); + if (sourcemap) flags.push(`--sourcemap=${sourcemap === true ? "external" : sourcemap}`); + if (sourcefile) flags.push(`--sourcefile=${sourcefile}`); + if (loader) flags.push(`--loader=${loader}`); + if (banner) flags.push(`--banner=${banner}`); + if (footer) flags.push(`--footer=${footer}`); + return { + flags, + mangleCache: validateMangleCache(mangleCache) + }; +} +function createChannel(streamIn) { + const requestCallbacksByKey = {}; + const closeData = { didClose: false, reason: "" }; + let responseCallbacks = {}; + let nextRequestID = 0; + let nextBuildKey = 0; + let stdout = new Uint8Array(16 * 1024); + let stdoutUsed = 0; + let readFromStdout = (chunk) => { + let limit = stdoutUsed + chunk.length; + if (limit > stdout.length) { + let swap = new Uint8Array(limit * 2); + swap.set(stdout); + stdout = swap; + } + stdout.set(chunk, stdoutUsed); + stdoutUsed += chunk.length; + let offset = 0; + while (offset + 4 <= stdoutUsed) { + let length = readUInt32LE(stdout, offset); + if (offset + 4 + length > stdoutUsed) { + break; + } + offset += 4; + handleIncomingPacket(stdout.subarray(offset, offset + length)); + offset += length; + } + if (offset > 0) { + stdout.copyWithin(0, offset, stdoutUsed); + stdoutUsed -= offset; + } + }; + let afterClose = (error) => { + closeData.didClose = true; + if (error) closeData.reason = ": " + (error.message || error); + const text = "The service was stopped" + closeData.reason; + for (let id in responseCallbacks) { + responseCallbacks[id](text, null); + } + responseCallbacks = {}; + }; + let sendRequest = (refs, value, callback) => { + if (closeData.didClose) return callback("The service is no longer running" + closeData.reason, null); + let id = nextRequestID++; + responseCallbacks[id] = (error, response) => { + try { + callback(error, response); + } finally { + if (refs) refs.unref(); + } + }; + if (refs) refs.ref(); + streamIn.writeToStdin(encodePacket({ id, isRequest: true, value })); + }; + let sendResponse = (id, value) => { + if (closeData.didClose) throw new Error("The service is no longer running" + closeData.reason); + streamIn.writeToStdin(encodePacket({ id, isRequest: false, value })); + }; + let handleRequest = async (id, request) => { + try { + if (request.command === "ping") { + sendResponse(id, {}); + return; + } + if (typeof request.key === "number") { + const requestCallbacks = requestCallbacksByKey[request.key]; + if (!requestCallbacks) { + return; + } + const callback = requestCallbacks[request.command]; + if (callback) { + await callback(id, request); + return; + } + } + throw new Error(`Invalid command: ` + request.command); + } catch (e) { + const errors = [extractErrorMessageV8(e, streamIn, null, void 0, "")]; + try { + sendResponse(id, { errors }); + } catch { + } + } + }; + let isFirstPacket = true; + let handleIncomingPacket = (bytes) => { + if (isFirstPacket) { + isFirstPacket = false; + let binaryVersion = String.fromCharCode(...bytes); + if (binaryVersion !== "0.28.1") { + throw new Error(`Cannot start service: Host version "${"0.28.1"}" does not match binary version ${quote(binaryVersion)}`); + } + return; + } + let packet = decodePacket(bytes); + if (packet.isRequest) { + handleRequest(packet.id, packet.value); + } else { + let callback = responseCallbacks[packet.id]; + delete responseCallbacks[packet.id]; + if (packet.value.error) callback(packet.value.error, {}); + else callback(null, packet.value); + } + }; + let buildOrContext = ({ callName, refs, options, isTTY: isTTY2, defaultWD: defaultWD2, callback }) => { + let refCount = 0; + const buildKey = nextBuildKey++; + const requestCallbacks = {}; + const buildRefs = { + ref() { + if (++refCount === 1) { + if (refs) refs.ref(); + } + }, + unref() { + if (--refCount === 0) { + delete requestCallbacksByKey[buildKey]; + if (refs) refs.unref(); + } + } + }; + requestCallbacksByKey[buildKey] = requestCallbacks; + buildRefs.ref(); + buildOrContextImpl( + callName, + buildKey, + sendRequest, + sendResponse, + buildRefs, + streamIn, + requestCallbacks, + options, + isTTY2, + defaultWD2, + (err, res) => { + try { + callback(err, res); + } finally { + buildRefs.unref(); + } + } + ); + }; + let transform2 = ({ callName, refs, input, options, isTTY: isTTY2, fs: fs3, callback }) => { + const details = createObjectStash(); + let start = (inputPath) => { + try { + if (typeof input !== "string" && !(input instanceof Uint8Array)) + throw new Error('The input to "transform" must be a string or a Uint8Array'); + let { + flags, + mangleCache + } = flagsForTransformOptions(callName, options, isTTY2, transformLogLevelDefault); + let request = { + command: "transform", + flags, + inputFS: inputPath !== null, + input: inputPath !== null ? encodeUTF8(inputPath) : typeof input === "string" ? encodeUTF8(input) : input + }; + if (mangleCache) request.mangleCache = mangleCache; + sendRequest(refs, request, (error, response) => { + if (error) return callback(new Error(error), null); + let errors = replaceDetailsInMessages(response.errors, details); + let warnings = replaceDetailsInMessages(response.warnings, details); + let outstanding = 1; + let next = () => { + if (--outstanding === 0) { + let result = { + warnings, + code: response.code, + map: response.map, + mangleCache: void 0, + legalComments: void 0 + }; + if ("legalComments" in response) result.legalComments = response == null ? void 0 : response.legalComments; + if (response.mangleCache) result.mangleCache = response == null ? void 0 : response.mangleCache; + callback(null, result); + } + }; + if (errors.length > 0) return callback(failureErrorWithLog("Transform failed", errors, warnings), null); + if (response.codeFS) { + outstanding++; + fs3.readFile(response.code, (err, contents) => { + if (err !== null) { + callback(err, null); + } else { + response.code = contents; + next(); + } + }); + } + if (response.mapFS) { + outstanding++; + fs3.readFile(response.map, (err, contents) => { + if (err !== null) { + callback(err, null); + } else { + response.map = contents; + next(); + } + }); + } + next(); + }); + } catch (e) { + let flags = []; + try { + pushLogFlags(flags, options, {}, isTTY2, transformLogLevelDefault); + } catch { + } + const error = extractErrorMessageV8(e, streamIn, details, void 0, ""); + sendRequest(refs, { command: "error", flags, error }, () => { + error.detail = details.load(error.detail); + callback(failureErrorWithLog("Transform failed", [error], []), null); + }); + } + }; + if ((typeof input === "string" || input instanceof Uint8Array) && input.length > 1024 * 1024) { + let next = start; + start = () => fs3.writeFile(input, next); + } + start(null); + }; + let formatMessages2 = ({ callName, refs, messages, options, callback }) => { + if (!options) throw new Error(`Missing second argument in ${callName}() call`); + let keys = {}; + let kind = getFlag(options, keys, "kind", mustBeString); + let color = getFlag(options, keys, "color", mustBeBoolean); + let terminalWidth = getFlag(options, keys, "terminalWidth", mustBeInteger); + checkForInvalidFlags(options, keys, `in ${callName}() call`); + if (kind === void 0) throw new Error(`Missing "kind" in ${callName}() call`); + if (kind !== "error" && kind !== "warning") throw new Error(`Expected "kind" to be "error" or "warning" in ${callName}() call`); + let request = { + command: "format-msgs", + messages: sanitizeMessages(messages, "messages", null, "", terminalWidth), + isWarning: kind === "warning" + }; + if (color !== void 0) request.color = color; + if (terminalWidth !== void 0) request.terminalWidth = terminalWidth; + sendRequest(refs, request, (error, response) => { + if (error) return callback(new Error(error), null); + callback(null, response.messages); + }); + }; + let analyzeMetafile2 = ({ callName, refs, metafile, options, callback }) => { + if (options === void 0) options = {}; + let keys = {}; + let color = getFlag(options, keys, "color", mustBeBoolean); + let verbose = getFlag(options, keys, "verbose", mustBeBoolean); + checkForInvalidFlags(options, keys, `in ${callName}() call`); + let request = { + command: "analyze-metafile", + metafile + }; + if (color !== void 0) request.color = color; + if (verbose !== void 0) request.verbose = verbose; + sendRequest(refs, request, (error, response) => { + if (error) return callback(new Error(error), null); + callback(null, response.result); + }); + }; + return { + readFromStdout, + afterClose, + service: { + buildOrContext, + transform: transform2, + formatMessages: formatMessages2, + analyzeMetafile: analyzeMetafile2 + } + }; +} +function buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, callback) { + const details = createObjectStash(); + const isContext = callName === "context"; + const handleError = (e, pluginName) => { + const flags = []; + try { + pushLogFlags(flags, options, {}, isTTY2, buildLogLevelDefault); + } catch { + } + const message = extractErrorMessageV8(e, streamIn, details, void 0, pluginName); + sendRequest(refs, { command: "error", flags, error: message }, () => { + message.detail = details.load(message.detail); + callback(failureErrorWithLog(isContext ? "Context failed" : "Build failed", [message], []), null); + }); + }; + let plugins; + if (typeof options === "object") { + const value = options.plugins; + if (value !== void 0) { + if (!Array.isArray(value)) return handleError(new Error(`"plugins" must be an array`), ""); + plugins = value; + } + } + if (plugins && plugins.length > 0) { + if (streamIn.isSync) return handleError(new Error("Cannot use plugins in synchronous API calls"), ""); + handlePlugins( + buildKey, + sendRequest, + sendResponse, + refs, + streamIn, + requestCallbacks, + options, + plugins, + details + ).then( + (result) => { + if (!result.ok) return handleError(result.error, result.pluginName); + try { + buildOrContextContinue(result.requestPlugins, result.runOnEndCallbacks, result.scheduleOnDisposeCallbacks); + } catch (e) { + handleError(e, ""); + } + }, + (e) => handleError(e, "") + ); + return; + } + try { + buildOrContextContinue(null, (result, done) => done([], []), () => { + }); + } catch (e) { + handleError(e, ""); + } + function buildOrContextContinue(requestPlugins, runOnEndCallbacks, scheduleOnDisposeCallbacks) { + const writeDefault = streamIn.hasFS; + const { + entries, + flags, + write, + stdinContents, + stdinResolveDir, + absWorkingDir, + nodePaths, + mangleCache + } = flagsForBuildOptions(callName, options, isTTY2, buildLogLevelDefault, writeDefault); + if (write && !streamIn.hasFS) throw new Error(`The "write" option is unavailable in this environment`); + const request = { + command: "build", + key: buildKey, + entries, + flags, + write, + stdinContents, + stdinResolveDir, + absWorkingDir: absWorkingDir || defaultWD2, + nodePaths, + context: isContext + }; + if (requestPlugins) request.plugins = requestPlugins; + if (mangleCache) request.mangleCache = mangleCache; + const buildResponseToResult = (response, callback2) => { + const result = { + errors: replaceDetailsInMessages(response.errors, details), + warnings: replaceDetailsInMessages(response.warnings, details), + outputFiles: void 0, + metafile: void 0, + mangleCache: void 0 + }; + const originalErrors = result.errors.slice(); + const originalWarnings = result.warnings.slice(); + if (response.outputFiles) result.outputFiles = response.outputFiles.map(convertOutputFiles); + if (response.metafile && response.metafile.length) result.metafile = parseJSON(response.metafile); + if (response.mangleCache) result.mangleCache = response.mangleCache; + if (response.writeToStdout !== void 0) console.log(decodeUTF8(response.writeToStdout).replace(/\n$/, "")); + runOnEndCallbacks(result, (onEndErrors, onEndWarnings) => { + if (originalErrors.length > 0 || onEndErrors.length > 0) { + const error = failureErrorWithLog("Build failed", originalErrors.concat(onEndErrors), originalWarnings.concat(onEndWarnings)); + return callback2(error, null, onEndErrors, onEndWarnings); + } + callback2(null, result, onEndErrors, onEndWarnings); + }); + }; + let latestResultPromise; + let provideLatestResult; + if (isContext) + requestCallbacks["on-end"] = (id, request2) => new Promise((resolve) => { + buildResponseToResult(request2, (err, result, onEndErrors, onEndWarnings) => { + const response = { + errors: onEndErrors, + warnings: onEndWarnings + }; + if (provideLatestResult) provideLatestResult(err, result); + latestResultPromise = void 0; + provideLatestResult = void 0; + sendResponse(id, response); + resolve(); + }); + }); + sendRequest(refs, request, (error, response) => { + if (error) return callback(new Error(error), null); + if (!isContext) { + return buildResponseToResult(response, (err, res) => { + scheduleOnDisposeCallbacks(); + return callback(err, res); + }); + } + if (response.errors.length > 0) { + return callback(failureErrorWithLog("Context failed", response.errors, response.warnings), null); + } + let didDispose = false; + const result = { + rebuild: () => { + if (!latestResultPromise) latestResultPromise = new Promise((resolve, reject) => { + let settlePromise; + provideLatestResult = (err, result2) => { + if (!settlePromise) settlePromise = () => err ? reject(err) : resolve(result2); + }; + const triggerAnotherBuild = () => { + const request2 = { + command: "rebuild", + key: buildKey + }; + sendRequest(refs, request2, (error2, response2) => { + if (error2) { + reject(new Error(error2)); + } else if (settlePromise) { + settlePromise(); + } else { + triggerAnotherBuild(); + } + }); + }; + triggerAnotherBuild(); + }); + return latestResultPromise; + }, + watch: (options2 = {}) => new Promise((resolve, reject) => { + if (!streamIn.hasFS) throw new Error(`Cannot use the "watch" API in this environment`); + const keys = {}; + const delay = getFlag(options2, keys, "delay", mustBeInteger); + checkForInvalidFlags(options2, keys, `in watch() call`); + const request2 = { + command: "watch", + key: buildKey + }; + if (delay) request2.delay = delay; + sendRequest(refs, request2, (error2) => { + if (error2) reject(new Error(error2)); + else resolve(void 0); + }); + }), + serve: (options2 = {}) => new Promise((resolve, reject) => { + if (!streamIn.hasFS) throw new Error(`Cannot use the "serve" API in this environment`); + const keys = {}; + const port = getFlag(options2, keys, "port", mustBeValidPortNumber); + const host = getFlag(options2, keys, "host", mustBeString); + const servedir = getFlag(options2, keys, "servedir", mustBeString); + const keyfile = getFlag(options2, keys, "keyfile", mustBeString); + const certfile = getFlag(options2, keys, "certfile", mustBeString); + const fallback = getFlag(options2, keys, "fallback", mustBeString); + const cors = getFlag(options2, keys, "cors", mustBeObject); + const onRequest = getFlag(options2, keys, "onRequest", mustBeFunction); + checkForInvalidFlags(options2, keys, `in serve() call`); + const request2 = { + command: "serve", + key: buildKey, + onRequest: !!onRequest + }; + if (port !== void 0) request2.port = port; + if (host !== void 0) request2.host = host; + if (servedir !== void 0) request2.servedir = servedir; + if (keyfile !== void 0) request2.keyfile = keyfile; + if (certfile !== void 0) request2.certfile = certfile; + if (fallback !== void 0) request2.fallback = fallback; + if (cors) { + const corsKeys = {}; + const origin = getFlag(cors, corsKeys, "origin", mustBeStringOrArrayOfStrings); + checkForInvalidFlags(cors, corsKeys, `on "cors" object`); + if (Array.isArray(origin)) request2.corsOrigin = origin; + else if (origin !== void 0) request2.corsOrigin = [origin]; + } + sendRequest(refs, request2, (error2, response2) => { + if (error2) return reject(new Error(error2)); + if (onRequest) { + requestCallbacks["serve-request"] = (id, request3) => { + onRequest(request3.args); + sendResponse(id, {}); + }; + } + resolve(response2); + }); + }), + cancel: () => new Promise((resolve) => { + if (didDispose) return resolve(); + const request2 = { + command: "cancel", + key: buildKey + }; + sendRequest(refs, request2, () => { + resolve(); + }); + }), + dispose: () => new Promise((resolve) => { + if (didDispose) return resolve(); + didDispose = true; + const request2 = { + command: "dispose", + key: buildKey + }; + sendRequest(refs, request2, () => { + resolve(); + scheduleOnDisposeCallbacks(); + refs.unref(); + }); + }) + }; + refs.ref(); + callback(null, result); + }); + } +} +var handlePlugins = async (buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, initialOptions, plugins, details) => { + let onStartCallbacks = []; + let onEndCallbacks = []; + let onResolveCallbacks = {}; + let onLoadCallbacks = {}; + let onDisposeCallbacks = []; + let nextCallbackID = 0; + let i = 0; + let requestPlugins = []; + let isSetupDone = false; + plugins = [...plugins]; + for (let item of plugins) { + let keys = {}; + if (typeof item !== "object") throw new Error(`Plugin at index ${i} must be an object`); + const name = getFlag(item, keys, "name", mustBeString); + if (typeof name !== "string" || name === "") throw new Error(`Plugin at index ${i} is missing a name`); + try { + let setup = getFlag(item, keys, "setup", mustBeFunction); + if (typeof setup !== "function") throw new Error(`Plugin is missing a setup function`); + checkForInvalidFlags(item, keys, `on plugin ${quote(name)}`); + let plugin = { + name, + onStart: false, + onEnd: false, + onResolve: [], + onLoad: [] + }; + i++; + let resolve = (path3, options = {}) => { + if (!isSetupDone) throw new Error('Cannot call "resolve" before plugin setup has completed'); + if (typeof path3 !== "string") throw new Error(`The path to resolve must be a string`); + let keys2 = /* @__PURE__ */ Object.create(null); + let pluginName = getFlag(options, keys2, "pluginName", mustBeString); + let importer = getFlag(options, keys2, "importer", mustBeString); + let namespace = getFlag(options, keys2, "namespace", mustBeString); + let resolveDir = getFlag(options, keys2, "resolveDir", mustBeString); + let kind = getFlag(options, keys2, "kind", mustBeString); + let pluginData = getFlag(options, keys2, "pluginData", canBeAnything); + let importAttributes = getFlag(options, keys2, "with", mustBeObject); + checkForInvalidFlags(options, keys2, "in resolve() call"); + return new Promise((resolve2, reject) => { + const request = { + command: "resolve", + path: path3, + key: buildKey, + pluginName: name + }; + if (pluginName != null) request.pluginName = pluginName; + if (importer != null) request.importer = importer; + if (namespace != null) request.namespace = namespace; + if (resolveDir != null) request.resolveDir = resolveDir; + if (kind != null) request.kind = kind; + else throw new Error(`Must specify "kind" when calling "resolve"`); + if (pluginData != null) request.pluginData = details.store(pluginData); + if (importAttributes != null) request.with = sanitizeStringMap(importAttributes, "with"); + sendRequest(refs, request, (error, response) => { + if (error !== null) reject(new Error(error)); + else resolve2({ + errors: replaceDetailsInMessages(response.errors, details), + warnings: replaceDetailsInMessages(response.warnings, details), + path: response.path, + external: response.external, + sideEffects: response.sideEffects, + namespace: response.namespace, + suffix: response.suffix, + pluginData: details.load(response.pluginData) + }); + }); + }); + }; + let promise = setup({ + initialOptions, + resolve, + onStart(callback) { + let registeredText = `This error came from the "onStart" callback registered here:`; + let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onStart"); + onStartCallbacks.push({ name, callback, note: registeredNote }); + plugin.onStart = true; + }, + onEnd(callback) { + let registeredText = `This error came from the "onEnd" callback registered here:`; + let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onEnd"); + onEndCallbacks.push({ name, callback, note: registeredNote }); + plugin.onEnd = true; + }, + onResolve(options, callback) { + let registeredText = `This error came from the "onResolve" callback registered here:`; + let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onResolve"); + let keys2 = {}; + let filter = getFlag(options, keys2, "filter", mustBeRegExp); + let namespace = getFlag(options, keys2, "namespace", mustBeString); + checkForInvalidFlags(options, keys2, `in onResolve() call for plugin ${quote(name)}`); + if (filter == null) throw new Error(`onResolve() call is missing a filter`); + let id = nextCallbackID++; + onResolveCallbacks[id] = { name, callback, note: registeredNote }; + plugin.onResolve.push({ id, filter: jsRegExpToGoRegExp(filter), namespace: namespace || "" }); + }, + onLoad(options, callback) { + let registeredText = `This error came from the "onLoad" callback registered here:`; + let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onLoad"); + let keys2 = {}; + let filter = getFlag(options, keys2, "filter", mustBeRegExp); + let namespace = getFlag(options, keys2, "namespace", mustBeString); + checkForInvalidFlags(options, keys2, `in onLoad() call for plugin ${quote(name)}`); + if (filter == null) throw new Error(`onLoad() call is missing a filter`); + let id = nextCallbackID++; + onLoadCallbacks[id] = { name, callback, note: registeredNote }; + plugin.onLoad.push({ id, filter: jsRegExpToGoRegExp(filter), namespace: namespace || "" }); + }, + onDispose(callback) { + onDisposeCallbacks.push(callback); + }, + esbuild: streamIn.esbuild + }); + if (promise) await promise; + requestPlugins.push(plugin); + } catch (e) { + return { ok: false, error: e, pluginName: name }; + } + } + requestCallbacks["on-start"] = async (id, request) => { + details.clear(); + let response = { errors: [], warnings: [] }; + await Promise.all(onStartCallbacks.map(async ({ name, callback, note }) => { + try { + let result = await callback(); + if (result != null) { + if (typeof result !== "object") throw new Error(`Expected onStart() callback in plugin ${quote(name)} to return an object`); + let keys = {}; + let errors = getFlag(result, keys, "errors", mustBeArray); + let warnings = getFlag(result, keys, "warnings", mustBeArray); + checkForInvalidFlags(result, keys, `from onStart() callback in plugin ${quote(name)}`); + if (errors != null) response.errors.push(...sanitizeMessages(errors, "errors", details, name, void 0)); + if (warnings != null) response.warnings.push(...sanitizeMessages(warnings, "warnings", details, name, void 0)); + } + } catch (e) { + response.errors.push(extractErrorMessageV8(e, streamIn, details, note && note(), name)); + } + })); + sendResponse(id, response); + }; + requestCallbacks["on-resolve"] = async (id, request) => { + let response = {}, name = "", callback, note; + for (let id2 of request.ids) { + try { + ({ name, callback, note } = onResolveCallbacks[id2]); + let result = await callback({ + path: request.path, + importer: request.importer, + namespace: request.namespace, + resolveDir: request.resolveDir, + kind: request.kind, + pluginData: details.load(request.pluginData), + with: request.with + }); + if (result != null) { + if (typeof result !== "object") throw new Error(`Expected onResolve() callback in plugin ${quote(name)} to return an object`); + let keys = {}; + let pluginName = getFlag(result, keys, "pluginName", mustBeString); + let path3 = getFlag(result, keys, "path", mustBeString); + let namespace = getFlag(result, keys, "namespace", mustBeString); + let suffix = getFlag(result, keys, "suffix", mustBeString); + let external = getFlag(result, keys, "external", mustBeBoolean); + let sideEffects = getFlag(result, keys, "sideEffects", mustBeBoolean); + let pluginData = getFlag(result, keys, "pluginData", canBeAnything); + let errors = getFlag(result, keys, "errors", mustBeArray); + let warnings = getFlag(result, keys, "warnings", mustBeArray); + let watchFiles = getFlag(result, keys, "watchFiles", mustBeArrayOfStrings); + let watchDirs = getFlag(result, keys, "watchDirs", mustBeArrayOfStrings); + checkForInvalidFlags(result, keys, `from onResolve() callback in plugin ${quote(name)}`); + response.id = id2; + if (pluginName != null) response.pluginName = pluginName; + if (path3 != null) response.path = path3; + if (namespace != null) response.namespace = namespace; + if (suffix != null) response.suffix = suffix; + if (external != null) response.external = external; + if (sideEffects != null) response.sideEffects = sideEffects; + if (pluginData != null) response.pluginData = details.store(pluginData); + if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0); + if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0); + if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles"); + if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs"); + break; + } + } catch (e) { + response = { id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] }; + break; + } + } + sendResponse(id, response); + }; + requestCallbacks["on-load"] = async (id, request) => { + let response = {}, name = "", callback, note; + for (let id2 of request.ids) { + try { + ({ name, callback, note } = onLoadCallbacks[id2]); + let result = await callback({ + path: request.path, + namespace: request.namespace, + suffix: request.suffix, + pluginData: details.load(request.pluginData), + with: request.with + }); + if (result != null) { + if (typeof result !== "object") throw new Error(`Expected onLoad() callback in plugin ${quote(name)} to return an object`); + let keys = {}; + let pluginName = getFlag(result, keys, "pluginName", mustBeString); + let contents = getFlag(result, keys, "contents", mustBeStringOrUint8Array); + let resolveDir = getFlag(result, keys, "resolveDir", mustBeString); + let pluginData = getFlag(result, keys, "pluginData", canBeAnything); + let loader = getFlag(result, keys, "loader", mustBeString); + let errors = getFlag(result, keys, "errors", mustBeArray); + let warnings = getFlag(result, keys, "warnings", mustBeArray); + let watchFiles = getFlag(result, keys, "watchFiles", mustBeArrayOfStrings); + let watchDirs = getFlag(result, keys, "watchDirs", mustBeArrayOfStrings); + checkForInvalidFlags(result, keys, `from onLoad() callback in plugin ${quote(name)}`); + response.id = id2; + if (pluginName != null) response.pluginName = pluginName; + if (contents instanceof Uint8Array) response.contents = contents; + else if (contents != null) response.contents = encodeUTF8(contents); + if (resolveDir != null) response.resolveDir = resolveDir; + if (pluginData != null) response.pluginData = details.store(pluginData); + if (loader != null) response.loader = loader; + if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0); + if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0); + if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles"); + if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs"); + break; + } + } catch (e) { + response = { id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] }; + break; + } + } + sendResponse(id, response); + }; + let runOnEndCallbacks = (result, done) => done([], []); + if (onEndCallbacks.length > 0) { + runOnEndCallbacks = (result, done) => { + (async () => { + const onEndErrors = []; + const onEndWarnings = []; + for (const { name, callback, note } of onEndCallbacks) { + let newErrors; + let newWarnings; + try { + const value = await callback(result); + if (value != null) { + if (typeof value !== "object") throw new Error(`Expected onEnd() callback in plugin ${quote(name)} to return an object`); + let keys = {}; + let errors = getFlag(value, keys, "errors", mustBeArray); + let warnings = getFlag(value, keys, "warnings", mustBeArray); + checkForInvalidFlags(value, keys, `from onEnd() callback in plugin ${quote(name)}`); + if (errors != null) newErrors = sanitizeMessages(errors, "errors", details, name, void 0); + if (warnings != null) newWarnings = sanitizeMessages(warnings, "warnings", details, name, void 0); + } + } catch (e) { + newErrors = [extractErrorMessageV8(e, streamIn, details, note && note(), name)]; + } + if (newErrors) { + onEndErrors.push(...newErrors); + try { + result.errors.push(...newErrors); + } catch { + } + } + if (newWarnings) { + onEndWarnings.push(...newWarnings); + try { + result.warnings.push(...newWarnings); + } catch { + } + } + } + done(onEndErrors, onEndWarnings); + })(); + }; + } + let scheduleOnDisposeCallbacks = () => { + for (const cb of onDisposeCallbacks) { + setTimeout(() => cb(), 0); + } + }; + isSetupDone = true; + return { + ok: true, + requestPlugins, + runOnEndCallbacks, + scheduleOnDisposeCallbacks + }; +}; +function createObjectStash() { + const map = /* @__PURE__ */ new Map(); + let nextID = 0; + return { + clear() { + map.clear(); + }, + load(id) { + return map.get(id); + }, + store(value) { + if (value === void 0) return -1; + const id = nextID++; + map.set(id, value); + return id; + } + }; +} +function extractCallerV8(e, streamIn, ident) { + let note; + let tried = false; + return () => { + if (tried) return note; + tried = true; + try { + let lines = (e.stack + "").split("\n"); + lines.splice(1, 1); + let location = parseStackLinesV8(streamIn, lines, ident); + if (location) { + note = { text: e.message, location }; + return note; + } + } catch { + } + }; +} +function extractErrorMessageV8(e, streamIn, stash, note, pluginName) { + let text = "Internal error"; + let location = null; + try { + text = (e && e.message || e) + ""; + } catch { + } + try { + location = parseStackLinesV8(streamIn, (e.stack + "").split("\n"), ""); + } catch { + } + return { id: "", pluginName, text, location, notes: note ? [note] : [], detail: stash ? stash.store(e) : -1 }; +} +function parseStackLinesV8(streamIn, lines, ident) { + let at = " at "; + if (streamIn.readFileSync && !lines[0].startsWith(at) && lines[1].startsWith(at)) { + for (let i = 1; i < lines.length; i++) { + let line = lines[i]; + if (!line.startsWith(at)) continue; + line = line.slice(at.length); + while (true) { + let match = /^(?:new |async )?\S+ \((.*)\)$/.exec(line); + if (match) { + line = match[1]; + continue; + } + match = /^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(line); + if (match) { + line = match[1]; + continue; + } + match = /^(\S+):(\d+):(\d+)$/.exec(line); + if (match) { + let contents; + try { + contents = streamIn.readFileSync(match[1], "utf8"); + } catch { + break; + } + let lineText = contents.split(/\r\n|\r|\n|\u2028|\u2029/)[+match[2] - 1] || ""; + let column = +match[3] - 1; + let length = lineText.slice(column, column + ident.length) === ident ? ident.length : 0; + return { + file: match[1], + namespace: "file", + line: +match[2], + column: encodeUTF8(lineText.slice(0, column)).length, + length: encodeUTF8(lineText.slice(column, column + length)).length, + lineText: lineText + "\n" + lines.slice(1).join("\n"), + suggestion: "" + }; + } + break; + } + } + } + return null; +} +function failureErrorWithLog(text, errors, warnings) { + let limit = 5; + text += errors.length < 1 ? "" : ` with ${errors.length} error${errors.length < 2 ? "" : "s"}:` + errors.slice(0, limit + 1).map((e, i) => { + if (i === limit) return "\n..."; + if (!e.location) return ` +error: ${e.text}`; + let { file, line, column } = e.location; + let pluginText = e.pluginName ? `[plugin: ${e.pluginName}] ` : ""; + return ` +${file}:${line}:${column}: ERROR: ${pluginText}${e.text}`; + }).join(""); + let error = new Error(text); + for (const [key, value] of [["errors", errors], ["warnings", warnings]]) { + Object.defineProperty(error, key, { + configurable: true, + enumerable: true, + get: () => value, + set: (value2) => Object.defineProperty(error, key, { + configurable: true, + enumerable: true, + value: value2 + }) + }); + } + return error; +} +function replaceDetailsInMessages(messages, stash) { + for (const message of messages) { + message.detail = stash.load(message.detail); + } + return messages; +} +function sanitizeLocation(location, where, terminalWidth) { + if (location == null) return null; + let keys = {}; + let file = getFlag(location, keys, "file", mustBeString); + let namespace = getFlag(location, keys, "namespace", mustBeString); + let line = getFlag(location, keys, "line", mustBeInteger); + let column = getFlag(location, keys, "column", mustBeInteger); + let length = getFlag(location, keys, "length", mustBeInteger); + let lineText = getFlag(location, keys, "lineText", mustBeString); + let suggestion = getFlag(location, keys, "suggestion", mustBeString); + checkForInvalidFlags(location, keys, where); + if (lineText) { + const relevantASCII = lineText.slice( + 0, + (column && column > 0 ? column : 0) + (length && length > 0 ? length : 0) + (terminalWidth && terminalWidth > 0 ? terminalWidth : 80) + ); + if (!/[\x7F-\uFFFF]/.test(relevantASCII) && !/\n/.test(lineText)) { + lineText = relevantASCII; + } + } + return { + file: file || "", + namespace: namespace || "", + line: line || 0, + column: column || 0, + length: length || 0, + lineText: lineText || "", + suggestion: suggestion || "" + }; +} +function sanitizeMessages(messages, property, stash, fallbackPluginName, terminalWidth) { + let messagesClone = []; + let index = 0; + for (const message of messages) { + let keys = {}; + let id = getFlag(message, keys, "id", mustBeString); + let pluginName = getFlag(message, keys, "pluginName", mustBeString); + let text = getFlag(message, keys, "text", mustBeString); + let location = getFlag(message, keys, "location", mustBeObjectOrNull); + let notes = getFlag(message, keys, "notes", mustBeArray); + let detail = getFlag(message, keys, "detail", canBeAnything); + let where = `in element ${index} of "${property}"`; + checkForInvalidFlags(message, keys, where); + let notesClone = []; + if (notes) { + for (const note of notes) { + let noteKeys = {}; + let noteText = getFlag(note, noteKeys, "text", mustBeString); + let noteLocation = getFlag(note, noteKeys, "location", mustBeObjectOrNull); + checkForInvalidFlags(note, noteKeys, where); + notesClone.push({ + text: noteText || "", + location: sanitizeLocation(noteLocation, where, terminalWidth) + }); + } + } + messagesClone.push({ + id: id || "", + pluginName: pluginName || fallbackPluginName, + text: text || "", + location: sanitizeLocation(location, where, terminalWidth), + notes: notesClone, + detail: stash ? stash.store(detail) : -1 + }); + index++; + } + return messagesClone; +} +function sanitizeStringArray(values, property) { + const result = []; + for (const value of values) { + if (typeof value !== "string") throw new Error(`${quote(property)} must be an array of strings`); + result.push(value); + } + return result; +} +function sanitizeStringMap(map, property) { + const result = /* @__PURE__ */ Object.create(null); + for (const key in map) { + const value = map[key]; + if (typeof value !== "string") throw new Error(`key ${quote(key)} in object ${quote(property)} must be a string`); + result[key] = value; + } + return result; +} +function convertOutputFiles({ path: path3, contents, hash }) { + let text = null; + return { + path: path3, + contents, + hash, + get text() { + const binary = this.contents; + if (text === null || binary !== contents) { + contents = binary; + text = decodeUTF8(binary); + } + return text; + } + }; +} +function jsRegExpToGoRegExp(regexp) { + let result = regexp.source; + if (regexp.flags) result = `(?${regexp.flags})${result}`; + return result; +} +function parseJSON(bytes) { + let text; + try { + text = decodeUTF8(bytes); + } catch { + return JSON_parse(bytes); + } + return JSON.parse(text); +} + +// lib/npm/node-platform.ts +var fs = require("fs"); +var os = require("os"); +var path = require("path"); +var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH; +var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild"; +var packageDarwin_arm64 = "@esbuild/darwin-arm64"; +var packageDarwin_x64 = "@esbuild/darwin-x64"; +var knownWindowsPackages = { + "win32 arm64 LE": "@esbuild/win32-arm64", + "win32 ia32 LE": "@esbuild/win32-ia32", + "win32 x64 LE": "@esbuild/win32-x64" +}; +var knownUnixlikePackages = { + "aix ppc64 BE": "@esbuild/aix-ppc64", + "android arm64 LE": "@esbuild/android-arm64", + "darwin arm64 LE": "@esbuild/darwin-arm64", + "darwin x64 LE": "@esbuild/darwin-x64", + "freebsd arm64 LE": "@esbuild/freebsd-arm64", + "freebsd x64 LE": "@esbuild/freebsd-x64", + "linux arm LE": "@esbuild/linux-arm", + "linux arm64 LE": "@esbuild/linux-arm64", + "linux ia32 LE": "@esbuild/linux-ia32", + "linux mips64el LE": "@esbuild/linux-mips64el", + "linux ppc64 LE": "@esbuild/linux-ppc64", + "linux riscv64 LE": "@esbuild/linux-riscv64", + "linux s390x BE": "@esbuild/linux-s390x", + "linux x64 LE": "@esbuild/linux-x64", + "linux loong64 LE": "@esbuild/linux-loong64", + "netbsd arm64 LE": "@esbuild/netbsd-arm64", + "netbsd x64 LE": "@esbuild/netbsd-x64", + "openbsd arm64 LE": "@esbuild/openbsd-arm64", + "openbsd x64 LE": "@esbuild/openbsd-x64", + "sunos x64 LE": "@esbuild/sunos-x64" +}; +var knownWebAssemblyFallbackPackages = { + "android arm LE": "@esbuild/android-arm", + "android x64 LE": "@esbuild/android-x64", + "openharmony arm64 LE": "@esbuild/openharmony-arm64" +}; +function pkgAndSubpathForCurrentPlatform() { + let pkg; + let subpath; + let isWASM = false; + let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`; + if (platformKey in knownWindowsPackages) { + pkg = knownWindowsPackages[platformKey]; + subpath = "esbuild.exe"; + } else if (platformKey in knownUnixlikePackages) { + pkg = knownUnixlikePackages[platformKey]; + subpath = "bin/esbuild"; + } else if (platformKey in knownWebAssemblyFallbackPackages) { + pkg = knownWebAssemblyFallbackPackages[platformKey]; + subpath = "bin/esbuild"; + isWASM = true; + } else { + throw new Error(`Unsupported platform: ${platformKey}`); + } + return { pkg, subpath, isWASM }; +} +function pkgForSomeOtherPlatform() { + const libMainJS = require.resolve("esbuild"); + const nodeModulesDirectory = path.dirname(path.dirname(path.dirname(libMainJS))); + if (path.basename(nodeModulesDirectory) === "node_modules") { + for (const unixKey in knownUnixlikePackages) { + try { + const pkg = knownUnixlikePackages[unixKey]; + if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg; + } catch { + } + } + for (const windowsKey in knownWindowsPackages) { + try { + const pkg = knownWindowsPackages[windowsKey]; + if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg; + } catch { + } + } + } + return null; +} +function downloadedBinPath(pkg, subpath) { + const esbuildLibDir = path.dirname(require.resolve("esbuild")); + return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`); +} +function generateBinPath() { + if (isValidBinaryPath(ESBUILD_BINARY_PATH)) { + if (!fs.existsSync(ESBUILD_BINARY_PATH)) { + console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`); + } else { + return { binPath: ESBUILD_BINARY_PATH, isWASM: false }; + } + } + const { pkg, subpath, isWASM } = pkgAndSubpathForCurrentPlatform(); + let binPath; + try { + binPath = require.resolve(`${pkg}/${subpath}`); + } catch (e) { + binPath = downloadedBinPath(pkg, subpath); + if (!fs.existsSync(binPath)) { + try { + require.resolve(pkg); + } catch { + const otherPkg = pkgForSomeOtherPlatform(); + if (otherPkg) { + let suggestions = ` +Specifically the "${otherPkg}" package is present but this platform +needs the "${pkg}" package instead. People often get into this +situation by installing esbuild on Windows or macOS and copying "node_modules" +into a Docker image that runs Linux, or by copying "node_modules" between +Windows and WSL environments. + +If you are installing with npm, you can try not copying the "node_modules" +directory when you copy the files over, and running "npm ci" or "npm install" +on the destination platform after the copy. Or you could consider using yarn +instead of npm which has built-in support for installing a package on multiple +platforms simultaneously. + +If you are installing with yarn, you can try listing both this platform and the +other platform in your ".yarnrc.yml" file using the "supportedArchitectures" +feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures +Keep in mind that this means multiple copies of esbuild will be present. +`; + if (pkg === packageDarwin_x64 && otherPkg === packageDarwin_arm64 || pkg === packageDarwin_arm64 && otherPkg === packageDarwin_x64) { + suggestions = ` +Specifically the "${otherPkg}" package is present but this platform +needs the "${pkg}" package instead. People often get into this +situation by installing esbuild with npm running inside of Rosetta 2 and then +trying to use it with node running outside of Rosetta 2, or vice versa (Rosetta +2 is Apple's on-the-fly x86_64-to-arm64 translation service). + +If you are installing with npm, you can try ensuring that both npm and node are +not running under Rosetta 2 and then reinstalling esbuild. This likely involves +changing how you installed npm and/or node. For example, installing node with +the universal installer here should work: https://nodejs.org/en/download/. Or +you could consider using yarn instead of npm which has built-in support for +installing a package on multiple platforms simultaneously. + +If you are installing with yarn, you can try listing both "arm64" and "x64" +in your ".yarnrc.yml" file using the "supportedArchitectures" feature: +https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures +Keep in mind that this means multiple copies of esbuild will be present. +`; + } + throw new Error(` +You installed esbuild for another platform than the one you're currently using. +This won't work because esbuild is written with native code and needs to +install a platform-specific binary executable. +${suggestions} +Another alternative is to use the "esbuild-wasm" package instead, which works +the same way on all platforms. But it comes with a heavy performance cost and +can sometimes be 10x slower than the "esbuild" package, so you may also not +want to do that. +`); + } + throw new Error(`The package "${pkg}" could not be found, and is needed by esbuild. + +If you are installing esbuild with npm, make sure that you don't specify the +"--no-optional" or "--omit=optional" flags. The "optionalDependencies" feature +of "package.json" is used by esbuild to install the correct binary executable +for your current platform.`); + } + throw e; + } + } + if (/\.zip\//.test(binPath)) { + let pnpapi; + try { + pnpapi = require("pnpapi"); + } catch (e) { + } + if (pnpapi) { + const root = pnpapi.getPackageInformation(pnpapi.topLevel).packageLocation; + const binTargetPath = path.join( + root, + "node_modules", + ".cache", + "esbuild", + `pnpapi-${pkg.replace("/", "-")}-${"0.28.1"}-${path.basename(subpath)}` + ); + if (!fs.existsSync(binTargetPath)) { + fs.mkdirSync(path.dirname(binTargetPath), { recursive: true }); + fs.copyFileSync(binPath, binTargetPath); + fs.chmodSync(binTargetPath, 493); + } + return { binPath: binTargetPath, isWASM }; + } + } + return { binPath, isWASM }; +} + +// lib/npm/node.ts +var child_process = require("child_process"); +var crypto = require("crypto"); +var path2 = require("path"); +var fs2 = require("fs"); +var os2 = require("os"); +var tty = require("tty"); +var worker_threads; +if (process.env.ESBUILD_WORKER_THREADS !== "0") { + try { + worker_threads = require("worker_threads"); + } catch { + } + let [major, minor] = process.versions.node.split("."); + if ( + // { + if ((!ESBUILD_BINARY_PATH || false) && (path2.basename(__filename) !== "main.js" || path2.basename(__dirname) !== "lib")) { + throw new Error( + `The esbuild JavaScript API cannot be bundled. Please mark the "esbuild" package as external so it's not included in the bundle. + +More information: The file containing the code for esbuild's JavaScript API (${__filename}) does not appear to be inside the esbuild package on the file system, which usually means that the esbuild package was bundled into another file. This is problematic because the API needs to run a binary executable inside the esbuild package which is located using a relative path from the API code to the executable. If the esbuild package is bundled, the relative path will be incorrect and the executable won't be found.` + ); + } + if (false) { + return ["node", [path2.join(__dirname, "..", "bin", "esbuild")]]; + } else { + const { binPath, isWASM } = generateBinPath(); + if (isWASM) { + return ["node", [binPath]]; + } else { + return [binPath, []]; + } + } +}; +var isTTY = () => tty.isatty(2); +var fsSync = { + readFile(tempFile, callback) { + try { + let contents = fs2.readFileSync(tempFile, "utf8"); + try { + fs2.unlinkSync(tempFile); + } catch { + } + callback(null, contents); + } catch (err) { + callback(err, null); + } + }, + writeFile(contents, callback) { + try { + let tempFile = randomFileName(); + fs2.writeFileSync(tempFile, contents); + callback(tempFile); + } catch { + callback(null); + } + } +}; +var fsAsync = { + readFile(tempFile, callback) { + try { + fs2.readFile(tempFile, "utf8", (err, contents) => { + try { + fs2.unlink(tempFile, () => callback(err, contents)); + } catch { + callback(err, contents); + } + }); + } catch (err) { + callback(err, null); + } + }, + writeFile(contents, callback) { + try { + let tempFile = randomFileName(); + fs2.writeFile(tempFile, contents, (err) => err !== null ? callback(null) : callback(tempFile)); + } catch { + callback(null); + } + } +}; +var version = "0.28.1"; +var build = (options) => ensureServiceIsRunning().build(options); +var context = (buildOptions) => ensureServiceIsRunning().context(buildOptions); +var transform = (input, options) => ensureServiceIsRunning().transform(input, options); +var formatMessages = (messages, options) => ensureServiceIsRunning().formatMessages(messages, options); +var analyzeMetafile = (messages, options) => ensureServiceIsRunning().analyzeMetafile(messages, options); +var buildSync = (options) => { + if (worker_threads && !isInternalWorkerThread) { + if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads); + return workerThreadService.buildSync(options); + } + let result; + runServiceSync((service) => service.buildOrContext({ + callName: "buildSync", + refs: null, + options, + isTTY: isTTY(), + defaultWD, + callback: (err, res) => { + if (err) throw err; + result = res; + } + })); + return result; +}; +var transformSync = (input, options) => { + if (worker_threads && !isInternalWorkerThread) { + if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads); + return workerThreadService.transformSync(input, options); + } + let result; + runServiceSync((service) => service.transform({ + callName: "transformSync", + refs: null, + input, + options: options || {}, + isTTY: isTTY(), + fs: fsSync, + callback: (err, res) => { + if (err) throw err; + result = res; + } + })); + return result; +}; +var formatMessagesSync = (messages, options) => { + if (worker_threads && !isInternalWorkerThread) { + if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads); + return workerThreadService.formatMessagesSync(messages, options); + } + let result; + runServiceSync((service) => service.formatMessages({ + callName: "formatMessagesSync", + refs: null, + messages, + options, + callback: (err, res) => { + if (err) throw err; + result = res; + } + })); + return result; +}; +var analyzeMetafileSync = (metafile, options) => { + if (worker_threads && !isInternalWorkerThread) { + if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads); + return workerThreadService.analyzeMetafileSync(metafile, options); + } + let result; + runServiceSync((service) => service.analyzeMetafile({ + callName: "analyzeMetafileSync", + refs: null, + metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile), + options, + callback: (err, res) => { + if (err) throw err; + result = res; + } + })); + return result; +}; +var stop = () => { + if (stopService) stopService(); + if (workerThreadService) workerThreadService.stop(); + return Promise.resolve(); +}; +var initializeWasCalled = false; +var initialize = (options) => { + options = validateInitializeOptions(options || {}); + if (options.wasmURL) throw new Error(`The "wasmURL" option only works in the browser`); + if (options.wasmModule) throw new Error(`The "wasmModule" option only works in the browser`); + if (options.worker) throw new Error(`The "worker" option only works in the browser`); + if (initializeWasCalled) throw new Error('Cannot call "initialize" more than once'); + ensureServiceIsRunning(); + initializeWasCalled = true; + return Promise.resolve(); +}; +var defaultWD = process.cwd(); +var longLivedService; +var stopService; +var ensureServiceIsRunning = () => { + if (longLivedService) return longLivedService; + let [command, args] = esbuildCommandAndArgs(); + let child = child_process.spawn(command, args.concat(`--service=${"0.28.1"}`, "--ping"), { + windowsHide: true, + stdio: ["pipe", "pipe", "inherit"], + cwd: defaultWD + }); + let { readFromStdout, afterClose, service } = createChannel({ + writeToStdin(bytes) { + child.stdin.write(bytes, (err) => { + if (err) afterClose(err); + }); + }, + readFileSync: fs2.readFileSync, + isSync: false, + hasFS: true, + esbuild: node_exports + }); + child.stdin.on("error", afterClose); + child.on("error", afterClose); + const stdin = child.stdin; + const stdout = child.stdout; + stdout.on("data", readFromStdout); + stdout.on("end", afterClose); + stopService = () => { + stdin.destroy(); + stdout.destroy(); + child.kill(); + initializeWasCalled = false; + longLivedService = void 0; + stopService = void 0; + }; + let refCount = 0; + child.unref(); + if (stdin.unref) { + stdin.unref(); + } + if (stdout.unref) { + stdout.unref(); + } + const refs = { + ref() { + if (++refCount === 1) child.ref(); + }, + unref() { + if (--refCount === 0) child.unref(); + } + }; + longLivedService = { + build: (options) => new Promise((resolve, reject) => { + service.buildOrContext({ + callName: "build", + refs, + options, + isTTY: isTTY(), + defaultWD, + callback: (err, res) => err ? reject(err) : resolve(res) + }); + }), + context: (options) => new Promise((resolve, reject) => service.buildOrContext({ + callName: "context", + refs, + options, + isTTY: isTTY(), + defaultWD, + callback: (err, res) => err ? reject(err) : resolve(res) + })), + transform: (input, options) => new Promise((resolve, reject) => service.transform({ + callName: "transform", + refs, + input, + options: options || {}, + isTTY: isTTY(), + fs: fsAsync, + callback: (err, res) => err ? reject(err) : resolve(res) + })), + formatMessages: (messages, options) => new Promise((resolve, reject) => service.formatMessages({ + callName: "formatMessages", + refs, + messages, + options, + callback: (err, res) => err ? reject(err) : resolve(res) + })), + analyzeMetafile: (metafile, options) => new Promise((resolve, reject) => service.analyzeMetafile({ + callName: "analyzeMetafile", + refs, + metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile), + options, + callback: (err, res) => err ? reject(err) : resolve(res) + })) + }; + return longLivedService; +}; +var runServiceSync = (callback) => { + let [command, args] = esbuildCommandAndArgs(); + let stdin = new Uint8Array(); + let { readFromStdout, afterClose, service } = createChannel({ + writeToStdin(bytes) { + if (stdin.length !== 0) throw new Error("Must run at most one command"); + stdin = bytes; + }, + isSync: true, + hasFS: true, + esbuild: node_exports + }); + callback(service); + let stdout = child_process.execFileSync(command, args.concat(`--service=${"0.28.1"}`), { + cwd: defaultWD, + windowsHide: true, + input: stdin, + // We don't know how large the output could be. If it's too large, the + // command will fail with ENOBUFS. Reserve 16mb for now since that feels + // like it should be enough. Also allow overriding this with an environment + // variable. + maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16 * 1024 * 1024 + }); + readFromStdout(stdout); + afterClose(null); +}; +var randomFileName = () => { + return path2.join(os2.tmpdir(), `esbuild-${crypto.randomBytes(32).toString("hex")}`); +}; +var workerThreadService = null; +var startWorkerThreadService = (worker_threads2) => { + let { port1: mainPort, port2: workerPort } = new worker_threads2.MessageChannel(); + let worker = new worker_threads2.Worker(__filename, { + workerData: { workerPort, defaultWD, esbuildVersion: "0.28.1" }, + transferList: [workerPort], + // From node's documentation: https://nodejs.org/api/worker_threads.html + // + // Take care when launching worker threads from preload scripts (scripts loaded + // and run using the `-r` command line flag). Unless the `execArgv` option is + // explicitly set, new Worker threads automatically inherit the command line flags + // from the running process and will preload the same preload scripts as the main + // thread. If the preload script unconditionally launches a worker thread, every + // thread spawned will spawn another until the application crashes. + // + execArgv: [] + }); + let nextID = 0; + let fakeBuildError = (text) => { + let error = new Error(`Build failed with 1 error: +error: ${text}`); + let errors = [{ id: "", pluginName: "", text, location: null, notes: [], detail: void 0 }]; + error.errors = errors; + error.warnings = []; + return error; + }; + let validateBuildSyncOptions = (options) => { + if (!options) return; + let plugins = options.plugins; + if (plugins && plugins.length > 0) throw fakeBuildError(`Cannot use plugins in synchronous API calls`); + }; + let applyProperties = (object, properties) => { + for (let key in properties) { + object[key] = properties[key]; + } + }; + let runCallSync = (command, args) => { + let id = nextID++; + let sharedBuffer = new SharedArrayBuffer(8); + let sharedBufferView = new Int32Array(sharedBuffer); + let msg = { sharedBuffer, id, command, args }; + worker.postMessage(msg); + let status = Atomics.wait(sharedBufferView, 0, 0); + if (status !== "ok" && status !== "not-equal") throw new Error("Internal error: Atomics.wait() failed: " + status); + let { message: { id: id2, resolve, reject, properties } } = worker_threads2.receiveMessageOnPort(mainPort); + if (id !== id2) throw new Error(`Internal error: Expected id ${id} but got id ${id2}`); + if (reject) { + applyProperties(reject, properties); + throw reject; + } + return resolve; + }; + worker.unref(); + return { + buildSync(options) { + validateBuildSyncOptions(options); + return runCallSync("build", [options]); + }, + transformSync(input, options) { + return runCallSync("transform", [input, options]); + }, + formatMessagesSync(messages, options) { + return runCallSync("formatMessages", [messages, options]); + }, + analyzeMetafileSync(metafile, options) { + return runCallSync("analyzeMetafile", [metafile, options]); + }, + stop() { + worker.terminate(); + workerThreadService = null; + } + }; +}; +var startSyncServiceWorker = () => { + let workerPort = worker_threads.workerData.workerPort; + let parentPort = worker_threads.parentPort; + let extractProperties = (object) => { + let properties = {}; + if (object && typeof object === "object") { + for (let key in object) { + properties[key] = object[key]; + } + } + return properties; + }; + try { + let service = ensureServiceIsRunning(); + defaultWD = worker_threads.workerData.defaultWD; + parentPort.on("message", (msg) => { + (async () => { + let { sharedBuffer, id, command, args } = msg; + let sharedBufferView = new Int32Array(sharedBuffer); + try { + switch (command) { + case "build": + workerPort.postMessage({ id, resolve: await service.build(args[0]) }); + break; + case "transform": + workerPort.postMessage({ id, resolve: await service.transform(args[0], args[1]) }); + break; + case "formatMessages": + workerPort.postMessage({ id, resolve: await service.formatMessages(args[0], args[1]) }); + break; + case "analyzeMetafile": + workerPort.postMessage({ id, resolve: await service.analyzeMetafile(args[0], args[1]) }); + break; + default: + throw new Error(`Invalid command: ${command}`); + } + } catch (reject) { + workerPort.postMessage({ id, reject, properties: extractProperties(reject) }); + } + Atomics.add(sharedBufferView, 0, 1); + Atomics.notify(sharedBufferView, 0, Infinity); + })(); + }); + } catch (reject) { + parentPort.on("message", (msg) => { + let { sharedBuffer, id } = msg; + let sharedBufferView = new Int32Array(sharedBuffer); + workerPort.postMessage({ id, reject, properties: extractProperties(reject) }); + Atomics.add(sharedBufferView, 0, 1); + Atomics.notify(sharedBufferView, 0, Infinity); + }); + } +}; +if (isInternalWorkerThread) { + startSyncServiceWorker(); +} +var node_default = node_exports; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + analyzeMetafile, + analyzeMetafileSync, + build, + buildSync, + context, + formatMessages, + formatMessagesSync, + initialize, + stop, + transform, + transformSync, + version +}); diff --git a/tools/ui/node_modules/esbuild/package.json b/tools/ui/node_modules/esbuild/package.json new file mode 100644 index 0000000000000000000000000000000000000000..628583884bffe38c662c1806c474c22009d9bafa --- /dev/null +++ b/tools/ui/node_modules/esbuild/package.json @@ -0,0 +1,74 @@ +{ + "name": "esbuild", + "version": "0.28.1", + "description": "An extremely fast JavaScript and CSS bundler and minifier.", + "repository": { + "type": "git", + "url": "git+https://github.com/evanw/esbuild.git" + }, + "scripts": { + "postinstall": "node install.js" + }, + "main": "lib/main.js", + "types": "lib/main.d.ts", + "engines": { + "node": ">=18" + }, + "bin": { + "esbuild": "bin/esbuild" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.1", + "@esbuild/android-arm": "0.28.1", + "@esbuild/android-arm64": "0.28.1", + "@esbuild/android-x64": "0.28.1", + "@esbuild/darwin-arm64": "0.28.1", + "@esbuild/darwin-x64": "0.28.1", + "@esbuild/freebsd-arm64": "0.28.1", + "@esbuild/freebsd-x64": "0.28.1", + "@esbuild/linux-arm": "0.28.1", + "@esbuild/linux-arm64": "0.28.1", + "@esbuild/linux-ia32": "0.28.1", + "@esbuild/linux-loong64": "0.28.1", + "@esbuild/linux-mips64el": "0.28.1", + "@esbuild/linux-ppc64": "0.28.1", + "@esbuild/linux-riscv64": "0.28.1", + "@esbuild/linux-s390x": "0.28.1", + "@esbuild/linux-x64": "0.28.1", + "@esbuild/netbsd-arm64": "0.28.1", + "@esbuild/netbsd-x64": "0.28.1", + "@esbuild/openbsd-arm64": "0.28.1", + "@esbuild/openbsd-x64": "0.28.1", + "@esbuild/openharmony-arm64": "0.28.1", + "@esbuild/sunos-x64": "0.28.1", + "@esbuild/win32-arm64": "0.28.1", + "@esbuild/win32-ia32": "0.28.1", + "@esbuild/win32-x64": "0.28.1" + }, + "license": "MIT", + "esbuild.binaryHashes": { + "@esbuild/aix-ppc64/bin/esbuild": "0dd860154344f94b7a9367e64ffc2bc5b89a4313b4a399e5127cdc4ff5000303", + "@esbuild/android-arm64/bin/esbuild": "087671da02d323e7915fafc13567c0929192633ed544bd8adee9bc020fddf5b4", + "@esbuild/darwin-arm64/bin/esbuild": "e2dc9a52440a2a34f09434a2f4843cb1e30f84e40dcf238976ec61ef8cd7f36a", + "@esbuild/darwin-x64/bin/esbuild": "dd53ccf32f9b5b3ab30d41388ef1fc8f81c44ca57ee7a32a7364a1753308d009", + "@esbuild/freebsd-arm64/bin/esbuild": "5fef5a5ef24d9660d7711b756be5ddeba1fb3ca8dd62d703682ebb9fab3b68b0", + "@esbuild/freebsd-x64/bin/esbuild": "4427a8cbfa0661943ccfef2606a65b35f3411ac73e447e86f7732aace61e4609", + "@esbuild/linux-arm/bin/esbuild": "a2d93f7a8b1c9f91d47beec987888b4765c890501b6274f4bdff4061a5e0d9fd", + "@esbuild/linux-arm64/bin/esbuild": "51e829ba36f36be6d9aea6e329ddc4f9350302339b16aaca96a3cb97f64a8ebb", + "@esbuild/linux-ia32/bin/esbuild": "9cd7515a75d6f96b0aa055861cf987498315428088cd6d18de5082f904ae5794", + "@esbuild/linux-loong64/bin/esbuild": "73fa76af9b13f7a27fdb20673b8c2af927fe1511d14e51edeb4b7b71f7f03d0e", + "@esbuild/linux-mips64el/bin/esbuild": "d734787abc3c99d95242805047fe32da85a5822f04bf33d766a966bf5fd85488", + "@esbuild/linux-ppc64/bin/esbuild": "90709144617c2adf8f6c14937f03b114c259de0b9309666e3a9d89a1fb266d04", + "@esbuild/linux-riscv64/bin/esbuild": "86df35a46bedde8b756edb6565a1df7b5a832ad74dd0e179608cbf6509a2582a", + "@esbuild/linux-s390x/bin/esbuild": "f8cad0db35132e5ac3065c4345c36e7ffe18fdc98417a61bcf5a95a6c694e57c", + "@esbuild/linux-x64/bin/esbuild": "0c6588b092a2c291a72bab90659f3c9e0e25e0fe59c9ac12b4dae4d945e5548c", + "@esbuild/netbsd-arm64/bin/esbuild": "490cfdac2d96d5608d91cf55bdf4052bbde7013dafe87ec7adc7784778ad4d4c", + "@esbuild/netbsd-x64/bin/esbuild": "c61e0e4c553a4986fd0e9d63a0425e93be831ff7b13bfb8a564368fb7590f85d", + "@esbuild/openbsd-arm64/bin/esbuild": "f9d814698e26c09c3f90d4c103cbdf3832c9f2c841d64a93889d63d23da9b8cf", + "@esbuild/openbsd-x64/bin/esbuild": "2e30dce11f7236aa362c1c57212cc696f51472169aa417f30e9b641f3b7dcade", + "@esbuild/sunos-x64/bin/esbuild": "770e0d2bc930b1a1d19d3f43243ff8f393efddb599e7f5843160feacd253267d", + "@esbuild/win32-arm64/esbuild.exe": "bfb8798ab678f1ce4a723739f4a3eabab3244d7a04eeb12be2eb9f58095c13ef", + "@esbuild/win32-ia32/esbuild.exe": "8fa99b6e0945830fce8d7e208fdb21763aa4aea875751f4a0eec7f6e262af1dd", + "@esbuild/win32-x64/esbuild.exe": "ec02ee9b14ab332416fedd10614dfb80eed5304d94f67745067c011934a8c3c3" + } +} diff --git a/tools/ui/node_modules/escalade/dist/index.js b/tools/ui/node_modules/escalade/dist/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ad236c492050394ade5d7d3d1749e5bcfcc8542b --- /dev/null +++ b/tools/ui/node_modules/escalade/dist/index.js @@ -0,0 +1,22 @@ +const { dirname, resolve } = require('path'); +const { readdir, stat } = require('fs'); +const { promisify } = require('util'); + +const toStats = promisify(stat); +const toRead = promisify(readdir); + +module.exports = async function (start, callback) { + let dir = resolve('.', start); + let tmp, stats = await toStats(dir); + + if (!stats.isDirectory()) { + dir = dirname(dir); + } + + while (true) { + tmp = await callback(dir, await toRead(dir)); + if (tmp) return resolve(dir, tmp); + dir = dirname(tmp = dir); + if (tmp === dir) break; + } +} diff --git a/tools/ui/node_modules/escalade/dist/index.mjs b/tools/ui/node_modules/escalade/dist/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..bf95be03425c909cd4aaef11fdb7ac6fe31e2dd3 --- /dev/null +++ b/tools/ui/node_modules/escalade/dist/index.mjs @@ -0,0 +1,22 @@ +import { dirname, resolve } from 'path'; +import { readdir, stat } from 'fs'; +import { promisify } from 'util'; + +const toStats = promisify(stat); +const toRead = promisify(readdir); + +export default async function (start, callback) { + let dir = resolve('.', start); + let tmp, stats = await toStats(dir); + + if (!stats.isDirectory()) { + dir = dirname(dir); + } + + while (true) { + tmp = await callback(dir, await toRead(dir)); + if (tmp) return resolve(dir, tmp); + dir = dirname(tmp = dir); + if (tmp === dir) break; + } +} diff --git a/tools/ui/node_modules/escalade/index.d.mts b/tools/ui/node_modules/escalade/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..550699cf98e1c9b4de9b01128d072c1d8f6bd7e0 --- /dev/null +++ b/tools/ui/node_modules/escalade/index.d.mts @@ -0,0 +1,11 @@ +type Promisable = T | Promise; + +export type Callback = ( + directory: string, + files: string[], +) => Promisable; + +export default function ( + directory: string, + callback: Callback, +): Promise; diff --git a/tools/ui/node_modules/escalade/index.d.ts b/tools/ui/node_modules/escalade/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..26c58f2f3165162e35bf72c190d4c70955dbc9ec --- /dev/null +++ b/tools/ui/node_modules/escalade/index.d.ts @@ -0,0 +1,15 @@ +type Promisable = T | Promise; + +declare namespace escalade { + export type Callback = ( + directory: string, + files: string[], + ) => Promisable; +} + +declare function escalade( + directory: string, + callback: escalade.Callback, +): Promise; + +export = escalade; diff --git a/tools/ui/node_modules/escalade/license b/tools/ui/node_modules/escalade/license new file mode 100644 index 0000000000000000000000000000000000000000..fa6089faba3cf381229744c9f21ed3ae9ed5014a --- /dev/null +++ b/tools/ui/node_modules/escalade/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Luke Edwards (lukeed.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tools/ui/node_modules/escalade/package.json b/tools/ui/node_modules/escalade/package.json new file mode 100644 index 0000000000000000000000000000000000000000..1eed4f93a81e8d9c613bb36e2bf6840472c31ade --- /dev/null +++ b/tools/ui/node_modules/escalade/package.json @@ -0,0 +1,74 @@ +{ + "name": "escalade", + "version": "3.2.0", + "repository": "lukeed/escalade", + "description": "A tiny (183B to 210B) and fast utility to ascend parent directories", + "module": "dist/index.mjs", + "main": "dist/index.js", + "types": "index.d.ts", + "license": "MIT", + "author": { + "name": "Luke Edwards", + "email": "luke.edwards05@gmail.com", + "url": "https://lukeed.com" + }, + "exports": { + ".": [ + { + "import": { + "types": "./index.d.mts", + "default": "./dist/index.mjs" + }, + "require": { + "types": "./index.d.ts", + "default": "./dist/index.js" + } + }, + "./dist/index.js" + ], + "./sync": [ + { + "import": { + "types": "./sync/index.d.mts", + "default": "./sync/index.mjs" + }, + "require": { + "types": "./sync/index.d.ts", + "default": "./sync/index.js" + } + }, + "./sync/index.js" + ] + }, + "files": [ + "*.d.mts", + "*.d.ts", + "dist", + "sync" + ], + "modes": { + "sync": "src/sync.js", + "default": "src/async.js" + }, + "engines": { + "node": ">=6" + }, + "scripts": { + "build": "bundt", + "pretest": "npm run build", + "test": "uvu -r esm test -i fixtures" + }, + "keywords": [ + "find", + "parent", + "parents", + "directory", + "search", + "walk" + ], + "devDependencies": { + "bundt": "1.1.1", + "esm": "3.2.25", + "uvu": "0.3.3" + } +} diff --git a/tools/ui/node_modules/escalade/readme.md b/tools/ui/node_modules/escalade/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..e07ee0d387a9e5531d4bfa596272ed7b7c8ce124 --- /dev/null +++ b/tools/ui/node_modules/escalade/readme.md @@ -0,0 +1,211 @@ +# escalade [![CI](https://github.com/lukeed/escalade/workflows/CI/badge.svg)](https://github.com/lukeed/escalade/actions) [![licenses](https://licenses.dev/b/npm/escalade)](https://licenses.dev/npm/escalade) [![codecov](https://badgen.now.sh/codecov/c/github/lukeed/escalade)](https://codecov.io/gh/lukeed/escalade) + +> A tiny (183B to 210B) and [fast](#benchmarks) utility to ascend parent directories + +With [escalade](https://en.wikipedia.org/wiki/Escalade), you can scale parent directories until you've found what you're looking for.
Given an input file or directory, `escalade` will continue executing your callback function until either: + +1) the callback returns a truthy value +2) `escalade` has reached the system root directory (eg, `/`) + +> **Important:**
Please note that `escalade` only deals with direct ancestry – it will not dive into parents' sibling directories. + +--- + +**Notice:** As of v3.1.0, `escalade` now includes [Deno support](http://deno.land/x/escalade)! Please see [Deno Usage](#deno) below. + +--- + +## Install + +``` +$ npm install --save escalade +``` + + +## Modes + +There are two "versions" of `escalade` available: + +#### "async" +> **Node.js:** >= 8.x
+> **Size (gzip):** 210 bytes
+> **Availability:** [CommonJS](https://unpkg.com/escalade/dist/index.js), [ES Module](https://unpkg.com/escalade/dist/index.mjs) + +This is the primary/default mode. It makes use of `async`/`await` and [`util.promisify`](https://nodejs.org/api/util.html#util_util_promisify_original). + +#### "sync" +> **Node.js:** >= 6.x
+> **Size (gzip):** 183 bytes
+> **Availability:** [CommonJS](https://unpkg.com/escalade/sync/index.js), [ES Module](https://unpkg.com/escalade/sync/index.mjs) + +This is the opt-in mode, ideal for scenarios where `async` usage cannot be supported. + + +## Usage + +***Example Structure*** + +``` +/Users/lukeed + └── oss + ├── license + └── escalade + ├── package.json + └── test + └── fixtures + ├── index.js + └── foobar + └── demo.js +``` + +***Example Usage*** + +```js +//~> demo.js +import { join } from 'path'; +import escalade from 'escalade'; + +const input = join(__dirname, 'demo.js'); +// or: const input = __dirname; + +const pkg = await escalade(input, (dir, names) => { + console.log('~> dir:', dir); + console.log('~> names:', names); + console.log('---'); + + if (names.includes('package.json')) { + // will be resolved into absolute + return 'package.json'; + } +}); + +//~> dir: /Users/lukeed/oss/escalade/test/fixtures/foobar +//~> names: ['demo.js'] +//--- +//~> dir: /Users/lukeed/oss/escalade/test/fixtures +//~> names: ['index.js', 'foobar'] +//--- +//~> dir: /Users/lukeed/oss/escalade/test +//~> names: ['fixtures'] +//--- +//~> dir: /Users/lukeed/oss/escalade +//~> names: ['package.json', 'test'] +//--- + +console.log(pkg); +//=> /Users/lukeed/oss/escalade/package.json + +// Now search for "missing123.txt" +// (Assume it doesn't exist anywhere!) +const missing = await escalade(input, (dir, names) => { + console.log('~> dir:', dir); + return names.includes('missing123.txt') && 'missing123.txt'; +}); + +//~> dir: /Users/lukeed/oss/escalade/test/fixtures/foobar +//~> dir: /Users/lukeed/oss/escalade/test/fixtures +//~> dir: /Users/lukeed/oss/escalade/test +//~> dir: /Users/lukeed/oss/escalade +//~> dir: /Users/lukeed/oss +//~> dir: /Users/lukeed +//~> dir: /Users +//~> dir: / + +console.log(missing); +//=> undefined +``` + +> **Note:** To run the above example with "sync" mode, import from `escalade/sync` and remove the `await` keyword. + + +## API + +### escalade(input, callback) +Returns: `string|void` or `Promise` + +When your `callback` locates a file, `escalade` will resolve/return with an absolute path.
+If your `callback` was never satisfied, then `escalade` will resolve/return with nothing (undefined). + +> **Important:**
The `sync` and `async` versions share the same API.
The **only** difference is that `sync` is not Promise-based. + +#### input +Type: `string` + +The path from which to start ascending. + +This may be a file or a directory path.
However, when `input` is a file, `escalade` will begin with its parent directory. + +> **Important:** Unless given an absolute path, `input` will be resolved from `process.cwd()` location. + +#### callback +Type: `Function` + +The callback to execute for each ancestry level. It always is given two arguments: + +1) `dir` - an absolute path of the current parent directory +2) `names` - a list (`string[]`) of contents _relative to_ the `dir` parent + +> **Note:** The `names` list can contain names of files _and_ directories. + +When your callback returns a _falsey_ value, then `escalade` will continue with `dir`'s parent directory, re-invoking your callback with new argument values. + +When your callback returns a string, then `escalade` stops iteration immediately.
+If the string is an absolute path, then it's left as is. Otherwise, the string is resolved into an absolute path _from_ the `dir` that housed the satisfying condition. + +> **Important:** Your `callback` can be a `Promise/AsyncFunction` when using the "async" version of `escalade`. + +## Benchmarks + +> Running on Node.js v10.13.0 + +``` +# Load Time + find-up 3.891ms + escalade 0.485ms + escalade/sync 0.309ms + +# Levels: 6 (target = "foo.txt"): + find-up x 24,856 ops/sec ±6.46% (55 runs sampled) + escalade x 73,084 ops/sec ±4.23% (73 runs sampled) + find-up.sync x 3,663 ops/sec ±1.12% (83 runs sampled) + escalade/sync x 9,360 ops/sec ±0.62% (88 runs sampled) + +# Levels: 12 (target = "package.json"): + find-up x 29,300 ops/sec ±10.68% (70 runs sampled) + escalade x 73,685 ops/sec ± 5.66% (66 runs sampled) + find-up.sync x 1,707 ops/sec ± 0.58% (91 runs sampled) + escalade/sync x 4,667 ops/sec ± 0.68% (94 runs sampled) + +# Levels: 18 (target = "missing123.txt"): + find-up x 21,818 ops/sec ±17.37% (14 runs sampled) + escalade x 67,101 ops/sec ±21.60% (20 runs sampled) + find-up.sync x 1,037 ops/sec ± 2.86% (88 runs sampled) + escalade/sync x 1,248 ops/sec ± 0.50% (93 runs sampled) +``` + +## Deno + +As of v3.1.0, `escalade` is available on the Deno registry. + +Please note that the [API](#api) is identical and that there are still [two modes](#modes) from which to choose: + +```ts +// Choose "async" mode +import escalade from 'https://deno.land/escalade/async.ts'; + +// Choose "sync" mode +import escalade from 'https://deno.land/escalade/sync.ts'; +``` + +> **Important:** The `allow-read` permission is required! + + +## Related + +- [premove](https://github.com/lukeed/premove) - A tiny (247B) utility to remove items recursively +- [totalist](https://github.com/lukeed/totalist) - A tiny (195B to 224B) utility to recursively list all (total) files in a directory +- [mk-dirs](https://github.com/lukeed/mk-dirs) - A tiny (420B) utility to make a directory and its parents, recursively + +## License + +MIT © [Luke Edwards](https://lukeed.com) diff --git a/tools/ui/node_modules/escalade/sync/index.d.mts b/tools/ui/node_modules/escalade/sync/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..c023d37b286d1f16630ed054d492c027184dffc0 --- /dev/null +++ b/tools/ui/node_modules/escalade/sync/index.d.mts @@ -0,0 +1,9 @@ +export type Callback = ( + directory: string, + files: string[], +) => string | false | void; + +export default function ( + directory: string, + callback: Callback, +): string | void; diff --git a/tools/ui/node_modules/escalade/sync/index.d.ts b/tools/ui/node_modules/escalade/sync/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9d5b5890c38169867e93a5dd6d3e9ed829370243 --- /dev/null +++ b/tools/ui/node_modules/escalade/sync/index.d.ts @@ -0,0 +1,13 @@ +declare namespace escalade { + export type Callback = ( + directory: string, + files: string[], + ) => string | false | void; +} + +declare function escalade( + directory: string, + callback: escalade.Callback, +): string | void; + +export = escalade; diff --git a/tools/ui/node_modules/escalade/sync/index.js b/tools/ui/node_modules/escalade/sync/index.js new file mode 100644 index 0000000000000000000000000000000000000000..902cc46cd9a80b10aa787e067ff1936ada95505d --- /dev/null +++ b/tools/ui/node_modules/escalade/sync/index.js @@ -0,0 +1,18 @@ +const { dirname, resolve } = require('path'); +const { readdirSync, statSync } = require('fs'); + +module.exports = function (start, callback) { + let dir = resolve('.', start); + let tmp, stats = statSync(dir); + + if (!stats.isDirectory()) { + dir = dirname(dir); + } + + while (true) { + tmp = callback(dir, readdirSync(dir)); + if (tmp) return resolve(dir, tmp); + dir = dirname(tmp = dir); + if (tmp === dir) break; + } +} diff --git a/tools/ui/node_modules/escalade/sync/index.mjs b/tools/ui/node_modules/escalade/sync/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3cdc5bd1fee04733ea106fd6cdde40ec094880cb --- /dev/null +++ b/tools/ui/node_modules/escalade/sync/index.mjs @@ -0,0 +1,18 @@ +import { dirname, resolve } from 'path'; +import { readdirSync, statSync } from 'fs'; + +export default function (start, callback) { + let dir = resolve('.', start); + let tmp, stats = statSync(dir); + + if (!stats.isDirectory()) { + dir = dirname(dir); + } + + while (true) { + tmp = callback(dir, readdirSync(dir)); + if (tmp) return resolve(dir, tmp); + dir = dirname(tmp = dir); + if (tmp === dir) break; + } +} diff --git a/tools/ui/node_modules/escape-html/LICENSE b/tools/ui/node_modules/escape-html/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..2e70de9717e715b4fc05c7f8bdc4e8d63a33b859 --- /dev/null +++ b/tools/ui/node_modules/escape-html/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2012-2013 TJ Holowaychuk +Copyright (c) 2015 Andreas Lubbe +Copyright (c) 2015 Tiancheng "Timothy" Gu + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tools/ui/node_modules/escape-html/Readme.md b/tools/ui/node_modules/escape-html/Readme.md new file mode 100644 index 0000000000000000000000000000000000000000..653d9eaa793317827ce724c4a0756110e9356fc8 --- /dev/null +++ b/tools/ui/node_modules/escape-html/Readme.md @@ -0,0 +1,43 @@ + +# escape-html + + Escape string for use in HTML + +## Example + +```js +var escape = require('escape-html'); +var html = escape('foo & bar'); +// -> foo & bar +``` + +## Benchmark + +``` +$ npm run-script bench + +> escape-html@1.0.3 bench nodejs-escape-html +> node benchmark/index.js + + + http_parser@1.0 + node@0.10.33 + v8@3.14.5.9 + ares@1.9.0-DEV + uv@0.10.29 + zlib@1.2.3 + modules@11 + openssl@1.0.1j + + 1 test completed. + 2 tests completed. + 3 tests completed. + + no special characters x 19,435,271 ops/sec ±0.85% (187 runs sampled) + single special character x 6,132,421 ops/sec ±0.67% (194 runs sampled) + many special characters x 3,175,826 ops/sec ±0.65% (193 runs sampled) +``` + +## License + + MIT \ No newline at end of file diff --git a/tools/ui/node_modules/escape-html/index.js b/tools/ui/node_modules/escape-html/index.js new file mode 100644 index 0000000000000000000000000000000000000000..bf9e226f4e872bee53a930739e5381d013c47568 --- /dev/null +++ b/tools/ui/node_modules/escape-html/index.js @@ -0,0 +1,78 @@ +/*! + * escape-html + * Copyright(c) 2012-2013 TJ Holowaychuk + * Copyright(c) 2015 Andreas Lubbe + * Copyright(c) 2015 Tiancheng "Timothy" Gu + * MIT Licensed + */ + +'use strict'; + +/** + * Module variables. + * @private + */ + +var matchHtmlRegExp = /["'&<>]/; + +/** + * Module exports. + * @public + */ + +module.exports = escapeHtml; + +/** + * Escape special characters in the given string of html. + * + * @param {string} string The string to escape for inserting into HTML + * @return {string} + * @public + */ + +function escapeHtml(string) { + var str = '' + string; + var match = matchHtmlRegExp.exec(str); + + if (!match) { + return str; + } + + var escape; + var html = ''; + var index = 0; + var lastIndex = 0; + + for (index = match.index; index < str.length; index++) { + switch (str.charCodeAt(index)) { + case 34: // " + escape = '"'; + break; + case 38: // & + escape = '&'; + break; + case 39: // ' + escape = '''; + break; + case 60: // < + escape = '<'; + break; + case 62: // > + escape = '>'; + break; + default: + continue; + } + + if (lastIndex !== index) { + html += str.substring(lastIndex, index); + } + + lastIndex = index + 1; + html += escape; + } + + return lastIndex !== index + ? html + str.substring(lastIndex, index) + : html; +} diff --git a/tools/ui/node_modules/escape-html/package.json b/tools/ui/node_modules/escape-html/package.json new file mode 100644 index 0000000000000000000000000000000000000000..57ec7bd0754d50af9c5e96a208aed6d85c1e6d5e --- /dev/null +++ b/tools/ui/node_modules/escape-html/package.json @@ -0,0 +1,24 @@ +{ + "name": "escape-html", + "description": "Escape string for use in HTML", + "version": "1.0.3", + "license": "MIT", + "keywords": [ + "escape", + "html", + "utility" + ], + "repository": "component/escape-html", + "devDependencies": { + "benchmark": "1.0.0", + "beautify-benchmark": "0.2.4" + }, + "files": [ + "LICENSE", + "Readme.md", + "index.js" + ], + "scripts": { + "bench": "node benchmark/index.js" + } +} diff --git a/tools/ui/node_modules/escape-string-regexp/index.d.ts b/tools/ui/node_modules/escape-string-regexp/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7d34edc7c5488acb084509b460634bc76bd9f4ec --- /dev/null +++ b/tools/ui/node_modules/escape-string-regexp/index.d.ts @@ -0,0 +1,18 @@ +/** +Escape RegExp special characters. + +You can also use this to escape a string that is inserted into the middle of a regex, for example, into a character class. + +@example +``` +import escapeStringRegexp = require('escape-string-regexp'); + +const escapedString = escapeStringRegexp('How much $ for a 🦄?'); +//=> 'How much \\$ for a 🦄\\?' + +new RegExp(escapedString); +``` +*/ +declare const escapeStringRegexp: (string: string) => string; + +export = escapeStringRegexp; diff --git a/tools/ui/node_modules/escape-string-regexp/index.js b/tools/ui/node_modules/escape-string-regexp/index.js new file mode 100644 index 0000000000000000000000000000000000000000..387c5615a776b4a3441e7d1fd526f460d61e595e --- /dev/null +++ b/tools/ui/node_modules/escape-string-regexp/index.js @@ -0,0 +1,13 @@ +'use strict'; + +module.exports = string => { + if (typeof string !== 'string') { + throw new TypeError('Expected a string'); + } + + // Escape characters with special meaning either inside or outside character sets. + // Use a simple backslash escape when it’s always valid, and a \unnnn escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar. + return string + .replace(/[|\\{}()[\]^$+*?.]/g, '\\$&') + .replace(/-/g, '\\x2d'); +}; diff --git a/tools/ui/node_modules/escape-string-regexp/license b/tools/ui/node_modules/escape-string-regexp/license new file mode 100644 index 0000000000000000000000000000000000000000..fa7ceba3eb4a9657a9db7f3ffca4e4e97a9019de --- /dev/null +++ b/tools/ui/node_modules/escape-string-regexp/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tools/ui/node_modules/escape-string-regexp/package.json b/tools/ui/node_modules/escape-string-regexp/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c6eb4a91bc914b2cb46f1e09117af3a4774f4d44 --- /dev/null +++ b/tools/ui/node_modules/escape-string-regexp/package.json @@ -0,0 +1,38 @@ +{ + "name": "escape-string-regexp", + "version": "4.0.0", + "description": "Escape RegExp special characters", + "license": "MIT", + "repository": "sindresorhus/escape-string-regexp", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "escape", + "regex", + "regexp", + "regular", + "expression", + "string", + "special", + "characters" + ], + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.11.0", + "xo": "^0.28.3" + } +} diff --git a/tools/ui/node_modules/escape-string-regexp/readme.md b/tools/ui/node_modules/escape-string-regexp/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..2945dfcb23ea118a6f7abeb12741d139a92eecb0 --- /dev/null +++ b/tools/ui/node_modules/escape-string-regexp/readme.md @@ -0,0 +1,34 @@ +# escape-string-regexp [![Build Status](https://travis-ci.org/sindresorhus/escape-string-regexp.svg?branch=master)](https://travis-ci.org/sindresorhus/escape-string-regexp) + +> Escape RegExp special characters + +## Install + +``` +$ npm install escape-string-regexp +``` + +## Usage + +```js +const escapeStringRegexp = require('escape-string-regexp'); + +const escapedString = escapeStringRegexp('How much $ for a 🦄?'); +//=> 'How much \\$ for a 🦄\\?' + +new RegExp(escapedString); +``` + +You can also use this to escape a string that is inserted into the middle of a regex, for example, into a character class. + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/tools/ui/node_modules/eslint/LICENSE b/tools/ui/node_modules/eslint/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b607bb36e96c33fd8ef50897db0336c585b6137a --- /dev/null +++ b/tools/ui/node_modules/eslint/LICENSE @@ -0,0 +1,19 @@ +Copyright OpenJS Foundation and other contributors, + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/ui/node_modules/eslint/README.md b/tools/ui/node_modules/eslint/README.md new file mode 100644 index 0000000000000000000000000000000000000000..77d1940108eb8d0bda3a71bd9c8d973d25de6a2a --- /dev/null +++ b/tools/ui/node_modules/eslint/README.md @@ -0,0 +1,354 @@ +[![npm version](https://img.shields.io/npm/v/eslint.svg)](https://www.npmjs.com/package/eslint) +[![Downloads](https://img.shields.io/npm/dm/eslint.svg)](https://www.npmjs.com/package/eslint) +[![Build Status](https://github.com/eslint/eslint/workflows/CI/badge.svg)](https://github.com/eslint/eslint/actions) +
+[![Open Collective Backers](https://img.shields.io/opencollective/backers/eslint)](https://opencollective.com/eslint) +[![Open Collective Sponsors](https://img.shields.io/opencollective/sponsors/eslint)](https://opencollective.com/eslint) + +# ESLint + +[Website](https://eslint.org) | +[Configure ESLint](https://eslint.org/docs/latest/use/configure) | +[Rules](https://eslint.org/docs/rules/) | +[Contribute to ESLint](https://eslint.org/docs/latest/contribute) | +[Report Bugs](https://eslint.org/docs/latest/contribute/report-bugs) | +[Code of Conduct](https://eslint.org/conduct) | +[X](https://x.com/geteslint) | +[Discord](https://eslint.org/chat) | +[Mastodon](https://fosstodon.org/@eslint) | +[Bluesky](https://bsky.app/profile/eslint.org) + +ESLint is a tool for identifying and reporting on patterns found in ECMAScript/JavaScript code. In many ways, it is similar to JSLint and JSHint with a few exceptions: + +- ESLint uses [Espree](https://github.com/eslint/js/tree/main/packages/espree) for JavaScript parsing. +- ESLint uses an AST to evaluate patterns in code. +- ESLint is completely pluggable, every single rule is a plugin and you can add more at runtime. + +## Table of Contents + +1. [Installation and Usage](#installation-and-usage) +1. [Configuration](#configuration) +1. [Version Support](#version-support) +1. [Code of Conduct](#code-of-conduct) +1. [Filing Issues](#filing-issues) +1. [Frequently Asked Questions](#frequently-asked-questions) +1. [Releases](#releases) +1. [Security Policy](#security-policy) +1. [Semantic Versioning Policy](#semantic-versioning-policy) +1. [License](#license) +1. [Team](#team) +1. [Sponsors](#sponsors) +1. [Technology Sponsors](#technology-sponsors) + +## Installation and Usage + +Prerequisites: [Node.js](https://nodejs.org/) (`^18.18.0`, `^20.9.0`, or `>=21.1.0`) built with SSL support. (If you are using an official Node.js distribution, SSL is always built in.) + +You can install and configure ESLint using this command: + +```shell +npm init @eslint/config@latest +``` + +After that, you can run ESLint on any file or directory like this: + +```shell +npx eslint yourfile.js +``` + +### pnpm Installation + +To use ESLint with pnpm, we recommend setting up a `.npmrc` file with at least the following settings: + +```text +auto-install-peers=true +node-linker=hoisted +``` + +This ensures that pnpm installs dependencies in a way that is more compatible with npm and is less likely to produce errors. + +## Configuration + +You can configure rules in your `eslint.config.js` files as in this example: + +```js +import { defineConfig } from "eslint/config"; + +export default defineConfig([ + { + files: ["**/*.js", "**/*.cjs", "**/*.mjs"], + rules: { + "prefer-const": "warn", + "no-constant-binary-expression": "error", + }, + }, +]); +``` + +The names `"prefer-const"` and `"no-constant-binary-expression"` are the names of [rules](https://eslint.org/docs/rules) in ESLint. The first value is the error level of the rule and can be one of these values: + +- `"off"` or `0` - turn the rule off +- `"warn"` or `1` - turn the rule on as a warning (doesn't affect exit code) +- `"error"` or `2` - turn the rule on as an error (exit code will be 1) + +The three error levels allow you fine-grained control over how ESLint applies rules (for more configuration options and details, see the [configuration docs](https://eslint.org/docs/latest/use/configure)). + +## Version Support + +The ESLint team provides ongoing support for the current version and six months of limited support for the previous version. Limited support includes critical bug fixes, security issues, and compatibility issues only. + +ESLint offers commercial support for both current and previous versions through our partners, [Tidelift][tidelift] and [HeroDevs][herodevs]. + +See [Version Support](https://eslint.org/version-support) for more details. + +## Code of Conduct + +ESLint adheres to the [OpenJS Foundation Code of Conduct](https://eslint.org/conduct). + +## Filing Issues + +Before filing an issue, please be sure to read the guidelines for what you're reporting: + +- [Bug Report](https://eslint.org/docs/latest/contribute/report-bugs) +- [Propose a New Rule](https://eslint.org/docs/latest/contribute/propose-new-rule) +- [Proposing a Rule Change](https://eslint.org/docs/latest/contribute/propose-rule-change) +- [Request a Change](https://eslint.org/docs/latest/contribute/request-change) + +## Frequently Asked Questions + +### Does ESLint support JSX? + +Yes, ESLint natively supports parsing JSX syntax (this must be enabled in [configuration](https://eslint.org/docs/latest/use/configure)). Please note that supporting JSX syntax _is not_ the same as supporting React. React applies specific semantics to JSX syntax that ESLint doesn't recognize. We recommend using [eslint-plugin-react](https://www.npmjs.com/package/eslint-plugin-react) if you are using React and want React semantics. + +### Does Prettier replace ESLint? + +No, ESLint and Prettier have different jobs: ESLint is a linter (looking for problematic patterns) and Prettier is a code formatter. Using both tools is common, refer to [Prettier's documentation](https://prettier.io/docs/en/install#eslint-and-other-linters) to learn how to configure them to work well with each other. + +### What ECMAScript versions does ESLint support? + +ESLint has full support for ECMAScript 3, 5, and every year from 2015 up until the most recent stage 4 specification (the default). You can set your desired ECMAScript syntax and other settings (like global variables) through [configuration](https://eslint.org/docs/latest/use/configure). + +### What about experimental features? + +ESLint's parser only officially supports the latest final ECMAScript standard. We will make changes to core rules in order to avoid crashes on stage 3 ECMAScript syntax proposals (as long as they are implemented using the correct experimental ESTree syntax). We may make changes to core rules to better work with language extensions (such as JSX, Flow, and TypeScript) on a case-by-case basis. + +In other cases (including if rules need to warn on more or fewer cases due to new syntax, rather than just not crashing), we recommend you use other parsers and/or rule plugins. If you are using Babel, you can use [@babel/eslint-parser](https://www.npmjs.com/package/@babel/eslint-parser) and [@babel/eslint-plugin](https://www.npmjs.com/package/@babel/eslint-plugin) to use any option available in Babel. + +Once a language feature has been adopted into the ECMAScript standard (stage 4 according to the [TC39 process](https://tc39.github.io/process-document/)), we will accept issues and pull requests related to the new feature, subject to our [contributing guidelines](https://eslint.org/docs/latest/contribute). Until then, please use the appropriate parser and plugin(s) for your experimental feature. + +### Which Node.js versions does ESLint support? + +ESLint updates the supported Node.js versions with each major release of ESLint. At that time, ESLint's supported Node.js versions are updated to be: + +1. The most recent maintenance release of Node.js +1. The lowest minor version of the Node.js LTS release that includes the features the ESLint team wants to use. +1. The Node.js Current release + +ESLint is also expected to work with Node.js versions released after the Node.js Current release. + +Refer to the [Quick Start Guide](https://eslint.org/docs/latest/use/getting-started#prerequisites) for the officially supported Node.js versions for a given ESLint release. + +### Where to ask for help? + +Open a [discussion](https://github.com/eslint/eslint/discussions) or stop by our [Discord server](https://eslint.org/chat). + +### Why doesn't ESLint lock dependency versions? + +Lock files like `package-lock.json` are helpful for deployed applications. They ensure that dependencies are consistent between environments and across deployments. + +Packages like `eslint` that get published to the npm registry do not include lock files. `npm install eslint` as a user will respect version constraints in ESLint's `package.json`. ESLint and its dependencies will be included in the user's lock file if one exists, but ESLint's own lock file would not be used. + +We intentionally don't lock dependency versions so that we have the latest compatible dependency versions in development and CI that our users get when installing ESLint in a project. + +The Twilio blog has a [deeper dive](https://www.twilio.com/blog/lockfiles-nodejs) to learn more. + +## Releases + +We have scheduled releases every two weeks on Friday or Saturday. You can follow a [release issue](https://github.com/eslint/eslint/issues?q=is%3Aopen+is%3Aissue+label%3Arelease) for updates about the scheduling of any particular release. + +## Security Policy + +ESLint takes security seriously. We work hard to ensure that ESLint is safe for everyone and that security issues are addressed quickly and responsibly. Read the full [security policy](https://github.com/eslint/.github/blob/master/SECURITY.md). + +## Semantic Versioning Policy + +ESLint follows [semantic versioning](https://semver.org). However, due to the nature of ESLint as a code quality tool, it's not always clear when a minor or major version bump occurs. To help clarify this for everyone, we've defined the following semantic versioning policy for ESLint: + +- Patch release (intended to not break your lint build) + - A bug fix in a rule that results in ESLint reporting fewer linting errors. + - A bug fix to the CLI or core (including formatters). + - Improvements to documentation. + - Non-user-facing changes such as refactoring code, adding, deleting, or modifying tests, and increasing test coverage. + - Re-releasing after a failed release (i.e., publishing a release that doesn't work for anyone). +- Minor release (might break your lint build) + - A bug fix in a rule that results in ESLint reporting more linting errors. + - A new rule is created. + - A new option to an existing rule that does not result in ESLint reporting more linting errors by default. + - A new addition to an existing rule to support a newly-added language feature (within the last 12 months) that will result in ESLint reporting more linting errors by default. + - An existing rule is deprecated. + - A new CLI capability is created. + - New capabilities to the public API are added (new classes, new methods, new arguments to existing methods, etc.). + - A new formatter is created. + - `eslint:recommended` is updated and will result in strictly fewer linting errors (e.g., rule removals). +- Major release (likely to break your lint build) + - `eslint:recommended` is updated and may result in new linting errors (e.g., rule additions, most rule option updates). + - A new option to an existing rule that results in ESLint reporting more linting errors by default. + - An existing formatter is removed. + - Part of the public API is removed or changed in an incompatible way. The public API includes: + - Rule schemas + - Configuration schema + - Command-line options + - Node.js API + - Rule, formatter, parser, plugin APIs + +According to our policy, any minor update may report more linting errors than the previous release (ex: from a bug fix). As such, we recommend using the tilde (`~`) in `package.json` e.g. `"eslint": "~3.1.0"` to guarantee the results of your builds. + +## License + +MIT License + +Copyright OpenJS Foundation and other contributors, + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +## Team + +These folks keep the project moving and are resources for help. + + + + + +### Technical Steering Committee (TSC) + +The people who manage releases, review feature requests, and meet regularly to ensure ESLint is properly maintained. + +
+ +Nicholas C. Zakas's Avatar
+Nicholas C. Zakas +
+
+ +Francesco Trotta's Avatar
+Francesco Trotta +
+
+ +Milos Djermanovic's Avatar
+Milos Djermanovic +
+
+ +### Reviewers + +The people who review and implement new features. + +
+ +唯然's Avatar
+唯然 +
+
+ +Nitin Kumar's Avatar
+Nitin Kumar +
+
+ +### Committers + +The people who review and fix bugs and help triage issues. + +
+ +fnx's Avatar
+fnx +
+
+ +Josh Goldberg ✨'s Avatar
+Josh Goldberg ✨ +
+
+ +Sweta Tanwar's Avatar
+Sweta Tanwar +
+
+ +Tanuj Kanti's Avatar
+Tanuj Kanti +
+
+ +루밀LuMir's Avatar
+루밀LuMir +
+
+ +Pixel998's Avatar
+Pixel998 +
+
+ +### Website Team + +Team members who focus specifically on eslint.org + +
+ +Amaresh  S M's Avatar
+Amaresh S M +
+
+ +Harish's Avatar
+Harish +
+
+ +Percy Ma's Avatar
+Percy Ma +
+
+ + + + + + +## Sponsors + +The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate) +to get your logo on our READMEs and [website](https://eslint.org/sponsors). + +

Platinum Sponsors

+

Automattic Airbnb

Gold Sponsors

+

Qlty Software trunk.io Shopify

Silver Sponsors

+

Vite Liftoff American Express StackBlitz

Bronze Sponsors

+

Cybozu Icons8 Discord GitBook Nx Mercedes-Benz Group HeroCoders LambdaTest

+

Technology Sponsors

+Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work. +

Netlify Algolia 1Password

+ + + +[tidelift]: https://tidelift.com/funding/github/npm/eslint +[herodevs]: https://www.herodevs.com/support/eslint-nes?utm_source=ESLintWebsite&utm_medium=ESLintWebsite&utm_campaign=ESLintNES&utm_id=ESLintNES diff --git a/tools/ui/node_modules/eslint/bin/eslint.js b/tools/ui/node_modules/eslint/bin/eslint.js new file mode 100644 index 0000000000000000000000000000000000000000..9b202a98233128cd3b46c71940c27dfbf334c5df --- /dev/null +++ b/tools/ui/node_modules/eslint/bin/eslint.js @@ -0,0 +1,196 @@ +#!/usr/bin/env node + +/** + * @fileoverview Main CLI that is run via the eslint command. + * @author Nicholas C. Zakas + */ + +/* eslint no-console:off -- CLI */ + +"use strict"; + +const mod = require("node:module"); + +// to use V8's code cache to speed up instantiation time +mod.enableCompileCache?.(); + +// must do this initialization *before* other requires in order to work +if (process.argv.includes("--debug")) { + require("debug").enable("eslint:*,-eslint:code-path,eslintrc:*"); +} + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Read data from stdin til the end. + * + * Note: See + * - https://github.com/nodejs/node/blob/master/doc/api/process.md#processstdin + * - https://github.com/nodejs/node/blob/master/doc/api/process.md#a-note-on-process-io + * - https://lists.gnu.org/archive/html/bug-gnu-emacs/2016-01/msg00419.html + * - https://github.com/nodejs/node/issues/7439 (historical) + * + * On Windows using `fs.readFileSync(STDIN_FILE_DESCRIPTOR, "utf8")` seems + * to read 4096 bytes before blocking and never drains to read further data. + * + * The investigation on the Emacs thread indicates: + * + * > Emacs on MS-Windows uses pipes to communicate with subprocesses; a + * > pipe on Windows has a 4K buffer. So as soon as Emacs writes more than + * > 4096 bytes to the pipe, the pipe becomes full, and Emacs then waits for + * > the subprocess to read its end of the pipe, at which time Emacs will + * > write the rest of the stuff. + * @returns {Promise} The read text. + */ +function readStdin() { + return new Promise((resolve, reject) => { + let content = ""; + let chunk = ""; + + process.stdin + .setEncoding("utf8") + .on("readable", () => { + while ((chunk = process.stdin.read()) !== null) { + content += chunk; + } + }) + .on("end", () => resolve(content)) + .on("error", reject); + }); +} + +/** + * Get the error message of a given value. + * @param {any} error The value to get. + * @returns {string} The error message. + */ +function getErrorMessage(error) { + // Lazy loading because this is used only if an error happened. + const util = require("node:util"); + + // Foolproof -- third-party module might throw non-object. + if (typeof error !== "object" || error === null) { + return String(error); + } + + // Use templates if `error.messageTemplate` is present. + if (typeof error.messageTemplate === "string") { + try { + const template = require(`../messages/${error.messageTemplate}.js`); + + return template(error.messageData || {}); + } catch { + // Ignore template error then fallback to use `error.stack`. + } + } + + // Use the stacktrace if it's an error object. + if (typeof error.stack === "string") { + return error.stack; + } + + // Otherwise, dump the object. + return util.format("%o", error); +} + +/** + * Tracks error messages that are shown to the user so we only ever show the + * same message once. + * @type {Set} + */ +const displayedErrors = new Set(); + +/** + * Tracks whether an unexpected error was caught + * @type {boolean} + */ +let hadFatalError = false; + +/** + * Catch and report unexpected error. + * @param {any} error The thrown error object. + * @returns {void} + */ +function onFatalError(error) { + process.exitCode = 2; + hadFatalError = true; + + const { version } = require("../package.json"); + const message = ` +Oops! Something went wrong! :( + +ESLint: ${version} + +${getErrorMessage(error)}`; + + if (!displayedErrors.has(message)) { + console.error(message); + displayedErrors.add(message); + } +} + +//------------------------------------------------------------------------------ +// Execution +//------------------------------------------------------------------------------ + +(async function main() { + process.on("uncaughtException", onFatalError); + process.on("unhandledRejection", onFatalError); + + // Call the config initializer if `--init` is present. + if (process.argv.includes("--init")) { + // `eslint --init` has been moved to `@eslint/create-config` + console.warn( + "You can also run this command directly using 'npm init @eslint/config@latest'.", + ); + + const spawn = require("cross-spawn"); + + spawn.sync("npm", ["init", "@eslint/config@latest"], { + encoding: "utf8", + stdio: "inherit", + }); + return; + } + + // start the MCP server if `--mcp` is present + if (process.argv.includes("--mcp")) { + console.warn( + "You can also run this command directly using 'npx @eslint/mcp@latest'.", + ); + + const spawn = require("cross-spawn"); + + spawn.sync("npx", ["@eslint/mcp@latest"], { + encoding: "utf8", + stdio: "inherit", + }); + return; + } + + // Otherwise, call the CLI. + const cli = require("../lib/cli"); + const exitCode = await cli.execute( + process.argv, + process.argv.includes("--stdin") ? await readStdin() : null, + true, + ); + + /* + * If an uncaught exception or unhandled rejection was detected in the meantime, + * keep the fatal exit code 2 that is already assigned to `process.exitCode`. + * Without this condition, exit code 2 (unsuccessful execution) could be overwritten with + * 1 (successful execution, lint problems found) or even 0 (successful execution, no lint problems found). + * This ensures that unexpected errors that seemingly don't affect the success + * of the execution will still cause a non-zero exit code, as it's a common + * practice and the default behavior of Node.js to exit with non-zero + * in case of an uncaught exception or unhandled rejection. + * + * Otherwise, assign the exit code returned from CLI. + */ + if (!hadFatalError) { + process.exitCode = exitCode; + } +})().catch(onFatalError); diff --git a/tools/ui/node_modules/eslint/conf/default-cli-options.js b/tools/ui/node_modules/eslint/conf/default-cli-options.js new file mode 100644 index 0000000000000000000000000000000000000000..dda88d655904124ded0d53e08375f9b7452c8ed6 --- /dev/null +++ b/tools/ui/node_modules/eslint/conf/default-cli-options.js @@ -0,0 +1,32 @@ +/** + * @fileoverview Default CLIEngineOptions. + * @author Ian VanSchooten + */ + +"use strict"; + +module.exports = { + configFile: null, + baseConfig: false, + rulePaths: [], + useEslintrc: true, + envs: [], + globals: [], + extensions: null, + ignore: true, + ignorePath: void 0, + cache: false, + + /* + * in order to honor the cacheFile option if specified + * this option should not have a default value otherwise + * it will always be used + */ + cacheLocation: "", + cacheFile: ".eslintcache", + cacheStrategy: "metadata", + fix: false, + allowInlineConfig: true, + reportUnusedDisableDirectives: void 0, + globInputPaths: true, +}; diff --git a/tools/ui/node_modules/eslint/conf/ecma-version.js b/tools/ui/node_modules/eslint/conf/ecma-version.js new file mode 100644 index 0000000000000000000000000000000000000000..e68d302062717788130044dec8af6e16fcb3eaa4 --- /dev/null +++ b/tools/ui/node_modules/eslint/conf/ecma-version.js @@ -0,0 +1,16 @@ +/** + * @fileoverview Configuration related to ECMAScript versions + * @author Milos Djermanovic + */ + +"use strict"; + +/** + * The latest ECMAScript version supported by ESLint. + * @type {number} year-based ECMAScript version + */ +const LATEST_ECMA_VERSION = 2026; + +module.exports = { + LATEST_ECMA_VERSION, +}; diff --git a/tools/ui/node_modules/eslint/conf/globals.js b/tools/ui/node_modules/eslint/conf/globals.js new file mode 100644 index 0000000000000000000000000000000000000000..b630b272a155b007f31a528099e2902106579849 --- /dev/null +++ b/tools/ui/node_modules/eslint/conf/globals.js @@ -0,0 +1,169 @@ +/** + * @fileoverview Globals for ecmaVersion/sourceType + * @author Nicholas C. Zakas + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Globals +//----------------------------------------------------------------------------- + +const commonjs = { + exports: true, + global: false, + module: false, + require: false, +}; + +const es3 = { + Array: false, + Boolean: false, + constructor: false, + Date: false, + decodeURI: false, + decodeURIComponent: false, + encodeURI: false, + encodeURIComponent: false, + Error: false, + escape: false, + eval: false, + EvalError: false, + Function: false, + hasOwnProperty: false, + Infinity: false, + isFinite: false, + isNaN: false, + isPrototypeOf: false, + Math: false, + NaN: false, + Number: false, + Object: false, + parseFloat: false, + parseInt: false, + propertyIsEnumerable: false, + RangeError: false, + ReferenceError: false, + RegExp: false, + String: false, + SyntaxError: false, + toLocaleString: false, + toString: false, + TypeError: false, + undefined: false, + unescape: false, + URIError: false, + valueOf: false, +}; + +const es5 = { + ...es3, + JSON: false, +}; + +const es2015 = { + ...es5, + ArrayBuffer: false, + DataView: false, + Float32Array: false, + Float64Array: false, + Int16Array: false, + Int32Array: false, + Int8Array: false, + Intl: false, + Map: false, + Promise: false, + Proxy: false, + Reflect: false, + Set: false, + Symbol: false, + Uint16Array: false, + Uint32Array: false, + Uint8Array: false, + Uint8ClampedArray: false, + WeakMap: false, + WeakSet: false, +}; + +// no new globals in ES2016 +const es2016 = { + ...es2015, +}; + +const es2017 = { + ...es2016, + Atomics: false, + SharedArrayBuffer: false, +}; + +// no new globals in ES2018 +const es2018 = { + ...es2017, +}; + +// no new globals in ES2019 +const es2019 = { + ...es2018, +}; + +const es2020 = { + ...es2019, + BigInt: false, + BigInt64Array: false, + BigUint64Array: false, + globalThis: false, +}; + +const es2021 = { + ...es2020, + AggregateError: false, + FinalizationRegistry: false, + WeakRef: false, +}; + +const es2022 = { + ...es2021, +}; + +const es2023 = { + ...es2022, +}; + +const es2024 = { + ...es2023, +}; + +const es2025 = { + ...es2024, + Float16Array: false, + Iterator: false, +}; + +const es2026 = { + ...es2025, + AsyncDisposableStack: false, + DisposableStack: false, + SuppressedError: false, +}; + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +module.exports = { + commonjs, + es3, + es5, + es2015, + es2016, + es2017, + es2018, + es2019, + es2020, + es2021, + es2022, + es2023, + es2024, + es2025, + es2026, +}; diff --git a/tools/ui/node_modules/eslint/conf/replacements.json b/tools/ui/node_modules/eslint/conf/replacements.json new file mode 100644 index 0000000000000000000000000000000000000000..27329c4c9c62051a86b2f4386f0c76d092d4b136 --- /dev/null +++ b/tools/ui/node_modules/eslint/conf/replacements.json @@ -0,0 +1,26 @@ +{ + "rules": { + "generator-star": ["generator-star-spacing"], + "global-strict": ["strict"], + "no-arrow-condition": ["no-confusing-arrow", "no-constant-condition"], + "no-comma-dangle": ["comma-dangle"], + "no-empty-class": ["no-empty-character-class"], + "no-empty-label": ["no-labels"], + "no-extra-strict": ["strict"], + "no-reserved-keys": ["quote-props"], + "no-space-before-semi": ["semi-spacing"], + "no-wrap-func": ["no-extra-parens"], + "space-after-function-name": ["space-before-function-paren"], + "space-after-keywords": ["keyword-spacing"], + "space-before-function-parentheses": ["space-before-function-paren"], + "space-before-keywords": ["keyword-spacing"], + "space-in-brackets": [ + "object-curly-spacing", + "array-bracket-spacing", + "computed-property-spacing" + ], + "space-return-throw-case": ["keyword-spacing"], + "space-unary-word-ops": ["space-unary-ops"], + "spaced-line-comment": ["spaced-comment"] + } +} diff --git a/tools/ui/node_modules/eslint/conf/rule-type-list.json b/tools/ui/node_modules/eslint/conf/rule-type-list.json new file mode 100644 index 0000000000000000000000000000000000000000..05ddd3cb02afceeea31905f3176c3146ec764a3a --- /dev/null +++ b/tools/ui/node_modules/eslint/conf/rule-type-list.json @@ -0,0 +1,91 @@ +{ + "types": { + "problem": [], + "suggestion": [], + "layout": [] + }, + "deprecated": [], + "removed": [ + { + "removed": "generator-star", + "replacedBy": [{ "rule": { "name": "generator-star-spacing" } }] + }, + { + "removed": "global-strict", + "replacedBy": [{ "rule": { "name": "strict" } }] + }, + { + "removed": "no-arrow-condition", + "replacedBy": [ + { "rule": { "name": "no-confusing-arrow" } }, + { "rule": { "name": "no-constant-condition" } } + ] + }, + { + "removed": "no-comma-dangle", + "replacedBy": [{ "rule": { "name": "comma-dangle" } }] + }, + { + "removed": "no-empty-class", + "replacedBy": [{ "rule": { "name": "no-empty-character-class" } }] + }, + { + "removed": "no-empty-label", + "replacedBy": [{ "rule": { "name": "no-labels" } }] + }, + { + "removed": "no-extra-strict", + "replacedBy": [{ "rule": { "name": "strict" } }] + }, + { + "removed": "no-reserved-keys", + "replacedBy": [{ "rule": { "name": "quote-props" } }] + }, + { + "removed": "no-space-before-semi", + "replacedBy": [{ "rule": { "name": "semi-spacing" } }] + }, + { + "removed": "no-wrap-func", + "replacedBy": [{ "rule": { "name": "no-extra-parens" } }] + }, + { + "removed": "space-after-function-name", + "replacedBy": [{ "rule": { "name": "space-before-function-paren" } }] + }, + { + "removed": "space-after-keywords", + "replacedBy": [{ "rule": { "name": "keyword-spacing" } }] + }, + { + "removed": "space-before-function-parentheses", + "replacedBy": [{ "rule": { "name": "space-before-function-paren" } }] + }, + { + "removed": "space-before-keywords", + "replacedBy": [{ "rule": { "name": "keyword-spacing" } }] + }, + { + "removed": "space-in-brackets", + "replacedBy": [ + { "rule": { "name": "object-curly-spacing" } }, + { "rule": { "name": "array-bracket-spacing" } }, + { "rule": { "name": "computed-property-spacing" } } + ] + }, + { + "removed": "space-return-throw-case", + "replacedBy": [{ "rule": { "name": "keyword-spacing" } }] + }, + { + "removed": "space-unary-word-ops", + "replacedBy": [{ "rule": { "name": "space-unary-ops" } }] + }, + { + "removed": "spaced-line-comment", + "replacedBy": [{ "rule": { "name": "spaced-comment" } }] + }, + { "removed": "valid-jsdoc", "replacedBy": [] }, + { "removed": "require-jsdoc", "replacedBy": [] } + ] +} diff --git a/tools/ui/node_modules/eslint/lib/api.js b/tools/ui/node_modules/eslint/lib/api.js new file mode 100644 index 0000000000000000000000000000000000000000..ce6102dad522222314eb6a7910dc6fc41db9d1c0 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/api.js @@ -0,0 +1,50 @@ +/** + * @fileoverview Expose out ESLint and CLI to require. + * @author Ian Christian Myers + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Requirements +//----------------------------------------------------------------------------- + +const { ESLint, shouldUseFlatConfig } = require("./eslint/eslint"); +const { LegacyESLint } = require("./eslint/legacy-eslint"); +const { Linter } = require("./linter"); +const { RuleTester } = require("./rule-tester"); +const { SourceCode } = require("./languages/js/source-code"); + +//----------------------------------------------------------------------------- +// Functions +//----------------------------------------------------------------------------- + +/** + * Loads the correct ESLint constructor given the options. + * @param {Object} [options] The options object + * @param {boolean} [options.useFlatConfig] Whether or not to use a flat config + * @returns {Promise} The ESLint constructor + */ +async function loadESLint({ useFlatConfig } = {}) { + /* + * Note: The v8.x version of this function also accepted a `cwd` option, but + * it is not used in this implementation so we silently ignore it. + */ + + const shouldESLintUseFlatConfig = + useFlatConfig ?? (await shouldUseFlatConfig()); + + return shouldESLintUseFlatConfig ? ESLint : LegacyESLint; +} + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +module.exports = { + Linter, + loadESLint, + ESLint, + RuleTester, + SourceCode, +}; diff --git a/tools/ui/node_modules/eslint/lib/cli-engine/cli-engine.js b/tools/ui/node_modules/eslint/lib/cli-engine/cli-engine.js new file mode 100644 index 0000000000000000000000000000000000000000..a0c3bc67bfede8a1fa637462d737a3159c229516 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/cli-engine/cli-engine.js @@ -0,0 +1,1109 @@ +/** + * @fileoverview Main CLI object. + * @author Nicholas C. Zakas + */ + +"use strict"; + +/* + * The CLI object should *not* call process.exit() directly. It should only return + * exit codes. This allows other programs to use the CLI object and still control + * when the program exits. + */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const fs = require("node:fs"); +const path = require("node:path"); +const defaultOptions = require("../../conf/default-cli-options"); +const pkg = require("../../package.json"); + +const { + Legacy: { + ConfigOps, + naming, + CascadingConfigArrayFactory, + IgnorePattern, + getUsedExtractedConfigs, + ModuleResolver, + }, +} = require("@eslint/eslintrc"); + +const { FileEnumerator } = require("./file-enumerator"); + +const { Linter } = require("../linter"); +const builtInRules = require("../rules"); +const loadRules = require("./load-rules"); +const hash = require("./hash"); +const LintResultCache = require("./lint-result-cache"); + +const debug = require("debug")("eslint:cli-engine"); +const removedFormatters = new Set([ + "checkstyle", + "codeframe", + "compact", + "jslint-xml", + "junit", + "table", + "tap", + "unix", + "visualstudio", +]); +const validFixTypes = new Set(["directive", "problem", "suggestion", "layout"]); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +// For VSCode IntelliSense +/** @typedef {import("../types").ESLint.ConfigData} ConfigData */ +/** @typedef {import("../types").ESLint.DeprecatedRuleUse} DeprecatedRuleInfo */ +/** @typedef {import("../types").ESLint.FormatterFunction} FormatterFunction */ +/** @typedef {import("../types").Linter.LintMessage} LintMessage */ +/** @typedef {import("../types").Linter.ParserOptions} ParserOptions */ +/** @typedef {import("../types").ESLint.Plugin} Plugin */ +/** @typedef {import("../types").Rule.RuleModule} Rule */ +/** @typedef {import("../types").Linter.RuleEntry} RuleConf */ +/** @typedef {import("../types").Linter.SuppressedLintMessage} SuppressedLintMessage */ +/** @typedef {ReturnType} ConfigArray */ +/** @typedef {ReturnType} ExtractedConfig */ + +/** + * The options to configure a CLI engine with. + * @typedef {Object} CLIEngineOptions + * @property {boolean} [allowInlineConfig] Enable or disable inline configuration comments. + * @property {ConfigData} [baseConfig] Base config object, extended by all configs used with this CLIEngine instance + * @property {boolean} [cache] Enable result caching. + * @property {string} [cacheLocation] The cache file to use instead of .eslintcache. + * @property {string} [configFile] The configuration file to use. + * @property {string} [cwd] The value to use for the current working directory. + * @property {string[]} [envs] An array of environments to load. + * @property {string[]|null} [extensions] An array of file extensions to check. + * @property {boolean|Function} [fix] Execute in autofix mode. If a function, should return a boolean. + * @property {string[]} [fixTypes] Array of rule types to apply fixes for. + * @property {string[]} [globals] An array of global variables to declare. + * @property {boolean} [ignore] False disables use of .eslintignore. + * @property {string} [ignorePath] The ignore file to use instead of .eslintignore. + * @property {string|string[]} [ignorePattern] One or more glob patterns to ignore. + * @property {boolean} [useEslintrc] False disables looking for .eslintrc + * @property {string} [parser] The name of the parser to use. + * @property {ParserOptions} [parserOptions] An object of parserOption settings to use. + * @property {string[]} [plugins] An array of plugins to load. + * @property {Record} [rules] An object of rules to use. + * @property {string[]} [rulePaths] An array of directories to load custom rules from. + * @property {boolean|string} [reportUnusedDisableDirectives] `true`, `"error"` or '"warn"' adds reports for unused eslint-disable directives + * @property {boolean} [globInputPaths] Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file. + * @property {string} [resolvePluginsRelativeTo] The folder where plugins should be resolved from, defaulting to the CWD + */ + +/** + * A linting result. + * @typedef {Object} LintResult + * @property {string} filePath The path to the file that was linted. + * @property {LintMessage[]} messages All of the messages for the result. + * @property {SuppressedLintMessage[]} suppressedMessages All of the suppressed messages for the result. + * @property {number} errorCount Number of errors for the result. + * @property {number} fatalErrorCount Number of fatal errors for the result. + * @property {number} warningCount Number of warnings for the result. + * @property {number} fixableErrorCount Number of fixable errors for the result. + * @property {number} fixableWarningCount Number of fixable warnings for the result. + * @property {string} [source] The source code of the file that was linted. + * @property {string} [output] The source code of the file that was linted, with as many fixes applied as possible. + */ + +/** + * Linting results. + * @typedef {Object} LintReport + * @property {LintResult[]} results All of the result. + * @property {number} errorCount Number of errors for the result. + * @property {number} fatalErrorCount Number of fatal errors for the result. + * @property {number} warningCount Number of warnings for the result. + * @property {number} fixableErrorCount Number of fixable errors for the result. + * @property {number} fixableWarningCount Number of fixable warnings for the result. + * @property {DeprecatedRuleInfo[]} usedDeprecatedRules The list of used deprecated rules. + */ + +/** + * Private data for CLIEngine. + * @typedef {Object} CLIEngineInternalSlots + * @property {Map} additionalPluginPool The map for additional plugins. + * @property {string} cacheFilePath The path to the cache of lint results. + * @property {CascadingConfigArrayFactory} configArrayFactory The factory of configs. + * @property {(filePath: string) => boolean} defaultIgnores The default predicate function to check if a file ignored or not. + * @property {FileEnumerator} fileEnumerator The file enumerator. + * @property {ConfigArray[]} lastConfigArrays The list of config arrays that the last `executeOnFiles` or `executeOnText` used. + * @property {LintResultCache|null} lintResultCache The cache of lint results. + * @property {Linter} linter The linter instance which has loaded rules. + * @property {CLIEngineOptions} options The normalized options of this instance. + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** @type {WeakMap} */ +const internalSlotsMap = new WeakMap(); + +/** + * Determines if each fix type in an array is supported by ESLint and throws + * an error if not. + * @param {string[]} fixTypes An array of fix types to check. + * @returns {void} + * @throws {Error} If an invalid fix type is found. + */ +function validateFixTypes(fixTypes) { + for (const fixType of fixTypes) { + if (!validFixTypes.has(fixType)) { + throw new Error(`Invalid fix type "${fixType}" found.`); + } + } +} + +/** + * It will calculate the error and warning count for collection of messages per file + * @param {LintMessage[]} messages Collection of messages + * @returns {Object} Contains the stats + * @private + */ +function calculateStatsPerFile(messages) { + const stat = { + errorCount: 0, + fatalErrorCount: 0, + warningCount: 0, + fixableErrorCount: 0, + fixableWarningCount: 0, + }; + + for (let i = 0; i < messages.length; i++) { + const message = messages[i]; + + if (message.fatal || message.severity === 2) { + stat.errorCount++; + if (message.fatal) { + stat.fatalErrorCount++; + } + if (message.fix) { + stat.fixableErrorCount++; + } + } else { + stat.warningCount++; + if (message.fix) { + stat.fixableWarningCount++; + } + } + } + return stat; +} + +/** + * It will calculate the error and warning count for collection of results from all files + * @param {LintResult[]} results Collection of messages from all the files + * @returns {Object} Contains the stats + * @private + */ +function calculateStatsPerRun(results) { + const stat = { + errorCount: 0, + fatalErrorCount: 0, + warningCount: 0, + fixableErrorCount: 0, + fixableWarningCount: 0, + }; + + for (let i = 0; i < results.length; i++) { + const result = results[i]; + + stat.errorCount += result.errorCount; + stat.fatalErrorCount += result.fatalErrorCount; + stat.warningCount += result.warningCount; + stat.fixableErrorCount += result.fixableErrorCount; + stat.fixableWarningCount += result.fixableWarningCount; + } + + return stat; +} + +/** + * Processes an source code using ESLint. + * @param {Object} config The config object. + * @param {string} config.text The source code to verify. + * @param {string} config.cwd The path to the current working directory. + * @param {string|undefined} config.filePath The path to the file of `text`. If this is undefined, it uses ``. + * @param {ConfigArray} config.config The config. + * @param {boolean} config.fix If `true` then it does fix. + * @param {boolean} config.allowInlineConfig If `true` then it uses directive comments. + * @param {boolean|string} config.reportUnusedDisableDirectives If `true`, `"error"` or '"warn"', then it reports unused `eslint-disable` comments. + * @param {FileEnumerator} config.fileEnumerator The file enumerator to check if a path is a target or not. + * @param {Linter} config.linter The linter instance to verify. + * @returns {LintResult} The result of linting. + * @private + */ +function verifyText({ + text, + cwd, + filePath: providedFilePath, + config, + fix, + allowInlineConfig, + reportUnusedDisableDirectives, + fileEnumerator, + linter, +}) { + const filePath = providedFilePath || ""; + + debug(`Lint ${filePath}`); + + /* + * Verify. + * `config.extractConfig(filePath)` requires an absolute path, but `linter` + * doesn't know CWD, so it gives `linter` an absolute path always. + */ + const filePathToVerify = + filePath === "" ? path.join(cwd, filePath) : filePath; + const { fixed, messages, output } = linter.verifyAndFix(text, config, { + allowInlineConfig, + filename: filePathToVerify, + fix, + reportUnusedDisableDirectives, + + /** + * Check if the linter should adopt a given code block or not. + * @param {string} blockFilename The virtual filename of a code block. + * @returns {boolean} `true` if the linter should adopt the code block. + */ + filterCodeBlock(blockFilename) { + return fileEnumerator.isTargetPath(blockFilename); + }, + }); + + // Tweak and return. + const result = { + filePath, + messages, + suppressedMessages: linter.getSuppressedMessages(), + ...calculateStatsPerFile(messages), + }; + + if (fixed) { + result.output = output; + } + if ( + result.errorCount + result.warningCount > 0 && + typeof result.output === "undefined" + ) { + result.source = text; + } + + return result; +} + +/** + * Returns result with warning by ignore settings + * @param {string} filePath File path of checked code + * @param {string} baseDir Absolute path of base directory + * @returns {LintResult} Result with single warning + * @private + */ +function createIgnoreResult(filePath, baseDir) { + let message; + const isHidden = filePath + .split(path.sep) + .find(segment => /^\./u.test(segment)); + const isInNodeModules = + baseDir && path.relative(baseDir, filePath).startsWith("node_modules"); + + if (isHidden) { + message = + "File ignored by default. Use a negated ignore pattern (like \"--ignore-pattern '!'\") to override."; + } else if (isInNodeModules) { + message = + "File ignored by default. Use \"--ignore-pattern '!node_modules/*'\" to override."; + } else { + message = + 'File ignored because of a matching ignore pattern. Use "--no-ignore" to override.'; + } + + return { + filePath: path.resolve(filePath), + messages: [ + { + ruleId: null, + fatal: false, + severity: 1, + message, + nodeType: null, + }, + ], + suppressedMessages: [], + errorCount: 0, + fatalErrorCount: 0, + warningCount: 1, + fixableErrorCount: 0, + fixableWarningCount: 0, + }; +} + +/** + * Get a rule. + * @param {string} ruleId The rule ID to get. + * @param {ConfigArray[]} configArrays The config arrays that have plugin rules. + * @returns {Rule|null} The rule or null. + */ +function getRule(ruleId, configArrays) { + for (const configArray of configArrays) { + const rule = configArray.pluginRules.get(ruleId); + + if (rule) { + return rule; + } + } + return builtInRules.get(ruleId) || null; +} + +/** + * Checks whether a message's rule type should be fixed. + * @param {LintMessage} message The message to check. + * @param {ConfigArray[]} lastConfigArrays The list of config arrays that the last `executeOnFiles` or `executeOnText` used. + * @param {string[]} fixTypes An array of fix types to check. + * @returns {boolean} Whether the message should be fixed. + */ +function shouldMessageBeFixed(message, lastConfigArrays, fixTypes) { + if (!message.ruleId) { + return fixTypes.has("directive"); + } + + const rule = message.ruleId && getRule(message.ruleId, lastConfigArrays); + + return Boolean(rule && rule.meta && fixTypes.has(rule.meta.type)); +} + +/** + * Collect used deprecated rules. + * @param {ConfigArray[]} usedConfigArrays The config arrays which were used. + * @returns {IterableIterator} Used deprecated rules. + */ +function* iterateRuleDeprecationWarnings(usedConfigArrays) { + const processedRuleIds = new Set(); + + // Flatten used configs. + /** @type {ExtractedConfig[]} */ + const configs = usedConfigArrays.flatMap(getUsedExtractedConfigs); + + // Traverse rule configs. + for (const config of configs) { + for (const [ruleId, ruleConfig] of Object.entries(config.rules)) { + // Skip if it was processed. + if (processedRuleIds.has(ruleId)) { + continue; + } + processedRuleIds.add(ruleId); + + // Skip if it's not used. + if (!ConfigOps.getRuleSeverity(ruleConfig)) { + continue; + } + const rule = getRule(ruleId, usedConfigArrays); + + // Skip if it's not deprecated. + if (!(rule && rule.meta && rule.meta.deprecated)) { + continue; + } + + // This rule was used and deprecated. + yield { + ruleId, + replacedBy: rule.meta.replacedBy || [], + }; + } + } +} + +/** + * Checks if the given message is an error message. + * @param {LintMessage} message The message to check. + * @returns {boolean} Whether or not the message is an error message. + * @private + */ +function isErrorMessage(message) { + return message.severity === 2; +} + +/** + * return the cacheFile to be used by eslint, based on whether the provided parameter is + * a directory or looks like a directory (ends in `path.sep`), in which case the file + * name will be the `cacheFile/.cache_hashOfCWD` + * + * if cacheFile points to a file or looks like a file then it will just use that file + * @param {string} cacheFile The name of file to be used to store the cache + * @param {string} cwd Current working directory + * @returns {string} the resolved path to the cache file + */ +function getCacheFile(cacheFile, cwd) { + /* + * make sure the path separators are normalized for the environment/os + * keeping the trailing path separator if present + */ + const normalizedCacheFile = path.normalize(cacheFile); + + const resolvedCacheFile = path.resolve(cwd, normalizedCacheFile); + const looksLikeADirectory = normalizedCacheFile.slice(-1) === path.sep; + + /** + * return the name for the cache file in case the provided parameter is a directory + * @returns {string} the resolved path to the cacheFile + */ + function getCacheFileForDirectory() { + return path.join(resolvedCacheFile, `.cache_${hash(cwd)}`); + } + + let fileStats; + + try { + fileStats = fs.lstatSync(resolvedCacheFile); + } catch { + fileStats = null; + } + + /* + * in case the file exists we need to verify if the provided path + * is a directory or a file. If it is a directory we want to create a file + * inside that directory + */ + if (fileStats) { + /* + * is a directory or is a file, but the original file the user provided + * looks like a directory but `path.resolve` removed the `last path.sep` + * so we need to still treat this like a directory + */ + if (fileStats.isDirectory() || looksLikeADirectory) { + return getCacheFileForDirectory(); + } + + // is file so just use that file + return resolvedCacheFile; + } + + /* + * here we known the file or directory doesn't exist, + * so we will try to infer if its a directory if it looks like a directory + * for the current operating system. + */ + + // if the last character passed is a path separator we assume is a directory + if (looksLikeADirectory) { + return getCacheFileForDirectory(); + } + + return resolvedCacheFile; +} + +/** + * Convert a string array to a boolean map. + * @param {string[]|null} keys The keys to assign true. + * @param {boolean} defaultValue The default value for each property. + * @param {string} displayName The property name which is used in error message. + * @throws {Error} Requires array. + * @returns {Record} The boolean map. + */ +function toBooleanMap(keys, defaultValue, displayName) { + if (keys && !Array.isArray(keys)) { + throw new Error(`${displayName} must be an array.`); + } + if (keys && keys.length > 0) { + return keys.reduce((map, def) => { + const [key, value] = def.split(":"); + + if (key !== "__proto__") { + map[key] = value === void 0 ? defaultValue : value === "true"; + } + + return map; + }, {}); + } + return void 0; +} + +/** + * Create a config data from CLI options. + * @param {CLIEngineOptions} options The options + * @returns {ConfigData|null} The created config data. + */ +function createConfigDataFromOptions(options) { + const { ignorePattern, parser, parserOptions, plugins, rules } = options; + const env = toBooleanMap(options.envs, true, "envs"); + const globals = toBooleanMap(options.globals, false, "globals"); + + if ( + env === void 0 && + globals === void 0 && + (ignorePattern === void 0 || ignorePattern.length === 0) && + parser === void 0 && + parserOptions === void 0 && + plugins === void 0 && + rules === void 0 + ) { + return null; + } + return { + env, + globals, + ignorePatterns: ignorePattern, + parser, + parserOptions, + plugins, + rules, + }; +} + +/** + * Checks whether a directory exists at the given location + * @param {string} resolvedPath A path from the CWD + * @throws {Error} As thrown by `fs.statSync` or `fs.isDirectory`. + * @returns {boolean} `true` if a directory exists + */ +function directoryExists(resolvedPath) { + try { + return fs.statSync(resolvedPath).isDirectory(); + } catch (error) { + if (error && (error.code === "ENOENT" || error.code === "ENOTDIR")) { + return false; + } + throw error; + } +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Core CLI. + */ +class CLIEngine { + /** + * Creates a new instance of the core CLI engine. + * @param {CLIEngineOptions} providedOptions The options for this instance. + * @param {Object} [additionalData] Additional settings that are not CLIEngineOptions. + * @param {Record|null} [additionalData.preloadedPlugins] Preloaded plugins. + */ + constructor(providedOptions, { preloadedPlugins } = {}) { + const options = Object.assign( + Object.create(null), + defaultOptions, + { cwd: process.cwd() }, + providedOptions, + ); + + if (options.fix === void 0) { + options.fix = false; + } + + const additionalPluginPool = new Map(); + + if (preloadedPlugins) { + for (const [id, plugin] of Object.entries(preloadedPlugins)) { + additionalPluginPool.set(id, plugin); + } + } + + const cacheFilePath = getCacheFile( + options.cacheLocation || options.cacheFile, + options.cwd, + ); + const configArrayFactory = new CascadingConfigArrayFactory({ + additionalPluginPool, + baseConfig: options.baseConfig || null, + cliConfig: createConfigDataFromOptions(options), + cwd: options.cwd, + ignorePath: options.ignorePath, + resolvePluginsRelativeTo: options.resolvePluginsRelativeTo, + rulePaths: options.rulePaths, + specificConfigPath: options.configFile, + useEslintrc: options.useEslintrc, + builtInRules, + loadRules, + getEslintRecommendedConfig: () => + require("@eslint/js").configs.recommended, + getEslintAllConfig: () => require("@eslint/js").configs.all, + }); + const fileEnumerator = new FileEnumerator({ + configArrayFactory, + cwd: options.cwd, + extensions: options.extensions, + globInputPaths: options.globInputPaths, + errorOnUnmatchedPattern: options.errorOnUnmatchedPattern, + ignore: options.ignore, + }); + const lintResultCache = options.cache + ? new LintResultCache(cacheFilePath, options.cacheStrategy) + : null; + const linter = new Linter({ cwd: options.cwd, configType: "eslintrc" }); + + /** @type {ConfigArray[]} */ + const lastConfigArrays = [configArrayFactory.getConfigArrayForFile()]; + + // Store private data. + internalSlotsMap.set(this, { + additionalPluginPool, + cacheFilePath, + configArrayFactory, + defaultIgnores: IgnorePattern.createDefaultIgnore(options.cwd), + fileEnumerator, + lastConfigArrays, + lintResultCache, + linter, + options, + }); + + // setup special filter for fixes + if (options.fix && options.fixTypes && options.fixTypes.length > 0) { + debug(`Using fix types ${options.fixTypes}`); + + // throw an error if any invalid fix types are found + validateFixTypes(options.fixTypes); + + // convert to Set for faster lookup + const fixTypes = new Set(options.fixTypes); + + // save original value of options.fix in case it's a function + const originalFix = + typeof options.fix === "function" ? options.fix : () => true; + + options.fix = message => + shouldMessageBeFixed(message, lastConfigArrays, fixTypes) && + originalFix(message); + } + } + + getRules() { + const { lastConfigArrays } = internalSlotsMap.get(this); + + return new Map( + (function* () { + yield* builtInRules; + + for (const configArray of lastConfigArrays) { + yield* configArray.pluginRules; + } + })(), + ); + } + + /** + * Returns results that only contains errors. + * @param {LintResult[]} results The results to filter. + * @returns {LintResult[]} The filtered results. + */ + static getErrorResults(results) { + const filtered = []; + + results.forEach(result => { + const filteredMessages = result.messages.filter(isErrorMessage); + const filteredSuppressedMessages = + result.suppressedMessages.filter(isErrorMessage); + + if (filteredMessages.length > 0) { + filtered.push({ + ...result, + messages: filteredMessages, + suppressedMessages: filteredSuppressedMessages, + errorCount: filteredMessages.length, + warningCount: 0, + fixableErrorCount: result.fixableErrorCount, + fixableWarningCount: 0, + }); + } + }); + + return filtered; + } + + /** + * Outputs fixes from the given results to files. + * @param {LintReport} report The report object created by CLIEngine. + * @returns {void} + */ + static outputFixes(report) { + report.results + .filter(result => Object.hasOwn(result, "output")) + .forEach(result => { + fs.writeFileSync(result.filePath, result.output); + }); + } + + /** + * Resolves the patterns passed into executeOnFiles() into glob-based patterns + * for easier handling. + * @param {string[]} patterns The file patterns passed on the command line. + * @returns {string[]} The equivalent glob patterns. + */ + resolveFileGlobPatterns(patterns) { + const { options } = internalSlotsMap.get(this); + + if (options.globInputPaths === false) { + return patterns.filter(Boolean); + } + + const extensions = (options.extensions || [".js"]).map(ext => + ext.replace(/^\./u, ""), + ); + const dirSuffix = `/**/*.{${extensions.join(",")}}`; + + return patterns.filter(Boolean).map(pathname => { + const resolvedPath = path.resolve(options.cwd, pathname); + const newPath = directoryExists(resolvedPath) + ? pathname.replace(/[/\\]$/u, "") + dirSuffix + : pathname; + + return path.normalize(newPath).replace(/\\/gu, "/"); + }); + } + + /** + * Executes the current configuration on an array of file and directory names. + * @param {string[]} patterns An array of file and directory names. + * @throws {Error} As may be thrown by `fs.unlinkSync`. + * @returns {LintReport} The results for all files that were linted. + */ + executeOnFiles(patterns) { + const { + cacheFilePath, + fileEnumerator, + lastConfigArrays, + lintResultCache, + linter, + options: { + allowInlineConfig, + cache, + cwd, + fix, + reportUnusedDisableDirectives, + }, + } = internalSlotsMap.get(this); + const results = []; + const startTime = Date.now(); + + // Clear the last used config arrays. + lastConfigArrays.length = 0; + + // Delete cache file; should this do here? + if (!cache) { + try { + fs.unlinkSync(cacheFilePath); + } catch (error) { + const errorCode = error && error.code; + + // Ignore errors when no such file exists or file system is read only (and cache file does not exist) + if ( + errorCode !== "ENOENT" && + !(errorCode === "EROFS" && !fs.existsSync(cacheFilePath)) + ) { + throw error; + } + } + } + + // Iterate source code files. + for (const { config, filePath, ignored } of fileEnumerator.iterateFiles( + patterns, + )) { + if (ignored) { + results.push(createIgnoreResult(filePath, cwd)); + continue; + } + + /* + * Store used configs for: + * - this method uses to collect used deprecated rules. + * - `getRules()` method uses to collect all loaded rules. + * - `--fix-type` option uses to get the loaded rule's meta data. + */ + if (!lastConfigArrays.includes(config)) { + lastConfigArrays.push(config); + } + + // Skip if there is cached result. + if (lintResultCache) { + const cachedResult = lintResultCache.getCachedLintResults( + filePath, + config, + ); + + if (cachedResult) { + const hadMessages = + cachedResult.messages && + cachedResult.messages.length > 0; + + if (hadMessages && fix) { + debug( + `Reprocessing cached file to allow autofix: ${filePath}`, + ); + } else { + debug( + `Skipping file since it hasn't changed: ${filePath}`, + ); + results.push(cachedResult); + continue; + } + } + } + + // Do lint. + const result = verifyText({ + text: fs.readFileSync(filePath, "utf8"), + filePath, + config, + cwd, + fix, + allowInlineConfig, + reportUnusedDisableDirectives, + fileEnumerator, + linter, + }); + + results.push(result); + + /* + * Store the lint result in the LintResultCache. + * NOTE: The LintResultCache will remove the file source and any + * other properties that are difficult to serialize, and will + * hydrate those properties back in on future lint runs. + */ + if (lintResultCache) { + lintResultCache.setCachedLintResults(filePath, config, result); + } + } + + // Persist the cache to disk. + if (lintResultCache) { + lintResultCache.reconcile(); + } + + debug(`Linting complete in: ${Date.now() - startTime}ms`); + let usedDeprecatedRules; + + return { + results, + ...calculateStatsPerRun(results), + + // Initialize it lazily because CLI and `ESLint` API don't use it. + get usedDeprecatedRules() { + if (!usedDeprecatedRules) { + usedDeprecatedRules = Array.from( + iterateRuleDeprecationWarnings(lastConfigArrays), + ); + } + return usedDeprecatedRules; + }, + }; + } + + /** + * Executes the current configuration on text. + * @param {string} text A string of JavaScript code to lint. + * @param {string} [filename] An optional string representing the texts filename. + * @param {boolean} [warnIgnored] Always warn when a file is ignored + * @returns {LintReport} The results for the linting. + */ + executeOnText(text, filename, warnIgnored) { + const { + configArrayFactory, + fileEnumerator, + lastConfigArrays, + linter, + options: { + allowInlineConfig, + cwd, + fix, + reportUnusedDisableDirectives, + }, + } = internalSlotsMap.get(this); + const results = []; + const startTime = Date.now(); + const resolvedFilename = filename && path.resolve(cwd, filename); + + // Clear the last used config arrays. + lastConfigArrays.length = 0; + if (resolvedFilename && this.isPathIgnored(resolvedFilename)) { + if (warnIgnored) { + results.push(createIgnoreResult(resolvedFilename, cwd)); + } + } else { + const config = configArrayFactory.getConfigArrayForFile( + resolvedFilename || "__placeholder__.js", + ); + + /* + * Store used configs for: + * - this method uses to collect used deprecated rules. + * - `getRules()` method uses to collect all loaded rules. + * - `--fix-type` option uses to get the loaded rule's meta data. + */ + lastConfigArrays.push(config); + + // Do lint. + results.push( + verifyText({ + text, + filePath: resolvedFilename, + config, + cwd, + fix, + allowInlineConfig, + reportUnusedDisableDirectives, + fileEnumerator, + linter, + }), + ); + } + + debug(`Linting complete in: ${Date.now() - startTime}ms`); + let usedDeprecatedRules; + + return { + results, + ...calculateStatsPerRun(results), + + // Initialize it lazily because CLI and `ESLint` API don't use it. + get usedDeprecatedRules() { + if (!usedDeprecatedRules) { + usedDeprecatedRules = Array.from( + iterateRuleDeprecationWarnings(lastConfigArrays), + ); + } + return usedDeprecatedRules; + }, + }; + } + + /** + * Returns a configuration object for the given file based on the CLI options. + * This is the same logic used by the ESLint CLI executable to determine + * configuration for each file it processes. + * @param {string} filePath The path of the file to retrieve a config object for. + * @throws {Error} If filepath a directory path. + * @returns {ConfigData} A configuration object for the file. + */ + getConfigForFile(filePath) { + const { configArrayFactory, options } = internalSlotsMap.get(this); + const absolutePath = path.resolve(options.cwd, filePath); + + if (directoryExists(absolutePath)) { + throw Object.assign( + new Error("'filePath' should not be a directory path."), + { messageTemplate: "print-config-with-directory-path" }, + ); + } + + return configArrayFactory + .getConfigArrayForFile(absolutePath) + .extractConfig(absolutePath) + .toCompatibleObjectAsConfigFileContent(); + } + + /** + * Checks if a given path is ignored by ESLint. + * @param {string} filePath The path of the file to check. + * @returns {boolean} Whether or not the given path is ignored. + */ + isPathIgnored(filePath) { + const { + configArrayFactory, + defaultIgnores, + options: { cwd, ignore }, + } = internalSlotsMap.get(this); + const absolutePath = path.resolve(cwd, filePath); + + if (ignore) { + const config = configArrayFactory + .getConfigArrayForFile(absolutePath) + .extractConfig(absolutePath); + const ignores = config.ignores || defaultIgnores; + + return ignores(absolutePath); + } + + return defaultIgnores(absolutePath); + } + + /** + * Returns the formatter representing the given format or null if the `format` is not a string. + * @param {string} [format] The name of the format to load or the path to a + * custom formatter. + * @throws {any} As may be thrown by requiring of formatter + * @returns {(FormatterFunction|null)} The formatter function or null if the `format` is not a string. + */ + getFormatter(format) { + // default is stylish + const resolvedFormatName = format || "stylish"; + + // only strings are valid formatters + if (typeof resolvedFormatName === "string") { + // replace \ with / for Windows compatibility + const normalizedFormatName = resolvedFormatName.replace( + /\\/gu, + "/", + ); + + const slots = internalSlotsMap.get(this); + const cwd = slots ? slots.options.cwd : process.cwd(); + const namespace = naming.getNamespaceFromTerm(normalizedFormatName); + + let formatterPath; + + // if there's a slash, then it's a file (TODO: this check seems dubious for scoped npm packages) + if (!namespace && normalizedFormatName.includes("/")) { + formatterPath = path.resolve(cwd, normalizedFormatName); + } else { + try { + const npmFormat = naming.normalizePackageName( + normalizedFormatName, + "eslint-formatter", + ); + + formatterPath = ModuleResolver.resolve( + npmFormat, + path.join(cwd, "__placeholder__.js"), + ); + } catch { + formatterPath = path.resolve( + __dirname, + "formatters", + normalizedFormatName, + ); + } + } + + try { + return require(formatterPath); + } catch (ex) { + if (removedFormatters.has(format)) { + ex.message = `The ${format} formatter is no longer part of core ESLint. Install it manually with \`npm install -D eslint-formatter-${format}\``; + } else { + ex.message = `There was a problem loading formatter: ${formatterPath}\nError: ${ex.message}`; + } + throw ex; + } + } else { + return null; + } + } +} + +CLIEngine.version = pkg.version; +CLIEngine.getFormatter = CLIEngine.prototype.getFormatter; + +module.exports = { + CLIEngine, + + /** + * Get the internal slots of a given CLIEngine instance for tests. + * @param {CLIEngine} instance The CLIEngine instance to get. + * @returns {CLIEngineInternalSlots} The internal slots. + */ + getCLIEngineInternalSlots(instance) { + return internalSlotsMap.get(instance); + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/cli-engine/file-enumerator.js b/tools/ui/node_modules/eslint/lib/cli-engine/file-enumerator.js new file mode 100644 index 0000000000000000000000000000000000000000..91c4013c995cc2b44d2760410c993a1623312e22 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/cli-engine/file-enumerator.js @@ -0,0 +1,541 @@ +/** + * @fileoverview `FileEnumerator` class. + * + * `FileEnumerator` class has two responsibilities: + * + * 1. Find target files by processing glob patterns. + * 2. Tie each target file and appropriate configuration. + * + * It provides a method: + * + * - `iterateFiles(patterns)` + * Iterate files which are matched by given patterns together with the + * corresponded configuration. This is for `CLIEngine#executeOnFiles()`. + * While iterating files, it loads the configuration file of each directory + * before iterate files on the directory, so we can use the configuration + * files to determine target files. + * + * @example + * const enumerator = new FileEnumerator(); + * const linter = new Linter(); + * + * for (const { config, filePath } of enumerator.iterateFiles(["*.js"])) { + * const code = fs.readFileSync(filePath, "utf8"); + * const messages = linter.verify(code, config, filePath); + * + * console.log(messages); + * } + * + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const fs = require("node:fs"); +const path = require("node:path"); +const getGlobParent = require("glob-parent"); +const isGlob = require("is-glob"); +const escapeRegExp = require("escape-string-regexp"); +const { Minimatch } = require("minimatch"); + +const { + Legacy: { IgnorePattern, CascadingConfigArrayFactory }, +} = require("@eslint/eslintrc"); +const debug = require("debug")("eslint:file-enumerator"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const minimatchOpts = { dot: true, matchBase: true }; +const dotfilesPattern = /(?:^\.|[/\\]\.)[^/\\.].*/u; +const NONE = 0; +const IGNORED_SILENTLY = 1; +const IGNORED = 2; + +// For VSCode intellisense +/** @typedef {ReturnType} ConfigArray */ + +/** + * @typedef {Object} FileEnumeratorOptions + * @property {CascadingConfigArrayFactory} [configArrayFactory] The factory for config arrays. + * @property {string} [cwd] The base directory to start lookup. + * @property {string[]} [extensions] The extensions to match files for directory patterns. + * @property {boolean} [globInputPaths] Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file. + * @property {boolean} [ignore] The flag to check ignored files. + * @property {string[]} [rulePaths] The value of `--rulesdir` option. + */ + +/** + * @typedef {Object} FileAndConfig + * @property {string} filePath The path to a target file. + * @property {ConfigArray} config The config entries of that file. + * @property {boolean} ignored If `true` then this file should be ignored and warned because it was directly specified. + */ + +/** + * @typedef {Object} FileEntry + * @property {string} filePath The path to a target file. + * @property {ConfigArray} config The config entries of that file. + * @property {NONE|IGNORED_SILENTLY|IGNORED} flag The flag. + * - `NONE` means the file is a target file. + * - `IGNORED_SILENTLY` means the file should be ignored silently. + * - `IGNORED` means the file should be ignored and warned because it was directly specified. + */ + +/** + * @typedef {Object} FileEnumeratorInternalSlots + * @property {CascadingConfigArrayFactory} configArrayFactory The factory for config arrays. + * @property {string} cwd The base directory to start lookup. + * @property {RegExp|null} extensionRegExp The RegExp to test if a string ends with specific file extensions. + * @property {boolean} globInputPaths Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file. + * @property {boolean} ignoreFlag The flag to check ignored files. + * @property {(filePath:string, dot:boolean) => boolean} defaultIgnores The default predicate function to ignore files. + */ + +/** @type {WeakMap} */ +const internalSlotsMap = new WeakMap(); + +/** + * Check if a string is a glob pattern or not. + * @param {string} pattern A glob pattern. + * @returns {boolean} `true` if the string is a glob pattern. + */ +function isGlobPattern(pattern) { + return isGlob(path.sep === "\\" ? pattern.replace(/\\/gu, "/") : pattern); +} + +/** + * Get stats of a given path. + * @param {string} filePath The path to target file. + * @throws {Error} As may be thrown by `fs.statSync`. + * @returns {fs.Stats|null} The stats. + * @private + */ +function statSafeSync(filePath) { + try { + return fs.statSync(filePath); + } catch (error) { + /* c8 ignore next */ + if (error.code !== "ENOENT") { + throw error; + } + return null; + } +} + +/** + * Get filenames in a given path to a directory. + * @param {string} directoryPath The path to target directory. + * @throws {Error} As may be thrown by `fs.readdirSync`. + * @returns {import("fs").Dirent[]} The filenames. + * @private + */ +function readdirSafeSync(directoryPath) { + try { + return fs.readdirSync(directoryPath, { withFileTypes: true }); + } catch (error) { + /* c8 ignore next */ + if (error.code !== "ENOENT") { + throw error; + } + return []; + } +} + +/** + * Create a `RegExp` object to detect extensions. + * @param {string[] | null} extensions The extensions to create. + * @returns {RegExp | null} The created `RegExp` object or null. + */ +function createExtensionRegExp(extensions) { + if (extensions) { + const normalizedExts = extensions.map(ext => + escapeRegExp(ext.startsWith(".") ? ext.slice(1) : ext), + ); + + return new RegExp(`.\\.(?:${normalizedExts.join("|")})$`, "u"); + } + return null; +} + +/** + * The error type when no files match a glob. + */ +class NoFilesFoundError extends Error { + /** + * @param {string} pattern The glob pattern which was not found. + * @param {boolean} globDisabled If `true` then the pattern was a glob pattern, but glob was disabled. + */ + constructor(pattern, globDisabled) { + super( + `No files matching '${pattern}' were found${globDisabled ? " (glob was disabled)" : ""}.`, + ); + this.messageTemplate = "file-not-found"; + this.messageData = { pattern, globDisabled }; + } +} + +/** + * The error type when there are files matched by a glob, but all of them have been ignored. + */ +class AllFilesIgnoredError extends Error { + /** + * @param {string} pattern The glob pattern which was not found. + */ + constructor(pattern) { + super(`All files matched by '${pattern}' are ignored.`); + this.messageTemplate = "all-files-ignored"; + this.messageData = { pattern }; + } +} + +/** + * This class provides the functionality that enumerates every file which is + * matched by given glob patterns and that configuration. + */ +class FileEnumerator { + /** + * Initialize this enumerator. + * @param {FileEnumeratorOptions} options The options. + */ + constructor({ + cwd = process.cwd(), + configArrayFactory = new CascadingConfigArrayFactory({ + cwd, + getEslintRecommendedConfig: () => + require("@eslint/js").configs.recommended, + getEslintAllConfig: () => require("@eslint/js").configs.all, + }), + extensions = null, + globInputPaths = true, + errorOnUnmatchedPattern = true, + ignore = true, + } = {}) { + internalSlotsMap.set(this, { + configArrayFactory, + cwd, + defaultIgnores: IgnorePattern.createDefaultIgnore(cwd), + extensionRegExp: createExtensionRegExp(extensions), + globInputPaths, + errorOnUnmatchedPattern, + ignoreFlag: ignore, + }); + } + + /** + * Check if a given file is target or not. + * @param {string} filePath The path to a candidate file. + * @param {ConfigArray} [providedConfig] Optional. The configuration for the file. + * @returns {boolean} `true` if the file is a target. + */ + isTargetPath(filePath, providedConfig) { + const { configArrayFactory, extensionRegExp } = + internalSlotsMap.get(this); + + // If `--ext` option is present, use it. + if (extensionRegExp) { + return extensionRegExp.test(filePath); + } + + // `.js` file is target by default. + if (filePath.endsWith(".js")) { + return true; + } + + // use `overrides[].files` to check additional targets. + const config = + providedConfig || + configArrayFactory.getConfigArrayForFile(filePath, { + ignoreNotFoundError: true, + }); + + return config.isAdditionalTargetPath(filePath); + } + + /** + * Iterate files which are matched by given glob patterns. + * @param {string|string[]} patternOrPatterns The glob patterns to iterate files. + * @throws {NoFilesFoundError|AllFilesIgnoredError} On an unmatched pattern. + * @returns {IterableIterator} The found files. + */ + *iterateFiles(patternOrPatterns) { + const { globInputPaths, errorOnUnmatchedPattern } = + internalSlotsMap.get(this); + const patterns = Array.isArray(patternOrPatterns) + ? patternOrPatterns + : [patternOrPatterns]; + + debug("Start to iterate files: %o", patterns); + + // The set of paths to remove duplicate. + const set = new Set(); + + for (const pattern of patterns) { + let foundRegardlessOfIgnored = false; + let found = false; + + // Skip empty string. + if (!pattern) { + continue; + } + + // Iterate files of this pattern. + for (const { config, filePath, flag } of this._iterateFiles( + pattern, + )) { + foundRegardlessOfIgnored = true; + if (flag === IGNORED_SILENTLY) { + continue; + } + found = true; + + // Remove duplicate paths while yielding paths. + if (!set.has(filePath)) { + set.add(filePath); + yield { + config, + filePath, + ignored: flag === IGNORED, + }; + } + } + + // Raise an error if any files were not found. + if (errorOnUnmatchedPattern) { + if (!foundRegardlessOfIgnored) { + throw new NoFilesFoundError( + pattern, + !globInputPaths && isGlob(pattern), + ); + } + if (!found) { + throw new AllFilesIgnoredError(pattern); + } + } + } + + debug(`Complete iterating files: ${JSON.stringify(patterns)}`); + } + + /** + * Iterate files which are matched by a given glob pattern. + * @param {string} pattern The glob pattern to iterate files. + * @returns {IterableIterator} The found files. + */ + _iterateFiles(pattern) { + const { cwd, globInputPaths } = internalSlotsMap.get(this); + const absolutePath = path.resolve(cwd, pattern); + const isDot = dotfilesPattern.test(pattern); + const stat = statSafeSync(absolutePath); + + if (stat && stat.isDirectory()) { + return this._iterateFilesWithDirectory(absolutePath, isDot); + } + if (stat && stat.isFile()) { + return this._iterateFilesWithFile(absolutePath); + } + if (globInputPaths && isGlobPattern(pattern)) { + return this._iterateFilesWithGlob(pattern, isDot); + } + + return []; + } + + /** + * Iterate a file which is matched by a given path. + * @param {string} filePath The path to the target file. + * @returns {IterableIterator} The found files. + * @private + */ + _iterateFilesWithFile(filePath) { + debug(`File: ${filePath}`); + + const { configArrayFactory } = internalSlotsMap.get(this); + const config = configArrayFactory.getConfigArrayForFile(filePath); + const ignored = this._isIgnoredFile(filePath, { config, direct: true }); + const flag = ignored ? IGNORED : NONE; + + return [{ config, filePath, flag }]; + } + + /** + * Iterate files in a given path. + * @param {string} directoryPath The path to the target directory. + * @param {boolean} dotfiles If `true` then it doesn't skip dot files by default. + * @returns {IterableIterator} The found files. + * @private + */ + _iterateFilesWithDirectory(directoryPath, dotfiles) { + debug(`Directory: ${directoryPath}`); + + return this._iterateFilesRecursive(directoryPath, { + dotfiles, + recursive: true, + selector: null, + }); + } + + /** + * Iterate files which are matched by a given glob pattern. + * @param {string} pattern The glob pattern to iterate files. + * @param {boolean} dotfiles If `true` then it doesn't skip dot files by default. + * @returns {IterableIterator} The found files. + * @private + */ + _iterateFilesWithGlob(pattern, dotfiles) { + debug(`Glob: ${pattern}`); + + const { cwd } = internalSlotsMap.get(this); + const directoryPath = path.resolve(cwd, getGlobParent(pattern)); + const absolutePath = path.resolve(cwd, pattern); + const globPart = absolutePath.slice(directoryPath.length + 1); + + /* + * recursive if there are `**` or path separators in the glob part. + * Otherwise, patterns such as `src/*.js`, it doesn't need recursive. + */ + const recursive = /\*\*|\/|\\/u.test(globPart); + const selector = new Minimatch(absolutePath, minimatchOpts); + + debug(`recursive? ${recursive}`); + + return this._iterateFilesRecursive(directoryPath, { + dotfiles, + recursive, + selector, + }); + } + + /** + * Iterate files in a given path. + * @param {string} directoryPath The path to the target directory. + * @param {Object} options The options to iterate files. + * @param {boolean} [options.dotfiles] If `true` then it doesn't skip dot files by default. + * @param {boolean} [options.recursive] If `true` then it dives into sub directories. + * @param {InstanceType} [options.selector] The matcher to choose files. + * @returns {IterableIterator} The found files. + * @private + */ + *_iterateFilesRecursive(directoryPath, options) { + debug(`Enter the directory: ${directoryPath}`); + const { configArrayFactory } = internalSlotsMap.get(this); + + /** @type {ConfigArray|null} */ + let config = null; + + // Enumerate the files of this directory. + for (const entry of readdirSafeSync(directoryPath)) { + const filePath = path.join(directoryPath, entry.name); + const fileInfo = entry.isSymbolicLink() + ? statSafeSync(filePath) + : entry; + + if (!fileInfo) { + continue; + } + + // Check if the file is matched. + if (fileInfo.isFile()) { + if (!config) { + config = configArrayFactory.getConfigArrayForFile( + filePath, + + /* + * We must ignore `ConfigurationNotFoundError` at this + * point because we don't know if target files exist in + * this directory. + */ + { ignoreNotFoundError: true }, + ); + } + const matched = options.selector + ? // Started with a glob pattern; choose by the pattern. + options.selector.match(filePath) + : // Started with a directory path; choose by file extensions. + this.isTargetPath(filePath, config); + + if (matched) { + const ignored = this._isIgnoredFile(filePath, { + ...options, + config, + }); + const flag = ignored ? IGNORED_SILENTLY : NONE; + + debug( + `Yield: ${entry.name}${ignored ? " but ignored" : ""}`, + ); + yield { + config: configArrayFactory.getConfigArrayForFile( + filePath, + ), + filePath, + flag, + }; + } else { + debug(`Didn't match: ${entry.name}`); + } + + // Dive into the sub directory. + } else if (options.recursive && fileInfo.isDirectory()) { + if (!config) { + config = configArrayFactory.getConfigArrayForFile( + filePath, + { ignoreNotFoundError: true }, + ); + } + const ignored = this._isIgnoredFile(filePath + path.sep, { + ...options, + config, + }); + + if (!ignored) { + yield* this._iterateFilesRecursive(filePath, options); + } + } + } + + debug(`Leave the directory: ${directoryPath}`); + } + + /** + * Check if a given file should be ignored. + * @param {string} filePath The path to a file to check. + * @param {Object} options Options + * @param {ConfigArray} [options.config] The config for this file. + * @param {boolean} [options.dotfiles] If `true` then this is not ignore dot files by default. + * @param {boolean} [options.direct] If `true` then this is a direct specified file. + * @returns {boolean} `true` if the file should be ignored. + * @private + */ + _isIgnoredFile( + filePath, + { config: providedConfig, dotfiles = false, direct = false }, + ) { + const { configArrayFactory, defaultIgnores, ignoreFlag } = + internalSlotsMap.get(this); + + if (ignoreFlag) { + const config = + providedConfig || + configArrayFactory.getConfigArrayForFile(filePath, { + ignoreNotFoundError: true, + }); + const ignores = + config.extractConfig(filePath).ignores || defaultIgnores; + + return ignores(filePath, dotfiles); + } + + return !direct && defaultIgnores(filePath, dotfiles); + } +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = { FileEnumerator }; diff --git a/tools/ui/node_modules/eslint/lib/cli-engine/formatters/formatters-meta.json b/tools/ui/node_modules/eslint/lib/cli-engine/formatters/formatters-meta.json new file mode 100644 index 0000000000000000000000000000000000000000..cf32052912494a421c515b6ce0192090575eaa7d --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/cli-engine/formatters/formatters-meta.json @@ -0,0 +1,18 @@ +[ + { + "name": "html", + "description": "Outputs results to HTML. The `html` formatter is useful for visual presentation in the browser." + }, + { + "name": "json-with-metadata", + "description": "Outputs JSON-serialized results. The `json-with-metadata` provides the same linting results as the [`json`](#json) formatter with additional metadata about the rules applied. The linting results are included in the `results` property and the rules metadata is included in the `metadata` property.\n\nAlternatively, you can use the [ESLint Node.js API](../../integrate/nodejs-api) to programmatically use ESLint." + }, + { + "name": "json", + "description": "Outputs JSON-serialized results. The `json` formatter is useful when you want to programmatically work with the CLI's linting results.\n\nAlternatively, you can use the [ESLint Node.js API](../../integrate/nodejs-api) to programmatically use ESLint." + }, + { + "name": "stylish", + "description": "Human-readable output format. This is the default formatter." + } +] diff --git a/tools/ui/node_modules/eslint/lib/cli-engine/formatters/html.js b/tools/ui/node_modules/eslint/lib/cli-engine/formatters/html.js new file mode 100644 index 0000000000000000000000000000000000000000..ef8d445ab796e09cdb25043b4e7ce24a5c1a60b5 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/cli-engine/formatters/html.js @@ -0,0 +1,359 @@ +/** + * @fileoverview HTML reporter + * @author Julian Laval + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const encodeHTML = (function () { + const encodeHTMLRules = { + "&": "&", + "<": "<", + ">": ">", + '"': """, + "'": "'", + }; + const matchHTML = /[&<>"']/gu; + + return function (code) { + return code + ? code.toString().replace(matchHTML, m => encodeHTMLRules[m] || m) + : ""; + }; +})(); + +/** + * Get the final HTML document. + * @param {Object} it data for the document. + * @returns {string} HTML document. + */ +function pageTemplate(it) { + const { reportColor, reportSummary, date, results } = it; + + return ` + + + + + ESLint Report + + + + + +
+

ESLint Report

+
+ ${reportSummary} - Generated on ${date} +
+
+ + + ${results} + +
+ + + +`.trimStart(); +} + +/** + * Given a word and a count, append an s if count is not one. + * @param {string} word A word in its singular form. + * @param {number} count A number controlling whether word should be pluralized. + * @returns {string} The original word with an s on the end if count is not one. + */ +function pluralize(word, count) { + return count === 1 ? word : `${word}s`; +} + +/** + * Renders text along the template of x problems (x errors, x warnings) + * @param {string} totalErrors Total errors + * @param {string} totalWarnings Total warnings + * @returns {string} The formatted string, pluralized where necessary + */ +function renderSummary(totalErrors, totalWarnings) { + const totalProblems = totalErrors + totalWarnings; + let renderedText = `${totalProblems} ${pluralize("problem", totalProblems)}`; + + if (totalProblems !== 0) { + renderedText += ` (${totalErrors} ${pluralize("error", totalErrors)}, ${totalWarnings} ${pluralize("warning", totalWarnings)})`; + } + return renderedText; +} + +/** + * Get the color based on whether there are errors/warnings... + * @param {string} totalErrors Total errors + * @param {string} totalWarnings Total warnings + * @returns {number} The color code (0 = green, 1 = yellow, 2 = red) + */ +function renderColor(totalErrors, totalWarnings) { + if (totalErrors !== 0) { + return 2; + } + if (totalWarnings !== 0) { + return 1; + } + return 0; +} + +/** + * Get HTML (table row) describing a single message. + * @param {Object} it data for the message. + * @returns {string} HTML (table row) describing the message. + */ +function messageTemplate(it) { + const { + parentIndex, + lineNumber, + columnNumber, + severityNumber, + severityName, + message, + ruleUrl, + ruleId, + } = it; + + return ` + + ${lineNumber}:${columnNumber} + ${severityName} + ${encodeHTML(message)} + + ${ruleId ? ruleId : ""} + + +`.trimStart(); +} + +/** + * Get HTML (table rows) describing the messages. + * @param {Array} messages Messages. + * @param {number} parentIndex Index of the parent HTML row. + * @param {Object} rulesMeta Dictionary containing metadata for each rule executed by the analysis. + * @returns {string} HTML (table rows) describing the messages. + */ +function renderMessages(messages, parentIndex, rulesMeta) { + /** + * Get HTML (table row) describing a message. + * @param {Object} message Message. + * @returns {string} HTML (table row) describing a message. + */ + return messages + .map(message => { + const lineNumber = message.line || 0; + const columnNumber = message.column || 0; + let ruleUrl; + + if (rulesMeta) { + const meta = rulesMeta[message.ruleId]; + + if (meta && meta.docs && meta.docs.url) { + ruleUrl = meta.docs.url; + } + } + + return messageTemplate({ + parentIndex, + lineNumber, + columnNumber, + severityNumber: message.severity, + severityName: message.severity === 1 ? "Warning" : "Error", + message: message.message, + ruleId: message.ruleId, + ruleUrl, + }); + }) + .join("\n"); +} + +/** + * Get HTML (table row) describing the result for a single file. + * @param {Object} it data for the file. + * @returns {string} HTML (table row) describing the result for the file. + */ +function resultTemplate(it) { + const { color, index, filePath, summary } = it; + + return ` + + + [+] ${encodeHTML(filePath)} + ${encodeHTML(summary)} + + +`.trimStart(); +} + +/** + * Render the results. + * @param {Array} results Test results. + * @param {Object} rulesMeta Dictionary containing metadata for each rule executed by the analysis. + * @returns {string} HTML string describing the results. + */ +function renderResults(results, rulesMeta) { + return results + .map( + (result, index) => + resultTemplate({ + index, + color: renderColor(result.errorCount, result.warningCount), + filePath: result.filePath, + summary: renderSummary( + result.errorCount, + result.warningCount, + ), + }) + renderMessages(result.messages, index, rulesMeta), + ) + .join("\n"); +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = function (results, data) { + let totalErrors, totalWarnings; + + const metaData = data ? data.rulesMeta : {}; + + totalErrors = 0; + totalWarnings = 0; + + // Iterate over results to get totals + results.forEach(result => { + totalErrors += result.errorCount; + totalWarnings += result.warningCount; + }); + + return pageTemplate({ + date: new Date(), + reportColor: renderColor(totalErrors, totalWarnings), + reportSummary: renderSummary(totalErrors, totalWarnings), + results: renderResults(results, metaData), + }); +}; diff --git a/tools/ui/node_modules/eslint/lib/cli-engine/formatters/json-with-metadata.js b/tools/ui/node_modules/eslint/lib/cli-engine/formatters/json-with-metadata.js new file mode 100644 index 0000000000000000000000000000000000000000..44c785c7417533f6eb0d63c3ef9762fbb1226892 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/cli-engine/formatters/json-with-metadata.js @@ -0,0 +1,16 @@ +/** + * @fileoverview JSON reporter, including rules metadata + * @author Chris Meyer + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = function (results, data) { + return JSON.stringify({ + results, + metadata: data, + }); +}; diff --git a/tools/ui/node_modules/eslint/lib/cli-engine/formatters/json.js b/tools/ui/node_modules/eslint/lib/cli-engine/formatters/json.js new file mode 100644 index 0000000000000000000000000000000000000000..230f5c5876de50104a1bf3df8957b5213e1a82ed --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/cli-engine/formatters/json.js @@ -0,0 +1,13 @@ +/** + * @fileoverview JSON reporter + * @author Burak Yigit Kaya aka BYK + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = function (results) { + return JSON.stringify(results); +}; diff --git a/tools/ui/node_modules/eslint/lib/cli-engine/formatters/stylish.js b/tools/ui/node_modules/eslint/lib/cli-engine/formatters/stylish.js new file mode 100644 index 0000000000000000000000000000000000000000..18aa58154e7b863d13ab2b11d861dcc43eff11e7 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/cli-engine/formatters/stylish.js @@ -0,0 +1,122 @@ +/** + * @fileoverview Stylish reporter + * @author Sindre Sorhus + */ +"use strict"; + +const chalk = require("chalk"), + util = require("node:util"), + table = require("../../shared/text-table"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Given a word and a count, append an s if count is not one. + * @param {string} word A word in its singular form. + * @param {number} count A number controlling whether word should be pluralized. + * @returns {string} The original word with an s on the end if count is not one. + */ +function pluralize(word, count) { + return count === 1 ? word : `${word}s`; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = function (results) { + let output = "\n", + errorCount = 0, + warningCount = 0, + fixableErrorCount = 0, + fixableWarningCount = 0, + summaryColor = "yellow"; + + results.forEach(result => { + const messages = result.messages; + + if (messages.length === 0) { + return; + } + + errorCount += result.errorCount; + warningCount += result.warningCount; + fixableErrorCount += result.fixableErrorCount; + fixableWarningCount += result.fixableWarningCount; + + output += `${chalk.underline(result.filePath)}\n`; + + output += `${table( + messages.map(message => { + let messageType; + + if (message.fatal || message.severity === 2) { + messageType = chalk.red("error"); + summaryColor = "red"; + } else { + messageType = chalk.yellow("warning"); + } + + return [ + "", + String(message.line || 0), + String(message.column || 0), + messageType, + message.message.replace(/([^ ])\.$/u, "$1"), + chalk.dim(message.ruleId || ""), + ]; + }), + { + align: ["", "r", "l"], + stringLength(str) { + return util.stripVTControlCharacters(str).length; + }, + }, + ) + .split("\n") + .map(el => + el.replace(/(\d+)\s+(\d+)/u, (m, p1, p2) => + chalk.dim(`${p1}:${p2}`), + ), + ) + .join("\n")}\n\n`; + }); + + const total = errorCount + warningCount; + + if (total > 0) { + output += chalk[summaryColor].bold( + [ + "\u2716 ", + total, + pluralize(" problem", total), + " (", + errorCount, + pluralize(" error", errorCount), + ", ", + warningCount, + pluralize(" warning", warningCount), + ")\n", + ].join(""), + ); + + if (fixableErrorCount > 0 || fixableWarningCount > 0) { + output += chalk[summaryColor].bold( + [ + " ", + fixableErrorCount, + pluralize(" error", fixableErrorCount), + " and ", + fixableWarningCount, + pluralize(" warning", fixableWarningCount), + " potentially fixable with the `--fix` option.\n", + ].join(""), + ); + } + } + + // Resets output color, for prevent change on top level + return total > 0 ? chalk.reset(output) : ""; +}; diff --git a/tools/ui/node_modules/eslint/lib/cli-engine/hash.js b/tools/ui/node_modules/eslint/lib/cli-engine/hash.js new file mode 100644 index 0000000000000000000000000000000000000000..4c306b9b4d6b928f356eba6d3fcc439a43db4720 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/cli-engine/hash.js @@ -0,0 +1,35 @@ +/** + * @fileoverview Defining the hashing function in one place. + * @author Michael Ficarra + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const murmur = require("imurmurhash"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ + +/** + * hash the given string + * @param {string} str the string to hash + * @returns {string} the hash + */ +function hash(str) { + return murmur(str).result().toString(36); +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = hash; diff --git a/tools/ui/node_modules/eslint/lib/cli-engine/index.js b/tools/ui/node_modules/eslint/lib/cli-engine/index.js new file mode 100644 index 0000000000000000000000000000000000000000..bba3fb0b8ad7a2437c36541aa8e0b773f1b360ff --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/cli-engine/index.js @@ -0,0 +1,7 @@ +"use strict"; + +const { CLIEngine } = require("./cli-engine"); + +module.exports = { + CLIEngine, +}; diff --git a/tools/ui/node_modules/eslint/lib/cli-engine/lint-result-cache.js b/tools/ui/node_modules/eslint/lib/cli-engine/lint-result-cache.js new file mode 100644 index 0000000000000000000000000000000000000000..48f42e19b8ccd7eac2e00fd1958355f6e4dc4f56 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/cli-engine/lint-result-cache.js @@ -0,0 +1,220 @@ +/** + * @fileoverview Utility for caching lint results. + * @author Kevin Partington + */ +"use strict"; + +//----------------------------------------------------------------------------- +// Requirements +//----------------------------------------------------------------------------- + +const fs = require("node:fs"); +const fileEntryCache = require("file-entry-cache"); +const stringify = require("json-stable-stringify-without-jsonify"); +const pkg = require("../../package.json"); +const assert = require("../shared/assert"); +const hash = require("./hash"); + +const debug = require("debug")("eslint:lint-result-cache"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** @typedef {import("../types").Linter.Config} Config */ + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +const configHashCache = new WeakMap(); +const nodeVersion = process && process.version; + +const validCacheStrategies = ["metadata", "content"]; +const invalidCacheStrategyErrorMessage = `Cache strategy must be one of: ${validCacheStrategies + .map(strategy => `"${strategy}"`) + .join(", ")}`; + +/** + * Tests whether a provided cacheStrategy is valid + * @param {string} cacheStrategy The cache strategy to use + * @returns {boolean} true if `cacheStrategy` is one of `validCacheStrategies`; false otherwise + */ +function isValidCacheStrategy(cacheStrategy) { + return validCacheStrategies.includes(cacheStrategy); +} + +/** + * Calculates the hash of the config + * @param {Config} config The config. + * @returns {string} The hash of the config + */ +function hashOfConfigFor(config) { + if (!configHashCache.has(config)) { + configHashCache.set( + config, + hash(`${pkg.version}_${nodeVersion}_${stringify(config)}`), + ); + } + + return configHashCache.get(config); +} + +//----------------------------------------------------------------------------- +// Public Interface +//----------------------------------------------------------------------------- + +/** + * Lint result cache. This wraps around the file-entry-cache module, + * transparently removing properties that are difficult or expensive to + * serialize and adding them back in on retrieval. + */ +class LintResultCache { + /** + * Creates a new LintResultCache instance. + * @param {string} cacheFileLocation The cache file location. + * @param {"metadata" | "content"} cacheStrategy The cache strategy to use. + */ + constructor(cacheFileLocation, cacheStrategy) { + assert(cacheFileLocation, "Cache file location is required"); + assert(cacheStrategy, "Cache strategy is required"); + assert( + isValidCacheStrategy(cacheStrategy), + invalidCacheStrategyErrorMessage, + ); + + debug(`Caching results to ${cacheFileLocation}`); + + const useChecksum = cacheStrategy === "content"; + + debug(`Using "${cacheStrategy}" strategy to detect changes`); + + this.fileEntryCache = fileEntryCache.create( + cacheFileLocation, + void 0, + useChecksum, + ); + this.cacheFileLocation = cacheFileLocation; + } + + /** + * Retrieve cached lint results for a given file path, if present in the + * cache. If the file is present and has not been changed, rebuild any + * missing result information. + * @param {string} filePath The file for which to retrieve lint results. + * @param {Config} config The config of the file. + * @returns {Object|null} The rebuilt lint results, or null if the file is + * changed or not in the filesystem. + */ + getCachedLintResults(filePath, config) { + const cachedResults = this.getValidCachedLintResults(filePath, config); + + if (!cachedResults) { + return cachedResults; + } + + /* + * Shallow clone the object to ensure that any properties added or modified afterwards + * will not be accidentally stored in the cache file when `reconcile()` is called. + * https://github.com/eslint/eslint/issues/13507 + * All intentional changes to the cache file must be done through `setCachedLintResults()`. + */ + const results = { ...cachedResults }; + + // If source is present but null, need to reread the file from the filesystem. + if (results.source === null) { + debug( + `Rereading cached result source from filesystem: ${filePath}`, + ); + results.source = fs.readFileSync(filePath, "utf-8"); + } + + return results; + } + + /** + * Retrieve cached lint results for a given file path, if present in the + * cache and still valid. + * @param {string} filePath The file for which to retrieve lint results. + * @param {Config} config The config of the file. + * @returns {Object|null} The cached lint results if present in the cache + * and still valid; null otherwise. + */ + getValidCachedLintResults(filePath, config) { + /* + * Cached lint results are valid if and only if: + * 1. The file is present in the filesystem + * 2. The file has not changed since the time it was previously linted + * 3. The ESLint configuration has not changed since the time the file + * was previously linted + * If any of these are not true, we will not reuse the lint results. + */ + const fileDescriptor = this.fileEntryCache.getFileDescriptor(filePath); + + if (fileDescriptor.notFound) { + debug(`File not found on the file system: ${filePath}`); + return null; + } + + const hashOfConfig = hashOfConfigFor(config); + const changed = + fileDescriptor.changed || + fileDescriptor.meta.hashOfConfig !== hashOfConfig; + + if (changed) { + debug(`Cache entry not found or no longer valid: ${filePath}`); + return null; + } + + return fileDescriptor.meta.results; + } + + /** + * Set the cached lint results for a given file path, after removing any + * information that will be both unnecessary and difficult to serialize. + * Avoids caching results with an "output" property (meaning fixes were + * applied), to prevent potentially incorrect results if fixes are not + * written to disk. + * @param {string} filePath The file for which to set lint results. + * @param {Config} config The config of the file. + * @param {Object} result The lint result to be set for the file. + * @returns {void} + */ + setCachedLintResults(filePath, config, result) { + if (result && Object.hasOwn(result, "output")) { + return; + } + + const fileDescriptor = this.fileEntryCache.getFileDescriptor(filePath); + + if (fileDescriptor && !fileDescriptor.notFound) { + debug(`Updating cached result: ${filePath}`); + + // Serialize the result, except that we want to remove the file source if present. + const resultToSerialize = Object.assign({}, result); + + /* + * Set result.source to null. + * In `getCachedLintResults`, if source is explicitly null, we will + * read the file from the filesystem to set the value again. + */ + if (Object.hasOwn(resultToSerialize, "source")) { + resultToSerialize.source = null; + } + + fileDescriptor.meta.results = resultToSerialize; + fileDescriptor.meta.hashOfConfig = hashOfConfigFor(config); + } + } + + /** + * Persists the in-memory cache to disk. + * @returns {void} + */ + reconcile() { + debug(`Persisting cached results: ${this.cacheFileLocation}`); + this.fileEntryCache.reconcile(); + } +} + +module.exports = LintResultCache; diff --git a/tools/ui/node_modules/eslint/lib/cli-engine/load-rules.js b/tools/ui/node_modules/eslint/lib/cli-engine/load-rules.js new file mode 100644 index 0000000000000000000000000000000000000000..5a7dc3498a7b38a13353d8039c6e99089501a928 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/cli-engine/load-rules.js @@ -0,0 +1,46 @@ +/** + * @fileoverview Module for loading rules from files and directories. + * @author Michael Ficarra + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const fs = require("node:fs"), + path = require("node:path"); + +const rulesDirCache = {}; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Load all rule modules from specified directory. + * @param {string} relativeRulesDir Path to rules directory, may be relative. + * @param {string} cwd Current working directory + * @returns {Object} Loaded rule modules. + */ +module.exports = function (relativeRulesDir, cwd) { + const rulesDir = path.resolve(cwd, relativeRulesDir); + + // cache will help performance as IO operation are expensive + if (rulesDirCache[rulesDir]) { + return rulesDirCache[rulesDir]; + } + + const rules = Object.create(null); + + fs.readdirSync(rulesDir).forEach(file => { + if (path.extname(file) !== ".js") { + return; + } + rules[file.slice(0, -3)] = require(path.join(rulesDir, file)); + }); + rulesDirCache[rulesDir] = rules; + + return rules; +}; diff --git a/tools/ui/node_modules/eslint/lib/cli.js b/tools/ui/node_modules/eslint/lib/cli.js new file mode 100644 index 0000000000000000000000000000000000000000..4e81721a92bcb8275f10725e3b570479d77987c8 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/cli.js @@ -0,0 +1,553 @@ +/** + * @fileoverview Main CLI object. + * @author Nicholas C. Zakas + */ + +"use strict"; + +/* + * NOTE: The CLI object should *not* call process.exit() directly. It should only return + * exit codes. This allows other programs to use the CLI object and still control + * when the program exits. + */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const fs = require("node:fs"), + { mkdir, stat, writeFile } = require("node:fs/promises"), + path = require("node:path"), + { pathToFileURL } = require("node:url"), + { LegacyESLint } = require("./eslint"), + { + ESLint, + shouldUseFlatConfig, + locateConfigFileToUse, + } = require("./eslint/eslint"), + createCLIOptions = require("./options"), + log = require("./shared/logging"), + RuntimeInfo = require("./shared/runtime-info"), + translateOptions = require("./shared/translate-cli-options"); +const { getCacheFile } = require("./eslint/eslint-helpers"); +const { SuppressionsService } = require("./services/suppressions-service"); +const debug = require("debug")("eslint:cli"); + +//------------------------------------------------------------------------------ +// Types +//------------------------------------------------------------------------------ + +/** @typedef {import("./options").ParsedCLIOptions} ParsedCLIOptions */ +/** @typedef {import("./types").ESLint.LintResult} LintResult */ +/** @typedef {import("./types").ESLint.ResultsMeta} ResultsMeta */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Count error messages. + * @param {LintResult[]} results The lint results. + * @returns {{errorCount:number;fatalErrorCount:number,warningCount:number}} The number of error messages. + */ +function countErrors(results) { + let errorCount = 0; + let fatalErrorCount = 0; + let warningCount = 0; + + for (const result of results) { + errorCount += result.errorCount; + fatalErrorCount += result.fatalErrorCount; + warningCount += result.warningCount; + } + + return { errorCount, fatalErrorCount, warningCount }; +} + +/** + * Creates an options module from the provided CLI options and encodes it as a data URL. + * @param {ParsedCLIOptions} options The CLI options. + * @returns {URL} The URL of the options module. + */ +function createOptionsModule(options) { + const translateOptionsFileURL = new URL( + "./shared/translate-cli-options.js", + pathToFileURL(__filename), + ).href; + const optionsSrc = + `import translateOptions from ${JSON.stringify(translateOptionsFileURL)};\n` + + `export default await translateOptions(${JSON.stringify(options)}, "flat");\n`; + + // Base64 encoding is typically shorter than URL encoding + return new URL( + `data:text/javascript;base64,${Buffer.from(optionsSrc).toString("base64")}`, + ); +} + +/** + * Check if a given file path is a directory or not. + * @param {string} filePath The path to a file to check. + * @returns {Promise} `true` if the given path is a directory. + */ +async function isDirectory(filePath) { + try { + return (await stat(filePath)).isDirectory(); + } catch (error) { + if (error.code === "ENOENT" || error.code === "ENOTDIR") { + return false; + } + throw error; + } +} + +/** + * Outputs the results of the linting. + * @param {ESLint} engine The ESLint instance to use. + * @param {LintResult[]} results The results to print. + * @param {string} format The name of the formatter to use or the path to the formatter. + * @param {string} outputFile The path for the output file. + * @param {ResultsMeta} resultsMeta Warning count and max threshold. + * @returns {Promise} True if the printing succeeds, false if not. + * @private + */ +async function printResults(engine, results, format, outputFile, resultsMeta) { + let formatter; + + try { + formatter = await engine.loadFormatter(format); + } catch (e) { + log.error(e.message); + return false; + } + + const output = await formatter.format(results, resultsMeta); + + if (outputFile) { + const filePath = path.resolve(process.cwd(), outputFile); + + if (await isDirectory(filePath)) { + log.error( + "Cannot write to output file path, it is a directory: %s", + outputFile, + ); + return false; + } + + try { + await mkdir(path.dirname(filePath), { recursive: true }); + await writeFile(filePath, output); + } catch (ex) { + log.error("There was a problem writing the output file:\n%s", ex); + return false; + } + } else if (output) { + log.info(output); + } + + return true; +} + +/** + * Validates the `--concurrency` flag value. + * @param {string} concurrency The `--concurrency` flag value to validate. + * @returns {void} + * @throws {Error} If the `--concurrency` flag value is invalid. + */ +function validateConcurrency(concurrency) { + if ( + concurrency === void 0 || + concurrency === "auto" || + concurrency === "off" + ) { + return; + } + + const concurrencyValue = Number(concurrency); + + if (!Number.isInteger(concurrencyValue) || concurrencyValue < 1) { + throw new Error( + `Option concurrency: '${concurrency}' is not a positive integer, 'auto' or 'off'.`, + ); + } +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Encapsulates all CLI behavior for eslint. Makes it easier to test as well as + * for other Node.js programs to effectively run the CLI. + */ +const cli = { + /** + * Calculates the command string for the --inspect-config operation. + * @param {string} configFile The path to the config file to inspect. + * @returns {Promise} The command string to execute. + */ + async calculateInspectConfigFlags(configFile) { + // find the config file + const { configFilePath, basePath } = await locateConfigFileToUse({ + cwd: process.cwd(), + configFile, + }); + + return ["--config", configFilePath, "--basePath", basePath]; + }, + + /** + * Executes the CLI based on an array of arguments that is passed in. + * @param {string|Array|Object} args The arguments to process. + * @param {string} [text] The text to lint (used for TTY). + * @param {boolean} [allowFlatConfig=true] Whether or not to allow flat config. + * @returns {Promise} The exit code for the operation. + */ + async execute(args, text, allowFlatConfig = true) { + if (Array.isArray(args)) { + debug("CLI args: %o", args.slice(2)); + } + + /* + * Before doing anything, we need to see if we are using a + * flat config file. If so, then we need to change the way command + * line args are parsed. This is temporary, and when we fully + * switch to flat config we can remove this logic. + */ + + const usingFlatConfig = + allowFlatConfig && (await shouldUseFlatConfig()); + + debug("Using flat config?", usingFlatConfig); + + if (allowFlatConfig && !usingFlatConfig) { + const { WarningService } = require("./services/warning-service"); + new WarningService().emitESLintRCWarning(); + } + + const CLIOptions = createCLIOptions(usingFlatConfig); + + /** @type {ParsedCLIOptions} */ + let options; + + try { + options = CLIOptions.parse(args); + validateConcurrency(options.concurrency); + } catch (error) { + debug("Error parsing CLI options:", error.message); + + let errorMessage = error.message; + + if (usingFlatConfig) { + errorMessage += + "\nYou're using eslint.config.js, some command line flags are no longer available. Please see https://eslint.org/docs/latest/use/command-line-interface for details."; + } + + log.error(errorMessage); + return 2; + } + + const files = options._; + const useStdin = typeof text === "string"; + + if (options.help) { + log.info(CLIOptions.generateHelp()); + return 0; + } + if (options.version) { + log.info(RuntimeInfo.version()); + return 0; + } + if (options.envInfo) { + try { + log.info(RuntimeInfo.environment()); + return 0; + } catch (err) { + debug("Error retrieving environment info"); + log.error(err.message); + return 2; + } + } + + if (options.printConfig) { + if (files.length) { + log.error( + "The --print-config option must be used with exactly one file name.", + ); + return 2; + } + if (useStdin) { + log.error( + "The --print-config option is not available for piped-in code.", + ); + return 2; + } + + const engine = usingFlatConfig + ? new ESLint(await translateOptions(options, "flat")) + : new LegacyESLint(await translateOptions(options)); + const fileConfig = await engine.calculateConfigForFile( + options.printConfig, + ); + + log.info(JSON.stringify(fileConfig, null, " ")); + return 0; + } + + if (options.inspectConfig) { + log.info( + "You can also run this command directly using 'npx @eslint/config-inspector@latest' in the same directory as your configuration file.", + ); + + try { + const flatOptions = await translateOptions(options, "flat"); + const spawn = require("cross-spawn"); + const flags = await cli.calculateInspectConfigFlags( + flatOptions.overrideConfigFile, + ); + + spawn.sync( + "npx", + ["@eslint/config-inspector@latest", ...flags], + { encoding: "utf8", stdio: "inherit" }, + ); + } catch (error) { + log.error(error); + return 2; + } + + return 0; + } + + debug(`Running on ${useStdin ? "text" : "files"}`); + + if (options.fix && options.fixDryRun) { + log.error( + "The --fix option and the --fix-dry-run option cannot be used together.", + ); + return 2; + } + if (useStdin && options.fix) { + log.error( + "The --fix option is not available for piped-in code; use --fix-dry-run instead.", + ); + return 2; + } + if (options.fixType && !options.fix && !options.fixDryRun) { + log.error( + "The --fix-type option requires either --fix or --fix-dry-run.", + ); + return 2; + } + + if ( + options.reportUnusedDisableDirectives && + options.reportUnusedDisableDirectivesSeverity !== void 0 + ) { + log.error( + "The --report-unused-disable-directives option and the --report-unused-disable-directives-severity option cannot be used together.", + ); + return 2; + } + + if (usingFlatConfig && options.ext) { + // Passing `--ext ""` results in `options.ext` being an empty array. + if (options.ext.length === 0) { + log.error("The --ext option value cannot be empty."); + return 2; + } + + // Passing `--ext ,ts` results in an empty string at index 0. Passing `--ext ts,,tsx` results in an empty string at index 1. + const emptyStringIndex = options.ext.indexOf(""); + + if (emptyStringIndex >= 0) { + log.error( + `The --ext option arguments cannot be empty strings. Found an empty string at index ${emptyStringIndex}.`, + ); + return 2; + } + } + + if (options.suppressAll && options.suppressRule) { + log.error( + "The --suppress-all option and the --suppress-rule option cannot be used together.", + ); + return 2; + } + + if (options.suppressAll && options.pruneSuppressions) { + log.error( + "The --suppress-all option and the --prune-suppressions option cannot be used together.", + ); + return 2; + } + + if (options.suppressRule && options.pruneSuppressions) { + log.error( + "The --suppress-rule option and the --prune-suppressions option cannot be used together.", + ); + return 2; + } + + if ( + useStdin && + (options.suppressAll || + options.suppressRule || + options.pruneSuppressions) + ) { + log.error( + "The --suppress-all, --suppress-rule, and --prune-suppressions options cannot be used with piped-in code.", + ); + return 2; + } + + const ActiveESLint = usingFlatConfig ? ESLint : LegacyESLint; + + /** @type {ESLint|LegacyESLint} */ + let engine; + + if (options.concurrency && options.concurrency !== "off") { + const optionsURL = createOptionsModule(options); + engine = await ESLint.fromOptionsModule(optionsURL); + } else { + const eslintOptions = await translateOptions( + options, + usingFlatConfig ? "flat" : "eslintrc", + ); + engine = new ActiveESLint(eslintOptions); + } + let results; + + if (useStdin) { + results = await engine.lintText(text, { + filePath: options.stdinFilename, + + // flatConfig respects CLI flag and constructor warnIgnored, eslintrc forces true for backwards compatibility + warnIgnored: usingFlatConfig ? void 0 : true, + }); + } else { + results = await engine.lintFiles(files); + } + + if (options.fix) { + debug("Fix mode enabled - applying fixes"); + await ActiveESLint.outputFixes(results); + } + + let unusedSuppressions = {}; + + if (!useStdin) { + const suppressionsFileLocation = getCacheFile( + options.suppressionsLocation || "eslint-suppressions.json", + process.cwd(), + { + prefix: "suppressions_", + }, + ); + + if ( + options.suppressionsLocation && + !fs.existsSync(suppressionsFileLocation) && + !options.suppressAll && + !options.suppressRule + ) { + log.error( + "The suppressions file does not exist. Please run the command with `--suppress-all` or `--suppress-rule` to create it.", + ); + return 2; + } + + if ( + options.suppressAll || + options.suppressRule || + options.pruneSuppressions || + fs.existsSync(suppressionsFileLocation) + ) { + const suppressions = new SuppressionsService({ + filePath: suppressionsFileLocation, + cwd: process.cwd(), + }); + + if (options.suppressAll || options.suppressRule) { + await suppressions.suppress(results, options.suppressRule); + } + + if (options.pruneSuppressions) { + await suppressions.prune(results); + } + + const suppressionResults = suppressions.applySuppressions( + results, + await suppressions.load(), + ); + + results = suppressionResults.results; + unusedSuppressions = suppressionResults.unused; + } + } + + let resultsToPrint = results; + + if (options.quiet) { + debug("Quiet mode enabled - filtering out warnings"); + resultsToPrint = ActiveESLint.getErrorResults(resultsToPrint); + } + + const resultCounts = countErrors(results); + const tooManyWarnings = + options.maxWarnings >= 0 && + resultCounts.warningCount > options.maxWarnings; + const resultsMeta = tooManyWarnings + ? { + maxWarningsExceeded: { + maxWarnings: options.maxWarnings, + foundWarnings: resultCounts.warningCount, + }, + } + : {}; + + if ( + await printResults( + engine, + resultsToPrint, + options.format, + options.outputFile, + resultsMeta, + ) + ) { + // Errors and warnings from the original unfiltered results should determine the exit code + const shouldExitForFatalErrors = + options.exitOnFatalError && resultCounts.fatalErrorCount > 0; + + if (!resultCounts.errorCount && tooManyWarnings) { + log.error( + "ESLint found too many warnings (maximum: %s).", + options.maxWarnings, + ); + } + + if (!options.passOnUnprunedSuppressions) { + const unusedSuppressionsCount = + Object.keys(unusedSuppressions).length; + + if (unusedSuppressionsCount > 0) { + log.error( + "There are suppressions left that do not occur anymore. Consider re-running the command with `--prune-suppressions`.", + ); + debug(JSON.stringify(unusedSuppressions, null, 2)); + + return 2; + } + } + + if (shouldExitForFatalErrors) { + return 2; + } + + return resultCounts.errorCount || tooManyWarnings ? 1 : 0; + } + + return 2; + }, +}; + +module.exports = cli; diff --git a/tools/ui/node_modules/eslint/lib/config-api.js b/tools/ui/node_modules/eslint/lib/config-api.js new file mode 100644 index 0000000000000000000000000000000000000000..5050a631cfb0b1d47e0e3e2c903416f19ea70ffa --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/config-api.js @@ -0,0 +1,12 @@ +/** + * @fileoverview exports for config helpers + * @author Nicholas C. Zakas + */ + +"use strict"; +const { defineConfig, globalIgnores } = require("@eslint/config-helpers"); + +module.exports = { + defineConfig, + globalIgnores, +}; diff --git a/tools/ui/node_modules/eslint/lib/config/config-loader.js b/tools/ui/node_modules/eslint/lib/config/config-loader.js new file mode 100644 index 0000000000000000000000000000000000000000..80dfaeb439f3fdccf543b2cea33b5da440f09285 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/config/config-loader.js @@ -0,0 +1,816 @@ +/** + * @fileoverview Utility to load config files + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const path = require("node:path"); +const fs = require("node:fs/promises"); +const findUp = require("find-up"); +const { pathToFileURL } = require("node:url"); +const debug = require("debug")("eslint:config-loader"); +const { FlatConfigArray } = require("./flat-config-array"); +const { WarningService } = require("../services/warning-service"); + +//----------------------------------------------------------------------------- +// Types +//----------------------------------------------------------------------------- + +/** @typedef {import("../types").Linter.Config} Config */ + +/** + * @typedef {Object} ConfigLoaderOptions + * @property {string|false|undefined} configFile The path to the config file to use. + * @property {string} cwd The current working directory. + * @property {boolean} ignoreEnabled Indicates if ignore patterns should be honored. + * @property {Config|Array} [baseConfig] The base config to use. + * @property {Array} [defaultConfigs] The default configs to use. + * @property {Array} [ignorePatterns] The ignore patterns to use. + * @property {Config|Array} [overrideConfig] The override config to use. + * @property {boolean} [hasUnstableNativeNodeJsTSConfigFlag] The flag to indicate whether the `unstable_native_nodejs_ts_config` flag is enabled. + * @property {WarningService} [warningService] The warning service to use. + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const FLAT_CONFIG_FILENAMES = [ + "eslint.config.js", + "eslint.config.mjs", + "eslint.config.cjs", + "eslint.config.ts", + "eslint.config.mts", + "eslint.config.cts", +]; + +const importedConfigFileModificationTime = new Map(); + +/** + * Asserts that the given file path is valid. + * @param {string} filePath The file path to check. + * @returns {void} + * @throws {Error} If `filePath` is not a non-empty string. + */ +function assertValidFilePath(filePath) { + if (!filePath || typeof filePath !== "string") { + throw new Error("'filePath' must be a non-empty string"); + } +} + +/** + * Asserts that a configuration exists. A configuration exists if any + * of the following are true: + * - `configFilePath` is defined. + * - `useConfigFile` is `false`. + * @param {string|undefined} configFilePath The path to the config file. + * @param {ConfigLoaderOptions} loaderOptions The options to use when loading configuration files. + * @returns {void} + * @throws {Error} If no configuration exists. + */ +function assertConfigurationExists(configFilePath, loaderOptions) { + const { configFile: useConfigFile } = loaderOptions; + + if (!configFilePath && useConfigFile !== false) { + const error = new Error("Could not find config file."); + + error.messageTemplate = "config-file-missing"; + throw error; + } +} + +/** + * Check if the file is a TypeScript file. + * @param {string} filePath The file path to check. + * @returns {boolean} `true` if the file is a TypeScript file, `false` if it's not. + */ +function isFileTS(filePath) { + const fileExtension = path.extname(filePath); + + return /^\.[mc]?ts$/u.test(fileExtension); +} + +/** + * Check if ESLint is running in Bun. + * @returns {boolean} `true` if the ESLint is running Bun, `false` if it's not. + */ +function isRunningInBun() { + return !!globalThis.Bun; +} + +/** + * Check if ESLint is running in Deno. + * @returns {boolean} `true` if the ESLint is running in Deno, `false` if it's not. + */ +function isRunningInDeno() { + return !!globalThis.Deno; +} + +/** + * Checks if native TypeScript support is + * enabled in the current Node.js process. + * + * This function determines if the + * {@linkcode NodeJS.ProcessFeatures.typescript | typescript} + * feature is present in the + * {@linkcode process.features} object + * and if its value is either "strip" or "transform". + * @returns {boolean} `true` if native TypeScript support is enabled, otherwise `false`. + * @since 9.24.0 + */ +function isNativeTypeScriptSupportEnabled() { + return ( + // eslint-disable-next-line n/no-unsupported-features/node-builtins -- it's still an experimental feature. + ["strip", "transform"].includes(process.features.typescript) + ); +} + +/** + * Load the TypeScript configuration file. + * @param {string} filePath The absolute file path to load. + * @param {URL} fileURL The file URL to load. + * @param {number} mtime The last modified timestamp of the file. + * @returns {Promise} The configuration loaded from the file. + * @since 9.24.0 + */ +async function loadTypeScriptConfigFileWithJiti(filePath, fileURL, mtime) { + const { createJiti, version: jitiVersion } = + // eslint-disable-next-line no-use-before-define -- `ConfigLoader.loadJiti` can be overwritten for testing + await ConfigLoader.loadJiti().catch(() => { + throw new Error( + "The 'jiti' library is required for loading TypeScript configuration files. Make sure to install it.", + ); + }); + + // `createJiti` was added in jiti v2. + if (typeof createJiti !== "function") { + throw new Error( + "You are using an outdated version of the 'jiti' library. Please update to the latest version of 'jiti' to ensure compatibility and access to the latest features.", + ); + } + + /* + * Disabling `moduleCache` allows us to reload a + * config file when the last modified timestamp changes. + */ + const jitiOptions = { + moduleCache: false, + }; + + if (jitiVersion.startsWith("2.1.")) { + jitiOptions.interopDefault = false; + } + + const jiti = createJiti(__filename, jitiOptions); + const config = await jiti.import(fileURL.href); + + importedConfigFileModificationTime.set(filePath, mtime); + + return config?.default ?? config; +} + +/** + * Dynamically imports a module from the given file path. + * @param {string} filePath The absolute file path of the module to import. + * @param {URL} fileURL The file URL to load. + * @param {number} mtime The last modified timestamp of the file. + * @returns {Promise} - A {@linkcode Promise | promise} that resolves to the imported ESLint config. + * @since 9.24.0 + */ +async function dynamicImportConfig(filePath, fileURL, mtime) { + const module = await import(fileURL.href); + + importedConfigFileModificationTime.set(filePath, mtime); + + return module.default; +} + +/** + * Load the config array from the given filename. + * @param {string} filePath The filename to load from. + * @param {boolean} hasUnstableNativeNodeJsTSConfigFlag The flag to indicate whether the `unstable_native_nodejs_ts_config` flag is enabled. + * @returns {Promise} The config loaded from the config file. + */ +async function loadConfigFile(filePath, hasUnstableNativeNodeJsTSConfigFlag) { + debug(`Loading config from ${filePath}`); + + const fileURL = pathToFileURL(filePath); + + debug(`Config file URL is ${fileURL}`); + + const mtime = (await fs.stat(filePath)).mtime.getTime(); + + /* + * Append a query with the config file's modification time (`mtime`) in order + * to import the current version of the config file. Without the query, `import()` would + * cache the config file module by the pathname only, and then always return + * the same version (the one that was actual when the module was imported for the first time). + * + * This ensures that the config file module is loaded and executed again + * if it has been changed since the last time it was imported. + * If it hasn't been changed, `import()` will just return the cached version. + * + * Note that we should not overuse queries (e.g., by appending the current time + * to always reload the config file module) as that could cause memory leaks + * because entries are never removed from the import cache. + */ + fileURL.searchParams.append("mtime", mtime); + + /* + * With queries, we can bypass the import cache. However, when import-ing a CJS module, + * Node.js uses the require infrastructure under the hood. That includes the require cache, + * which caches the config file module by its file path (queries have no effect). + * Therefore, we also need to clear the require cache before importing the config file module. + * In order to get the same behavior with ESM and CJS config files, in particular - to reload + * the config file only if it has been changed, we track file modification times and clear + * the require cache only if the file has been changed. + */ + if (importedConfigFileModificationTime.get(filePath) !== mtime) { + delete require.cache[filePath]; + } + + const isTS = isFileTS(filePath); + const isBun = isRunningInBun(); + const isDeno = isRunningInDeno(); + + /* + * If we are dealing with a TypeScript file, then we need to use `jiti` to load it + * in Node.js. Deno and Bun both allow native importing of TypeScript files. + * + * When Node.js supports native TypeScript imports, we can remove this check. + */ + + if (isTS) { + if (hasUnstableNativeNodeJsTSConfigFlag) { + if (isNativeTypeScriptSupportEnabled()) { + return await dynamicImportConfig(filePath, fileURL, mtime); + } + + if (!("typescript" in process.features)) { + throw new Error( + "The unstable_native_nodejs_ts_config flag is not supported in older versions of Node.js.", + ); + } + + throw new Error( + "The unstable_native_nodejs_ts_config flag is enabled, but native TypeScript support is not enabled in the current Node.js process. You need to either enable native TypeScript support by passing --experimental-strip-types or remove the unstable_native_nodejs_ts_config flag.", + ); + } + + if (!isDeno && !isBun) { + return await loadTypeScriptConfigFileWithJiti( + filePath, + fileURL, + mtime, + ); + } + } + + // fallback to normal runtime behavior + + return await dynamicImportConfig(filePath, fileURL, mtime); +} + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * Encapsulates the loading and caching of configuration files when looking up + * from the file being linted. + */ +class ConfigLoader { + /** + * Map of config file paths to the config arrays for those directories. + * @type {Map>} + */ + #configArrays = new Map(); + + /** + * Map of absolute directory names to the config file paths for those directories. + * @type {Map>} + */ + #configFilePaths = new Map(); + + /** + * The options to use when loading configuration files. + * @type {ConfigLoaderOptions} + */ + #options; + + /** + * Creates a new instance. + * @param {ConfigLoaderOptions} options The options to use when loading configuration files. + */ + constructor(options) { + this.#options = options.warningService + ? options + : { ...options, warningService: new WarningService() }; + } + + /** + * Determines which config file to use. This is determined by seeing if an + * override config file was specified, and if so, using it; otherwise, as long + * as override config file is not explicitly set to `false`, it will search + * upwards from `fromDirectory` for a file named `eslint.config.js`. + * @param {string} fromDirectory The directory from which to start searching. + * @returns {Promise<{configFilePath:string|undefined,basePath:string}>} Location information for + * the config file. + */ + async #locateConfigFileToUse(fromDirectory) { + // check cache first + if (this.#configFilePaths.has(fromDirectory)) { + return this.#configFilePaths.get(fromDirectory); + } + + const resultPromise = ConfigLoader.locateConfigFileToUse({ + useConfigFile: this.#options.configFile, + cwd: this.#options.cwd, + fromDirectory, + }); + + // ensure `ConfigLoader.locateConfigFileToUse` is called only once for `fromDirectory` + this.#configFilePaths.set(fromDirectory, resultPromise); + + // Unwrap the promise. This is primarily for the sync `getCachedConfigArrayForPath` method. + const result = await resultPromise; + + this.#configFilePaths.set(fromDirectory, result); + + return result; + } + + /** + * Calculates the config array for this run based on inputs. + * @param {string} configFilePath The absolute path to the config file to use if not overridden. + * @param {string} basePath The base path to use for relative paths in the config file. + * @returns {Promise} The config array for `eslint`. + */ + async #calculateConfigArray(configFilePath, basePath) { + // check for cached version first + if (this.#configArrays.has(configFilePath)) { + return this.#configArrays.get(configFilePath); + } + + const configsPromise = ConfigLoader.calculateConfigArray( + configFilePath, + basePath, + this.#options, + ); + + // ensure `ConfigLoader.calculateConfigArray` is called only once for `configFilePath` + this.#configArrays.set(configFilePath, configsPromise); + + // Unwrap the promise. This is primarily for the sync `getCachedConfigArrayForPath` method. + const configs = await configsPromise; + + this.#configArrays.set(configFilePath, configs); + + return configs; + } + + /** + * Returns the config file path for the given directory or file. This will either use + * the override config file that was specified in the constructor options or + * search for a config file from the directory. + * @param {string} fileOrDirPath The file or directory path to get the config file path for. + * @returns {Promise} The config file path or `undefined` if not found. + * @throws {Error} If `fileOrDirPath` is not a non-empty string. + * @throws {Error} If `fileOrDirPath` is not an absolute path. + */ + async findConfigFileForPath(fileOrDirPath) { + assertValidFilePath(fileOrDirPath); + + const absoluteDirPath = path.resolve( + this.#options.cwd, + path.dirname(fileOrDirPath), + ); + const { configFilePath } = + await this.#locateConfigFileToUse(absoluteDirPath); + + return configFilePath; + } + + /** + * Returns a configuration object for the given file based on the CLI options. + * This is the same logic used by the ESLint CLI executable to determine + * configuration for each file it processes. + * @param {string} filePath The path of the file or directory to retrieve config for. + * @returns {Promise} A configuration object for the file. + * @throws {Error} If no configuration for `filePath` exists. + */ + async loadConfigArrayForFile(filePath) { + assertValidFilePath(filePath); + + debug(`Calculating config for file ${filePath}`); + + const configFilePath = await this.findConfigFileForPath(filePath); + + assertConfigurationExists(configFilePath, this.#options); + + return this.loadConfigArrayForDirectory(filePath); + } + + /** + * Returns a configuration object for the given directory based on the CLI options. + * This is the same logic used by the ESLint CLI executable to determine + * configuration for each file it processes. + * @param {string} dirPath The path of the directory to retrieve config for. + * @returns {Promise} A configuration object for the directory. + */ + async loadConfigArrayForDirectory(dirPath) { + assertValidFilePath(dirPath); + + debug(`Calculating config for directory ${dirPath}`); + + const absoluteDirPath = path.resolve( + this.#options.cwd, + path.dirname(dirPath), + ); + const { configFilePath, basePath } = + await this.#locateConfigFileToUse(absoluteDirPath); + + debug(`Using config file ${configFilePath} and base path ${basePath}`); + return this.#calculateConfigArray(configFilePath, basePath); + } + + /** + * Returns a configuration array for the given file based on the CLI options. + * This is a synchronous operation and does not read any files from disk. It's + * intended to be used in locations where we know the config file has already + * been loaded and we just need to get the configuration for a file. + * @param {string} filePath The path of the file to retrieve a config object for. + * @returns {FlatConfigArray} A configuration object for the file. + * @throws {Error} If `filePath` is not a non-empty string. + * @throws {Error} If `filePath` is not an absolute path. + * @throws {Error} If the config file was not already loaded. + */ + getCachedConfigArrayForFile(filePath) { + assertValidFilePath(filePath); + + debug(`Looking up cached config for ${filePath}`); + + return this.getCachedConfigArrayForPath(path.dirname(filePath)); + } + + /** + * Returns a configuration array for the given directory based on the CLI options. + * This is a synchronous operation and does not read any files from disk. It's + * intended to be used in locations where we know the config file has already + * been loaded and we just need to get the configuration for a file. + * @param {string} fileOrDirPath The path of the directory to retrieve a config object for. + * @returns {FlatConfigArray} A configuration object for the directory. + * @throws {Error} If `dirPath` is not a non-empty string. + * @throws {Error} If `dirPath` is not an absolute path. + * @throws {Error} If the config file was not already loaded. + */ + getCachedConfigArrayForPath(fileOrDirPath) { + assertValidFilePath(fileOrDirPath); + + debug(`Looking up cached config for ${fileOrDirPath}`); + + const absoluteDirPath = path.resolve(this.#options.cwd, fileOrDirPath); + + if (!this.#configFilePaths.has(absoluteDirPath)) { + throw new Error(`Could not find config file for ${fileOrDirPath}`); + } + + const configFilePathInfo = this.#configFilePaths.get(absoluteDirPath); + + if (typeof configFilePathInfo.then === "function") { + throw new Error( + `Config file path for ${fileOrDirPath} has not yet been calculated or an error occurred during the calculation`, + ); + } + + const { configFilePath } = configFilePathInfo; + + const configArray = this.#configArrays.get(configFilePath); + + if (!configArray || typeof configArray.then === "function") { + throw new Error( + `Config array for ${fileOrDirPath} has not yet been calculated or an error occurred during the calculation`, + ); + } + + return configArray; + } + + /** + * Used to import the jiti dependency. This method is exposed internally for testing purposes. + * @returns {Promise<{createJiti: Function|undefined, version: string;}>} A promise that fulfills with an object containing the jiti module's createJiti function and version. + */ + static async loadJiti() { + const { createJiti } = await import("jiti"); + const version = require("jiti/package.json").version; + return { createJiti, version }; + } + + /** + * Determines which config file to use. This is determined by seeing if an + * override config file was specified, and if so, using it; otherwise, as long + * as override config file is not explicitly set to `false`, it will search + * upwards from `fromDirectory` for a file named `eslint.config.js`. + * This method is exposed internally for testing purposes. + * @param {Object} [options] the options object + * @param {string|false|undefined} options.useConfigFile The path to the config file to use. + * @param {string} options.cwd Path to a directory that should be considered as the current working directory. + * @param {string} [options.fromDirectory] The directory from which to start searching. Defaults to `cwd`. + * @returns {Promise<{configFilePath:string|undefined,basePath:string}>} Location information for + * the config file. + */ + static async locateConfigFileToUse({ + useConfigFile, + cwd, + fromDirectory = cwd, + }) { + // determine where to load config file from + let configFilePath; + let basePath = cwd; + + if (typeof useConfigFile === "string") { + debug(`Override config file path is ${useConfigFile}`); + configFilePath = path.resolve(cwd, useConfigFile); + basePath = cwd; + } else if (useConfigFile !== false) { + debug("Searching for eslint.config.js"); + configFilePath = await findUp(FLAT_CONFIG_FILENAMES, { + cwd: fromDirectory, + }); + + if (configFilePath) { + basePath = path.dirname(configFilePath); + } + } + + return { + configFilePath, + basePath, + }; + } + + /** + * Calculates the config array for this run based on inputs. + * This method is exposed internally for testing purposes. + * @param {string} configFilePath The absolute path to the config file to use if not overridden. + * @param {string} basePath The base path to use for relative paths in the config file. + * @param {ConfigLoaderOptions} options The options to use when loading configuration files. + * @returns {Promise} The config array for `eslint`. + */ + static async calculateConfigArray(configFilePath, basePath, options) { + const { + cwd, + baseConfig, + ignoreEnabled, + ignorePatterns, + overrideConfig, + hasUnstableNativeNodeJsTSConfigFlag = false, + defaultConfigs = [], + warningService, + } = options; + + debug( + `Calculating config array from config file ${configFilePath} and base path ${basePath}`, + ); + + const configs = new FlatConfigArray(baseConfig || [], { + basePath, + shouldIgnore: ignoreEnabled, + }); + + // load config file + if (configFilePath) { + debug(`Loading config file ${configFilePath}`); + const fileConfig = await loadConfigFile( + configFilePath, + hasUnstableNativeNodeJsTSConfigFlag, + ); + + /* + * It's possible that a config file could be empty or else + * have an empty object or array. In this case, we want to + * warn the user that they have an empty config. + * + * An empty CommonJS file exports an empty object while + * an empty ESM file exports undefined. + */ + + let emptyConfig = typeof fileConfig === "undefined"; + + debug( + `Config file ${configFilePath} is ${emptyConfig ? "empty" : "not empty"}`, + ); + + if (!emptyConfig) { + if (Array.isArray(fileConfig)) { + if (fileConfig.length === 0) { + debug( + `Config file ${configFilePath} is an empty array`, + ); + emptyConfig = true; + } else { + configs.push(...fileConfig); + } + } else { + if ( + typeof fileConfig === "object" && + fileConfig !== null && + Object.keys(fileConfig).length === 0 + ) { + debug( + `Config file ${configFilePath} is an empty object`, + ); + emptyConfig = true; + } else { + configs.push(fileConfig); + } + } + } + + if (emptyConfig) { + warningService.emitEmptyConfigWarning(configFilePath); + } + } + + // add in any configured defaults + configs.push(...defaultConfigs); + + // append command line ignore patterns + if (ignorePatterns && ignorePatterns.length > 0) { + /* + * Ignore patterns are added to the end of the config array + * so they can override default ignores. + */ + configs.push({ + basePath: cwd, + ignores: ignorePatterns, + }); + } + + if (overrideConfig) { + if (Array.isArray(overrideConfig)) { + configs.push(...overrideConfig); + } else { + configs.push(overrideConfig); + } + } + + await configs.normalize(); + + return configs; + } +} + +/** + * Encapsulates the loading and caching of configuration files when looking up + * from the current working directory. + */ +class LegacyConfigLoader extends ConfigLoader { + /** + * The options to use when loading configuration files. + * @type {ConfigLoaderOptions} + */ + #options; + + /** + * The cached config file path for this instance. + * @type {Promise<{configFilePath:string,basePath:string}|undefined>} + */ + #configFilePath; + + /** + * The cached config array for this instance. + * @type {FlatConfigArray|Promise} + */ + #configArray; + + /** + * Creates a new instance. + * @param {ConfigLoaderOptions} options The options to use when loading configuration files. + */ + constructor(options) { + const normalizedOptions = options.warningService + ? options + : { ...options, warningService: new WarningService() }; + super(normalizedOptions); + this.#options = normalizedOptions; + } + + /** + * Determines which config file to use. This is determined by seeing if an + * override config file was specified, and if so, using it; otherwise, as long + * as override config file is not explicitly set to `false`, it will search + * upwards from the cwd for a file named `eslint.config.js`. + * @returns {Promise<{configFilePath:string|undefined,basePath:string}>} Location information for + * the config file. + */ + #locateConfigFileToUse() { + if (!this.#configFilePath) { + this.#configFilePath = ConfigLoader.locateConfigFileToUse({ + useConfigFile: this.#options.configFile, + cwd: this.#options.cwd, + }); + } + + return this.#configFilePath; + } + + /** + * Calculates the config array for this run based on inputs. + * @param {string} configFilePath The absolute path to the config file to use if not overridden. + * @param {string} basePath The base path to use for relative paths in the config file. + * @returns {Promise} The config array for `eslint`. + */ + async #calculateConfigArray(configFilePath, basePath) { + // check for cached version first + if (this.#configArray) { + return this.#configArray; + } + + // ensure `ConfigLoader.calculateConfigArray` is called only once + this.#configArray = ConfigLoader.calculateConfigArray( + configFilePath, + basePath, + this.#options, + ); + + // Unwrap the promise. This is primarily for the sync `getCachedConfigArrayForPath` method. + this.#configArray = await this.#configArray; + + return this.#configArray; + } + + /** + * Returns the config file path for the given directory. This will either use + * the override config file that was specified in the constructor options or + * search for a config file from the directory of the file being linted. + * @param {string} dirPath The directory path to get the config file path for. + * @returns {Promise} The config file path or `undefined` if not found. + * @throws {Error} If `fileOrDirPath` is not a non-empty string. + * @throws {Error} If `fileOrDirPath` is not an absolute path. + */ + async findConfigFileForPath(dirPath) { + assertValidFilePath(dirPath); + + const { configFilePath } = await this.#locateConfigFileToUse(); + + return configFilePath; + } + + /** + * Returns a configuration object for the given file based on the CLI options. + * This is the same logic used by the ESLint CLI executable to determine + * configuration for each file it processes. + * @param {string} dirPath The path of the directory to retrieve config for. + * @returns {Promise} A configuration object for the file. + */ + async loadConfigArrayForDirectory(dirPath) { + assertValidFilePath(dirPath); + + debug(`[Legacy]: Calculating config for ${dirPath}`); + + const { configFilePath, basePath } = + await this.#locateConfigFileToUse(); + + debug( + `[Legacy]: Using config file ${configFilePath} and base path ${basePath}`, + ); + return this.#calculateConfigArray(configFilePath, basePath); + } + + /** + * Returns a configuration array for the given directory based on the CLI options. + * This is a synchronous operation and does not read any files from disk. It's + * intended to be used in locations where we know the config file has already + * been loaded and we just need to get the configuration for a file. + * @param {string} dirPath The path of the directory to retrieve a config object for. + * @returns {FlatConfigArray} A configuration object for the file. + * @throws {Error} If `dirPath` is not a non-empty string. + * @throws {Error} If `dirPath` is not an absolute path. + * @throws {Error} If the config file was not already loaded. + */ + getCachedConfigArrayForPath(dirPath) { + assertValidFilePath(dirPath); + + debug(`[Legacy]: Looking up cached config for ${dirPath}`); + + if (!this.#configArray) { + throw new Error(`Could not find config file for ${dirPath}`); + } + + if (typeof this.#configArray.then === "function") { + throw new Error( + `Config array for ${dirPath} has not yet been calculated or an error occurred during the calculation`, + ); + } + + return this.#configArray; + } +} + +module.exports = { ConfigLoader, LegacyConfigLoader }; diff --git a/tools/ui/node_modules/eslint/lib/config/config.js b/tools/ui/node_modules/eslint/lib/config/config.js new file mode 100644 index 0000000000000000000000000000000000000000..22fd5cc4ece74cba9b9b95d90b269aff94500189 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/config/config.js @@ -0,0 +1,674 @@ +/** + * @fileoverview The `Config` class + * @author Nicholas C. Zakas + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Requirements +//----------------------------------------------------------------------------- + +const { deepMergeArrays } = require("../shared/deep-merge-arrays"); +const { flatConfigSchema, hasMethod } = require("./flat-config-schema"); +const { ObjectSchema } = require("@eslint/config-array"); +const ajvImport = require("../shared/ajv"); +const ajv = ajvImport(); +const ruleReplacements = require("../../conf/replacements.json"); + +//----------------------------------------------------------------------------- +// Typedefs +//----------------------------------------------------------------------------- + +/** + * @import { RuleDefinition } from "@eslint/core"; + * @import { Linter } from "eslint"; + */ + +//----------------------------------------------------------------------------- +// Private Members +//------------------------------------------------------------------------------ + +// JSON schema that disallows passing any options +const noOptionsSchema = Object.freeze({ + type: "array", + minItems: 0, + maxItems: 0, +}); + +const severities = new Map([ + [0, 0], + [1, 1], + [2, 2], + ["off", 0], + ["warn", 1], + ["error", 2], +]); + +/** + * A collection of compiled validators for rules that have already + * been validated. + * @type {WeakMap} + */ +const validators = new WeakMap(); + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +/** + * Throws a helpful error when a rule cannot be found. + * @param {Object} ruleId The rule identifier. + * @param {string} ruleId.pluginName The ID of the rule to find. + * @param {string} ruleId.ruleName The ID of the rule to find. + * @param {Object} config The config to search in. + * @throws {TypeError} For missing plugin or rule. + * @returns {void} + */ +function throwRuleNotFoundError({ pluginName, ruleName }, config) { + const ruleId = pluginName === "@" ? ruleName : `${pluginName}/${ruleName}`; + + const errorMessageHeader = `Key "rules": Key "${ruleId}"`; + + let errorMessage = `${errorMessageHeader}: Could not find plugin "${pluginName}" in configuration.`; + + const missingPluginErrorMessage = errorMessage; + + // if the plugin exists then we need to check if the rule exists + if (config.plugins && config.plugins[pluginName]) { + const replacementRuleName = ruleReplacements.rules[ruleName]; + + if (pluginName === "@" && replacementRuleName) { + errorMessage = `${errorMessageHeader}: Rule "${ruleName}" was removed and replaced by "${replacementRuleName}".`; + } else { + errorMessage = `${errorMessageHeader}: Could not find "${ruleName}" in plugin "${pluginName}".`; + + // otherwise, let's see if we can find the rule name elsewhere + for (const [otherPluginName, otherPlugin] of Object.entries( + config.plugins, + )) { + if (otherPlugin.rules && otherPlugin.rules[ruleName]) { + errorMessage += ` Did you mean "${otherPluginName}/${ruleName}"?`; + break; + } + } + } + + // falls through to throw error + } + + const error = new TypeError(errorMessage); + + if (errorMessage === missingPluginErrorMessage) { + error.messageTemplate = "config-plugin-missing"; + error.messageData = { pluginName, ruleId }; + } + + throw error; +} + +/** + * The error type when a rule has an invalid `meta.schema`. + */ +class InvalidRuleOptionsSchemaError extends Error { + /** + * Creates a new instance. + * @param {string} ruleId Id of the rule that has an invalid `meta.schema`. + * @param {Error} processingError Error caught while processing the `meta.schema`. + */ + constructor(ruleId, processingError) { + super( + `Error while processing options validation schema of rule '${ruleId}': ${processingError.message}`, + { cause: processingError }, + ); + this.code = "ESLINT_INVALID_RULE_OPTIONS_SCHEMA"; + } +} + +/** + * Parses a ruleId into its plugin and rule parts. + * @param {string} ruleId The rule ID to parse. + * @returns {{pluginName:string,ruleName:string}} The plugin and rule + * parts of the ruleId; + */ +function parseRuleId(ruleId) { + let pluginName, ruleName; + + // distinguish between core rules and plugin rules + if (ruleId.includes("/")) { + // mimic scoped npm packages + if (ruleId.startsWith("@")) { + pluginName = ruleId.slice(0, ruleId.lastIndexOf("/")); + } else { + pluginName = ruleId.slice(0, ruleId.indexOf("/")); + } + + ruleName = ruleId.slice(pluginName.length + 1); + } else { + pluginName = "@"; + ruleName = ruleId; + } + + return { + pluginName, + ruleName, + }; +} + +/** + * Retrieves a rule instance from a given config based on the ruleId. + * @param {string} ruleId The rule ID to look for. + * @param {Linter.Config} config The config to search. + * @returns {RuleDefinition|undefined} The rule if found + * or undefined if not. + */ +function getRuleFromConfig(ruleId, config) { + const { pluginName, ruleName } = parseRuleId(ruleId); + + return config.plugins?.[pluginName]?.rules?.[ruleName]; +} + +/** + * Gets a complete options schema for a rule. + * @param {RuleDefinition} rule A rule object + * @throws {TypeError} If `meta.schema` is specified but is not an array, object or `false`. + * @returns {Object|null} JSON Schema for the rule's options. `null` if `meta.schema` is `false`. + */ +function getRuleOptionsSchema(rule) { + if (!rule.meta) { + return { ...noOptionsSchema }; // default if `meta.schema` is not specified + } + + const schema = rule.meta.schema; + + if (typeof schema === "undefined") { + return { ...noOptionsSchema }; // default if `meta.schema` is not specified + } + + // `schema:false` is an allowed explicit opt-out of options validation for the rule + if (schema === false) { + return null; + } + + if (typeof schema !== "object" || schema === null) { + throw new TypeError("Rule's `meta.schema` must be an array or object"); + } + + // ESLint-specific array form needs to be converted into a valid JSON Schema definition + if (Array.isArray(schema)) { + if (schema.length) { + return { + type: "array", + items: schema, + minItems: 0, + maxItems: schema.length, + }; + } + + // `schema:[]` is an explicit way to specify that the rule does not accept any options + return { ...noOptionsSchema }; + } + + // `schema:` is assumed to be a valid JSON Schema definition + return schema; +} + +/** + * Splits a plugin identifier in the form a/b/c into two parts: a/b and c. + * @param {string} identifier The identifier to parse. + * @returns {{objectName: string, pluginName: string}} The parts of the plugin + * name. + */ +function splitPluginIdentifier(identifier) { + const parts = identifier.split("/"); + + return { + objectName: parts.pop(), + pluginName: parts.join("/"), + }; +} + +/** + * Returns the name of an object in the config by reading its `meta` key. + * @param {Object} object The object to check. + * @returns {string?} The name of the object if found or `null` if there + * is no name. + */ +function getObjectId(object) { + // first check old-style name + let name = object.name; + + if (!name) { + if (!object.meta) { + return null; + } + + name = object.meta.name; + + if (!name) { + return null; + } + } + + // now check for old-style version + let version = object.version; + + if (!version) { + version = object.meta && object.meta.version; + } + + // if there's a version then append that + if (version) { + return `${name}@${version}`; + } + + return name; +} + +/** + * Asserts that a value is not a function. + * @param {any} value The value to check. + * @param {string} key The key of the value in the object. + * @param {string} objectKey The key of the object being checked. + * @returns {void} + * @throws {TypeError} If the value is a function. + */ +function assertNotFunction(value, key, objectKey) { + if (typeof value === "function") { + const error = new TypeError( + `Cannot serialize key "${key}" in "${objectKey}": Function values are not supported.`, + ); + + error.messageTemplate = "config-serialize-function"; + error.messageData = { key, objectKey }; + + throw error; + } +} + +/** + * Converts a languageOptions object to a JSON representation. + * @param {Record} languageOptions The options to create a JSON + * representation of. + * @param {string} objectKey The key of the object being converted. + * @returns {Record} The JSON representation of the languageOptions. + * @throws {TypeError} If a function is found in the languageOptions. + */ +function languageOptionsToJSON(languageOptions, objectKey = "languageOptions") { + if (typeof languageOptions.toJSON === "function") { + const result = languageOptions.toJSON(); + + assertNotFunction(result, "toJSON", objectKey); + + return result; + } + + const result = {}; + + for (const [key, value] of Object.entries(languageOptions)) { + if (value) { + if (typeof value === "object") { + const name = getObjectId(value); + + if (typeof value.toJSON === "function") { + result[key] = value.toJSON(); + assertNotFunction(result[key], key, objectKey); + } else if (name && hasMethod(value)) { + result[key] = name; + } else { + result[key] = languageOptionsToJSON(value, key); + } + continue; + } + + assertNotFunction(value, key, objectKey); + } + + result[key] = value; + } + + return result; +} + +/** + * Gets or creates a validator for a rule. + * @param {Object} rule The rule to get a validator for. + * @param {string} ruleId The ID of the rule (for error reporting). + * @returns {Function|null} A validation function or null if no validation is needed. + * @throws {InvalidRuleOptionsSchemaError} If a rule's `meta.schema` is invalid. + */ +function getOrCreateValidator(rule, ruleId) { + if (!validators.has(rule)) { + try { + const schema = getRuleOptionsSchema(rule); + + if (schema) { + validators.set(rule, ajv.compile(schema)); + } + } catch (err) { + throw new InvalidRuleOptionsSchemaError(ruleId, err); + } + } + + return validators.get(rule); +} + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * Represents a normalized configuration object. + */ +class Config { + /** + * The name to use for the language when serializing to JSON. + * @type {string|undefined} + */ + #languageName; + + /** + * The name to use for the processor when serializing to JSON. + * @type {string|undefined} + */ + #processorName; + + /** + * Creates a new instance. + * @param {Object} config The configuration object. + */ + constructor(config) { + const { plugins, language, languageOptions, processor, ...otherKeys } = + config; + + // Validate config object + const schema = new ObjectSchema(flatConfigSchema); + + schema.validate(config); + + // first, copy all the other keys over + Object.assign(this, otherKeys); + + // ensure that a language is specified + if (!language) { + throw new TypeError("Key 'language' is required."); + } + + // copy the rest over + this.plugins = plugins; + this.language = language; + + // Check language value + const { + pluginName: languagePluginName, + objectName: localLanguageName, + } = splitPluginIdentifier(language); + + this.#languageName = language; + + if ( + !plugins || + !plugins[languagePluginName] || + !plugins[languagePluginName].languages || + !plugins[languagePluginName].languages[localLanguageName] + ) { + throw new TypeError( + `Key "language": Could not find "${localLanguageName}" in plugin "${languagePluginName}".`, + ); + } + + this.language = + plugins[languagePluginName].languages[localLanguageName]; + + if (this.language.defaultLanguageOptions ?? languageOptions) { + this.languageOptions = flatConfigSchema.languageOptions.merge( + this.language.defaultLanguageOptions, + languageOptions, + ); + } else { + this.languageOptions = {}; + } + + // Validate language options + try { + this.language.validateLanguageOptions(this.languageOptions); + } catch (error) { + throw new TypeError(`Key "languageOptions": ${error.message}`, { + cause: error, + }); + } + + // Normalize language options if necessary + if (this.language.normalizeLanguageOptions) { + this.languageOptions = this.language.normalizeLanguageOptions( + this.languageOptions, + ); + } + + // Check processor value + if (processor) { + this.processor = processor; + + if (typeof processor === "string") { + const { pluginName, objectName: localProcessorName } = + splitPluginIdentifier(processor); + + this.#processorName = processor; + + if ( + !plugins || + !plugins[pluginName] || + !plugins[pluginName].processors || + !plugins[pluginName].processors[localProcessorName] + ) { + throw new TypeError( + `Key "processor": Could not find "${localProcessorName}" in plugin "${pluginName}".`, + ); + } + + this.processor = + plugins[pluginName].processors[localProcessorName]; + } else if (typeof processor === "object") { + this.#processorName = getObjectId(processor); + this.processor = processor; + } else { + throw new TypeError( + "Key 'processor' must be a string or an object.", + ); + } + } + + // Process the rules + if (this.rules) { + this.#normalizeRulesConfig(); + this.validateRulesConfig(this.rules); + } + } + + /** + * Converts the configuration to a JSON representation. + * @returns {Record} The JSON representation of the configuration. + * @throws {Error} If the configuration cannot be serialized. + */ + toJSON() { + if (this.processor && !this.#processorName) { + throw new Error( + "Could not serialize processor object (missing 'meta' object).", + ); + } + + if (!this.#languageName) { + throw new Error( + "Could not serialize language object (missing 'meta' object).", + ); + } + + return { + ...this, + plugins: Object.entries(this.plugins).map(([namespace, plugin]) => { + const pluginId = getObjectId(plugin); + + if (!pluginId) { + return namespace; + } + + return `${namespace}:${pluginId}`; + }), + language: this.#languageName, + languageOptions: languageOptionsToJSON(this.languageOptions), + processor: this.#processorName, + }; + } + + /** + * Gets a rule configuration by its ID. + * @param {string} ruleId The ID of the rule to get. + * @returns {RuleDefinition|undefined} The rule definition from the plugin, or `undefined` if the rule is not found. + */ + getRuleDefinition(ruleId) { + return getRuleFromConfig(ruleId, this); + } + + /** + * Normalizes the rules configuration. Ensures that each rule config is + * an array and that the severity is a number. Applies meta.defaultOptions. + * This function modifies `this.rules`. + * @returns {void} + */ + #normalizeRulesConfig() { + for (const [ruleId, originalConfig] of Object.entries(this.rules)) { + // ensure rule config is an array + let ruleConfig = Array.isArray(originalConfig) + ? originalConfig + : [originalConfig]; + + // normalize severity + ruleConfig[0] = severities.get(ruleConfig[0]); + + const rule = getRuleFromConfig(ruleId, this); + + // apply meta.defaultOptions + const slicedOptions = ruleConfig.slice(1); + const mergedOptions = deepMergeArrays( + rule?.meta?.defaultOptions, + slicedOptions, + ); + + if (mergedOptions.length) { + ruleConfig = [ruleConfig[0], ...mergedOptions]; + } + + this.rules[ruleId] = ruleConfig; + } + } + + /** + * Validates all of the rule configurations in the given rules config + * against the plugins in this instance. This is used primarily to + * validate inline configuration rules while inting. + * @param {Object} rulesConfig The rules config to validate. + * @returns {void} + * @throws {Error} If a rule's configuration does not match its schema. + * @throws {TypeError} If the rulesConfig is not provided or is invalid. + * @throws {InvalidRuleOptionsSchemaError} If a rule's `meta.schema` is invalid. + * @throws {TypeError} If a rule is not found in the plugins. + */ + validateRulesConfig(rulesConfig) { + if (!rulesConfig) { + throw new TypeError("Config is required for validation."); + } + + for (const [ruleId, ruleOptions] of Object.entries(rulesConfig)) { + // check for edge case + if (ruleId === "__proto__") { + continue; + } + + /* + * If a rule is disabled, we don't do any validation. This allows + * users to safely set any value to 0 or "off" without worrying + * that it will cause a validation error. + * + * Note: ruleOptions is always an array at this point because + * this validation occurs after FlatConfigArray has merged and + * normalized values. + */ + if (ruleOptions[0] === 0) { + continue; + } + + const rule = getRuleFromConfig(ruleId, this); + + if (!rule) { + throwRuleNotFoundError(parseRuleId(ruleId), this); + } + + const validateRule = getOrCreateValidator(rule, ruleId); + + if (validateRule) { + validateRule(ruleOptions.slice(1)); + + if (validateRule.errors) { + throw new Error( + `Key "rules": Key "${ruleId}":\n${validateRule.errors + .map(error => { + if ( + error.keyword === "additionalProperties" && + error.schema === false && + typeof error.parentSchema?.properties === + "object" && + typeof error.params?.additionalProperty === + "string" + ) { + const expectedProperties = Object.keys( + error.parentSchema.properties, + ).map(property => `"${property}"`); + + return `\tValue ${JSON.stringify(error.data)} ${error.message}.\n\t\tUnexpected property "${error.params.additionalProperty}". Expected properties: ${expectedProperties.join(", ")}.\n`; + } + + return `\tValue ${JSON.stringify(error.data)} ${error.message}.\n`; + }) + .join("")}`, + ); + } + } + } + } + + /** + * Gets a complete options schema for a rule. + * @param {RuleDefinition} ruleDefinition A rule definition object. + * @throws {TypeError} If `meta.schema` is specified but is not an array, object or `false`. + * @returns {Object|null} JSON Schema for the rule's options. `null` if `meta.schema` is `false`. + */ + static getRuleOptionsSchema(ruleDefinition) { + return getRuleOptionsSchema(ruleDefinition); + } + + /** + * Normalizes the severity value of a rule's configuration to a number + * @param {(number|string|[number, ...*]|[string, ...*])} ruleConfig A rule's configuration value, generally + * received from the user. A valid config value is either 0, 1, 2, the string "off" (treated the same as 0), + * the string "warn" (treated the same as 1), the string "error" (treated the same as 2), or an array + * whose first element is one of the above values. Strings are matched case-insensitively. + * @returns {(0|1|2)} The numeric severity value if the config value was valid, otherwise 0. + */ + static getRuleNumericSeverity(ruleConfig) { + const severityValue = Array.isArray(ruleConfig) + ? ruleConfig[0] + : ruleConfig; + + if (severities.has(severityValue)) { + return severities.get(severityValue); + } + + if (typeof severityValue === "string") { + return severities.get(severityValue.toLowerCase()) ?? 0; + } + + return 0; + } +} + +module.exports = { Config }; diff --git a/tools/ui/node_modules/eslint/lib/config/default-config.js b/tools/ui/node_modules/eslint/lib/config/default-config.js new file mode 100644 index 0000000000000000000000000000000000000000..aebf6e930685e78a13329ea7c67b26c428bf024a --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/config/default-config.js @@ -0,0 +1,78 @@ +/** + * @fileoverview Default configuration + * @author Nicholas C. Zakas + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Requirements +//----------------------------------------------------------------------------- + +const Rules = require("../rules"); + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +const sharedDefaultConfig = [ + // intentionally empty config to ensure these files are globbed by default + { + files: ["**/*.js", "**/*.mjs"], + }, + { + files: ["**/*.cjs"], + languageOptions: { + sourceType: "commonjs", + ecmaVersion: "latest", + }, + }, +]; + +exports.defaultConfig = Object.freeze([ + { + plugins: { + "@": { + languages: { + js: require("../languages/js"), + }, + + /* + * Because we try to delay loading rules until absolutely + * necessary, a proxy allows us to hook into the lazy-loading + * aspect of the rules map while still keeping all of the + * relevant configuration inside of the config array. + */ + rules: new Proxy( + {}, + { + get(target, property) { + return Rules.get(property); + }, + + has(target, property) { + return Rules.has(property); + }, + }, + ), + }, + }, + language: "@/js", + linterOptions: { + reportUnusedDisableDirectives: 1, + }, + }, + + // default ignores are listed here + { + ignores: ["**/node_modules/", ".git/"], + }, + + ...sharedDefaultConfig, +]); + +exports.defaultRuleTesterConfig = Object.freeze([ + { files: ["**"] }, // Make sure the default config matches for all files + + ...sharedDefaultConfig, +]); diff --git a/tools/ui/node_modules/eslint/lib/config/flat-config-array.js b/tools/ui/node_modules/eslint/lib/config/flat-config-array.js new file mode 100644 index 0000000000000000000000000000000000000000..aaa97db259958b1d54fb54cb5cd4d5a57db01c2d --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/config/flat-config-array.js @@ -0,0 +1,217 @@ +/** + * @fileoverview Flat Config Array + * @author Nicholas C. Zakas + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Requirements +//----------------------------------------------------------------------------- + +const { ConfigArray, ConfigArraySymbol } = require("@eslint/config-array"); +const { flatConfigSchema } = require("./flat-config-schema"); +const { defaultConfig } = require("./default-config"); +const { Config } = require("./config"); + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +/** + * Fields that are considered metadata and not part of the config object. + */ +const META_FIELDS = new Set(["name", "basePath"]); + +/** + * Wraps a config error with details about where the error occurred. + * @param {Error} error The original error. + * @param {number} originalLength The original length of the config array. + * @param {number} baseLength The length of the base config. + * @returns {TypeError} The new error with details. + */ +function wrapConfigErrorWithDetails(error, originalLength, baseLength) { + let location = "user-defined"; + let configIndex = error.index; + + /* + * A config array is set up in this order: + * 1. Base config + * 2. Original configs + * 3. User-defined configs + * 4. CLI-defined configs + * + * So we need to adjust the index to account for the base config. + * + * - If the index is less than the base length, it's in the base config + * (as specified by `baseConfig` argument to `FlatConfigArray` constructor). + * - If the index is greater than the base length but less than the original + * length + base length, it's in the original config. The original config + * is passed to the `FlatConfigArray` constructor as the first argument. + * - Otherwise, it's in the user-defined config, which is loaded from the + * config file and merged with any command-line options. + */ + if (error.index < baseLength) { + location = "base"; + } else if (error.index < originalLength + baseLength) { + location = "original"; + configIndex = error.index - baseLength; + } else { + configIndex = error.index - originalLength - baseLength; + } + + return new TypeError( + `${error.message.slice(0, -1)} at ${location} index ${configIndex}.`, + { cause: error }, + ); +} + +const originalBaseConfig = Symbol("originalBaseConfig"); +const originalLength = Symbol("originalLength"); +const baseLength = Symbol("baseLength"); + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * Represents an array containing configuration information for ESLint. + */ +class FlatConfigArray extends ConfigArray { + /** + * Creates a new instance. + * @param {*[]} configs An array of configuration information. + * @param {{basePath: string, shouldIgnore: boolean, baseConfig: FlatConfig}} options The options + * to use for the config array instance. + */ + constructor( + configs, + { basePath, shouldIgnore = true, baseConfig = defaultConfig } = {}, + ) { + super(configs, { + basePath, + schema: flatConfigSchema, + }); + + /** + * The original length of the array before any modifications. + * @type {number} + */ + this[originalLength] = this.length; + + if (baseConfig[Symbol.iterator]) { + this.unshift(...baseConfig); + } else { + this.unshift(baseConfig); + } + + /** + * The length of the array after applying the base config. + * @type {number} + */ + this[baseLength] = this.length - this[originalLength]; + + /** + * The base config used to build the config array. + * @type {Array} + */ + this[originalBaseConfig] = baseConfig; + Object.defineProperty(this, originalBaseConfig, { writable: false }); + + /** + * Determines if `ignores` fields should be honored. + * If true, then all `ignores` fields are honored. + * if false, then only `ignores` fields in the baseConfig are honored. + * @type {boolean} + */ + this.shouldIgnore = shouldIgnore; + Object.defineProperty(this, "shouldIgnore", { writable: false }); + } + + /** + * Normalizes the array by calling the superclass method and catching/rethrowing + * any ConfigError exceptions with additional details. + * @param {any} [context] The context to use to normalize the array. + * @returns {Promise} A promise that resolves when the array is normalized. + */ + normalize(context) { + return super.normalize(context).catch(error => { + if (error.name === "ConfigError") { + throw wrapConfigErrorWithDetails( + error, + this[originalLength], + this[baseLength], + ); + } + + throw error; + }); + } + + /** + * Normalizes the array by calling the superclass method and catching/rethrowing + * any ConfigError exceptions with additional details. + * @param {any} [context] The context to use to normalize the array. + * @returns {FlatConfigArray} The current instance. + * @throws {TypeError} If the config is invalid. + */ + normalizeSync(context) { + try { + return super.normalizeSync(context); + } catch (error) { + if (error.name === "ConfigError") { + throw wrapConfigErrorWithDetails( + error, + this[originalLength], + this[baseLength], + ); + } + + throw error; + } + } + + /* eslint-disable class-methods-use-this -- Desired as instance method */ + /** + * Replaces a config with another config to allow us to put strings + * in the config array that will be replaced by objects before + * normalization. + * @param {Object} config The config to preprocess. + * @returns {Object} The preprocessed config. + */ + [ConfigArraySymbol.preprocessConfig](config) { + /* + * If a config object has `ignores` and no other non-meta fields, then it's an object + * for global ignores. If `shouldIgnore` is false, that object shouldn't apply, + * so we'll remove its `ignores`. + */ + if ( + !this.shouldIgnore && + !this[originalBaseConfig].includes(config) && + config.ignores && + Object.keys(config).filter(key => !META_FIELDS.has(key)).length === + 1 + ) { + /* eslint-disable-next-line no-unused-vars -- need to strip off other keys */ + const { ignores, ...otherKeys } = config; + + return otherKeys; + } + + return config; + } + + /** + * Finalizes the config by replacing plugin references with their objects + * and validating rule option schemas. + * @param {Object} config The config to finalize. + * @returns {Object} The finalized config. + * @throws {TypeError} If the config is invalid. + */ + [ConfigArraySymbol.finalizeConfig](config) { + return new Config(config); + } + /* eslint-enable class-methods-use-this -- Desired as instance method */ +} + +exports.FlatConfigArray = FlatConfigArray; diff --git a/tools/ui/node_modules/eslint/lib/config/flat-config-schema.js b/tools/ui/node_modules/eslint/lib/config/flat-config-schema.js new file mode 100644 index 0000000000000000000000000000000000000000..f393a99988b77b1d61ec40d4cb2df195dc8570c8 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/config/flat-config-schema.js @@ -0,0 +1,598 @@ +/** + * @fileoverview Flat config schema + * @author Nicholas C. Zakas + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Requirements +//----------------------------------------------------------------------------- + +const { normalizeSeverityToNumber } = require("../shared/severity"); + +//----------------------------------------------------------------------------- +// Type Definitions +//----------------------------------------------------------------------------- + +/** + * @typedef ObjectPropertySchema + * @property {Function|string} merge The function or name of the function to call + * to merge multiple objects with this property. + * @property {Function|string} validate The function or name of the function to call + * to validate the value of this property. + */ + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +const ruleSeverities = new Map([ + [0, 0], + ["off", 0], + [1, 1], + ["warn", 1], + [2, 2], + ["error", 2], +]); + +/** + * Check if a value is a non-null object. + * @param {any} value The value to check. + * @returns {boolean} `true` if the value is a non-null object. + */ +function isNonNullObject(value) { + return typeof value === "object" && value !== null; +} + +/** + * Check if a value is a non-null non-array object. + * @param {any} value The value to check. + * @returns {boolean} `true` if the value is a non-null non-array object. + */ +function isNonArrayObject(value) { + return isNonNullObject(value) && !Array.isArray(value); +} + +/** + * Check if a value is undefined. + * @param {any} value The value to check. + * @returns {boolean} `true` if the value is undefined. + */ +function isUndefined(value) { + return typeof value === "undefined"; +} + +/** + * Deeply merges two non-array objects. + * @param {Object} first The base object. + * @param {Object} second The overrides object. + * @param {Map>} [mergeMap] Maps the combination of first and second arguments to a merged result. + * @returns {Object} An object with properties from both first and second. + */ +function deepMerge(first, second, mergeMap = new Map()) { + let secondMergeMap = mergeMap.get(first); + + if (secondMergeMap) { + const result = secondMergeMap.get(second); + + if (result) { + // If this combination of first and second arguments has been already visited, return the previously created result. + return result; + } + } else { + secondMergeMap = new Map(); + mergeMap.set(first, secondMergeMap); + } + + /* + * First create a result object where properties from the second object + * overwrite properties from the first. This sets up a baseline to use + * later rather than needing to inspect and change every property + * individually. + */ + const result = { + ...first, + ...second, + }; + + delete result.__proto__; // eslint-disable-line no-proto -- don't merge own property "__proto__" + + // Store the pending result for this combination of first and second arguments. + secondMergeMap.set(second, result); + + for (const key of Object.keys(second)) { + // avoid hairy edge case + if ( + key === "__proto__" || + !Object.prototype.propertyIsEnumerable.call(first, key) + ) { + continue; + } + + const firstValue = first[key]; + const secondValue = second[key]; + + if (isNonArrayObject(firstValue) && isNonArrayObject(secondValue)) { + result[key] = deepMerge(firstValue, secondValue, mergeMap); + } else if (isUndefined(secondValue)) { + result[key] = firstValue; + } + } + + return result; +} + +/** + * Normalizes the rule options config for a given rule by ensuring that + * it is an array and that the first item is 0, 1, or 2. + * @param {Array|string|number} ruleOptions The rule options config. + * @returns {Array} An array of rule options. + */ +function normalizeRuleOptions(ruleOptions) { + const finalOptions = Array.isArray(ruleOptions) + ? ruleOptions.slice(0) + : [ruleOptions]; + + finalOptions[0] = ruleSeverities.get(finalOptions[0]); + return structuredClone(finalOptions); +} + +/** + * Determines if an object has any methods. + * @param {Object} object The object to check. + * @returns {boolean} `true` if the object has any methods. + */ +function hasMethod(object) { + for (const key of Object.keys(object)) { + if (typeof object[key] === "function") { + return true; + } + } + + return false; +} + +//----------------------------------------------------------------------------- +// Assertions +//----------------------------------------------------------------------------- + +/** + * The error type when a rule's options are configured with an invalid type. + */ +class InvalidRuleOptionsError extends Error { + /** + * @param {string} ruleId Rule name being configured. + * @param {any} value The invalid value. + */ + constructor(ruleId, value) { + super( + `Key "${ruleId}": Expected severity of "off", 0, "warn", 1, "error", or 2.`, + ); + this.messageTemplate = "invalid-rule-options"; + this.messageData = { ruleId, value }; + } +} + +/** + * Validates that a value is a valid rule options entry. + * @param {string} ruleId Rule name being configured. + * @param {any} value The value to check. + * @returns {void} + * @throws {InvalidRuleOptionsError} If the value isn't a valid rule options. + */ +function assertIsRuleOptions(ruleId, value) { + if ( + typeof value !== "string" && + typeof value !== "number" && + !Array.isArray(value) + ) { + throw new InvalidRuleOptionsError(ruleId, value); + } +} + +/** + * The error type when a rule's severity is invalid. + */ +class InvalidRuleSeverityError extends Error { + /** + * @param {string} ruleId Rule name being configured. + * @param {any} value The invalid value. + */ + constructor(ruleId, value) { + super( + `Key "${ruleId}": Expected severity of "off", 0, "warn", 1, "error", or 2.`, + ); + this.messageTemplate = "invalid-rule-severity"; + this.messageData = { ruleId, value }; + } +} + +/** + * Validates that a value is valid rule severity. + * @param {string} ruleId Rule name being configured. + * @param {any} value The value to check. + * @returns {void} + * @throws {InvalidRuleSeverityError} If the value isn't a valid rule severity. + */ +function assertIsRuleSeverity(ruleId, value) { + const severity = ruleSeverities.get(value); + + if (typeof severity === "undefined") { + throw new InvalidRuleSeverityError(ruleId, value); + } +} + +/** + * Validates that a given string is the form pluginName/objectName. + * @param {string} value The string to check. + * @returns {void} + * @throws {TypeError} If the string isn't in the correct format. + */ +function assertIsPluginMemberName(value) { + if (!/[\w\-@$]+(?:\/[\w\-$]+)+$/iu.test(value)) { + throw new TypeError( + `Expected string in the form "pluginName/objectName" but found "${value}".`, + ); + } +} + +/** + * Validates that a value is an object. + * @param {any} value The value to check. + * @returns {void} + * @throws {TypeError} If the value isn't an object. + */ +function assertIsObject(value) { + if (!isNonNullObject(value)) { + throw new TypeError("Expected an object."); + } +} + +/** + * The error type when there's an eslintrc-style options in a flat config. + */ +class IncompatibleKeyError extends Error { + /** + * @param {string} key The invalid key. + */ + constructor(key) { + super( + "This appears to be in eslintrc format rather than flat config format.", + ); + this.messageTemplate = "eslintrc-incompat"; + this.messageData = { key }; + } +} + +/** + * The error type when there's an eslintrc-style plugins array found. + */ +class IncompatiblePluginsError extends Error { + /** + * Creates a new instance. + * @param {Array} plugins The plugins array. + */ + constructor(plugins) { + super( + "This appears to be in eslintrc format (array of strings) rather than flat config format (object).", + ); + this.messageTemplate = "eslintrc-plugins"; + this.messageData = { plugins }; + } +} + +//----------------------------------------------------------------------------- +// Low-Level Schemas +//----------------------------------------------------------------------------- + +/** @type {ObjectPropertySchema} */ +const booleanSchema = { + merge: "replace", + validate: "boolean", +}; + +const ALLOWED_SEVERITIES = new Set(["error", "warn", "off", 2, 1, 0]); + +/** @type {ObjectPropertySchema} */ +const disableDirectiveSeveritySchema = { + merge(first, second) { + const value = second === void 0 ? first : second; + + if (typeof value === "boolean") { + return value ? "warn" : "off"; + } + + return normalizeSeverityToNumber(value); + }, + validate(value) { + if (!(ALLOWED_SEVERITIES.has(value) || typeof value === "boolean")) { + throw new TypeError( + 'Expected one of: "error", "warn", "off", 0, 1, 2, or a boolean.', + ); + } + }, +}; + +/** @type {ObjectPropertySchema} */ +const unusedInlineConfigsSeveritySchema = { + merge(first, second) { + const value = second === void 0 ? first : second; + + return normalizeSeverityToNumber(value); + }, + validate(value) { + if (!ALLOWED_SEVERITIES.has(value)) { + throw new TypeError( + 'Expected one of: "error", "warn", "off", 0, 1, or 2.', + ); + } + }, +}; + +/** @type {ObjectPropertySchema} */ +const deepObjectAssignSchema = { + merge(first = {}, second = {}) { + return deepMerge(first, second); + }, + validate: "object", +}; + +//----------------------------------------------------------------------------- +// High-Level Schemas +//----------------------------------------------------------------------------- + +/** @type {ObjectPropertySchema} */ +const languageOptionsSchema = { + merge(first = {}, second = {}) { + const result = deepMerge(first, second); + + for (const [key, value] of Object.entries(result)) { + /* + * Special case: Because the `parser` property is an object, it should + * not be deep merged. Instead, it should be replaced if it exists in + * the second object. To make this more generic, we just check for + * objects with methods and replace them if they exist in the second + * object. + */ + if (isNonArrayObject(value)) { + if (hasMethod(value)) { + result[key] = second[key] ?? first[key]; + continue; + } + + // for other objects, make sure we aren't reusing the same object + result[key] = { ...result[key] }; + continue; + } + } + + return result; + }, + validate: "object", +}; + +/** @type {ObjectPropertySchema} */ +const languageSchema = { + merge: "replace", + validate: assertIsPluginMemberName, +}; + +/** @type {ObjectPropertySchema} */ +const pluginsSchema = { + merge(first = {}, second = {}) { + const keys = new Set([...Object.keys(first), ...Object.keys(second)]); + const result = {}; + + // manually validate that plugins are not redefined + for (const key of keys) { + // avoid hairy edge case + if (key === "__proto__") { + continue; + } + + if (key in first && key in second && first[key] !== second[key]) { + throw new TypeError(`Cannot redefine plugin "${key}".`); + } + + result[key] = second[key] || first[key]; + } + + return result; + }, + validate(value) { + // first check the value to be sure it's an object + if (value === null || typeof value !== "object") { + throw new TypeError("Expected an object."); + } + + // make sure it's not an array, which would mean eslintrc-style is used + if (Array.isArray(value)) { + throw new IncompatiblePluginsError(value); + } + + // second check the keys to make sure they are objects + for (const key of Object.keys(value)) { + // avoid hairy edge case + if (key === "__proto__") { + continue; + } + + if (value[key] === null || typeof value[key] !== "object") { + throw new TypeError(`Key "${key}": Expected an object.`); + } + } + }, +}; + +/** @type {ObjectPropertySchema} */ +const processorSchema = { + merge: "replace", + validate(value) { + if (typeof value === "string") { + assertIsPluginMemberName(value); + } else if (value && typeof value === "object") { + if ( + typeof value.preprocess !== "function" || + typeof value.postprocess !== "function" + ) { + throw new TypeError( + "Object must have a preprocess() and a postprocess() method.", + ); + } + } else { + throw new TypeError("Expected an object or a string."); + } + }, +}; + +/** @type {ObjectPropertySchema} */ +const rulesSchema = { + merge(first = {}, second = {}) { + const result = { + ...first, + ...second, + }; + + for (const ruleId of Object.keys(result)) { + try { + // avoid hairy edge case + if (ruleId === "__proto__") { + /* eslint-disable-next-line no-proto -- Though deprecated, may still be present */ + delete result.__proto__; + continue; + } + + result[ruleId] = normalizeRuleOptions(result[ruleId]); + + /* + * If either rule config is missing, then the correct + * config is already present and we just need to normalize + * the severity. + */ + if (!(ruleId in first) || !(ruleId in second)) { + continue; + } + + const firstRuleOptions = normalizeRuleOptions(first[ruleId]); + const secondRuleOptions = normalizeRuleOptions(second[ruleId]); + + /* + * If the second rule config only has a severity (length of 1), + * then use that severity and keep the rest of the options from + * the first rule config. + */ + if (secondRuleOptions.length === 1) { + result[ruleId] = [ + secondRuleOptions[0], + ...firstRuleOptions.slice(1), + ]; + continue; + } + + /* + * In any other situation, then the second rule config takes + * precedence. That means the value at `result[ruleId]` is + * already correct and no further work is necessary. + */ + } catch (ex) { + throw new Error(`Key "${ruleId}": ${ex.message}`, { + cause: ex, + }); + } + } + + return result; + }, + + validate(value) { + assertIsObject(value); + + /* + * We are not checking the rule schema here because there is no + * guarantee that the rule definition is present at this point. Instead + * we wait and check the rule schema during the finalization step + * of calculating a config. + */ + for (const ruleId of Object.keys(value)) { + // avoid hairy edge case + if (ruleId === "__proto__") { + continue; + } + + const ruleOptions = value[ruleId]; + + assertIsRuleOptions(ruleId, ruleOptions); + + if (Array.isArray(ruleOptions)) { + assertIsRuleSeverity(ruleId, ruleOptions[0]); + } else { + assertIsRuleSeverity(ruleId, ruleOptions); + } + } + }, +}; + +/** + * Creates a schema that always throws an error. Useful for warning + * about eslintrc-style keys. + * @param {string} key The eslintrc key to create a schema for. + * @returns {ObjectPropertySchema} The schema. + */ +function createEslintrcErrorSchema(key) { + return { + merge: "replace", + validate() { + throw new IncompatibleKeyError(key); + }, + }; +} + +const eslintrcKeys = [ + "env", + "extends", + "globals", + "ignorePatterns", + "noInlineConfig", + "overrides", + "parser", + "parserOptions", + "reportUnusedDisableDirectives", + "root", +]; + +//----------------------------------------------------------------------------- +// Full schema +//----------------------------------------------------------------------------- + +const flatConfigSchema = { + // eslintrc-style keys that should always error + ...Object.fromEntries( + eslintrcKeys.map(key => [key, createEslintrcErrorSchema(key)]), + ), + + // flat config keys + settings: deepObjectAssignSchema, + linterOptions: { + schema: { + noInlineConfig: booleanSchema, + reportUnusedDisableDirectives: disableDirectiveSeveritySchema, + reportUnusedInlineConfigs: unusedInlineConfigsSeveritySchema, + }, + }, + language: languageSchema, + languageOptions: languageOptionsSchema, + processor: processorSchema, + plugins: pluginsSchema, + rules: rulesSchema, +}; + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +module.exports = { + flatConfigSchema, + hasMethod, + assertIsRuleSeverity, +}; diff --git a/tools/ui/node_modules/eslint/lib/eslint/eslint-helpers.js b/tools/ui/node_modules/eslint/lib/eslint/eslint-helpers.js new file mode 100644 index 0000000000000000000000000000000000000000..16c8dde94ec82876d8123a5a36b23c7787b8a5ec --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/eslint/eslint-helpers.js @@ -0,0 +1,1465 @@ +/** + * @fileoverview Helper functions for ESLint class + * @author Nicholas C. Zakas + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Requirements +//----------------------------------------------------------------------------- + +const path = require("node:path"); +const fs = require("node:fs"); +const { isMainThread, threadId } = require("node:worker_threads"); +const fsp = fs.promises; +const isGlob = require("is-glob"); +const hash = require("../cli-engine/hash"); +const minimatch = require("minimatch"); +const globParent = require("glob-parent"); +const { Linter } = require("../linter"); +const { getShorthandName } = require("../shared/naming"); +const LintResultCache = require("../cli-engine/lint-result-cache"); +const { ConfigLoader, LegacyConfigLoader } = require("../config/config-loader"); +const createDebug = require("debug"); + +//----------------------------------------------------------------------------- +// Fixup references +//----------------------------------------------------------------------------- + +const Minimatch = minimatch.Minimatch; +const MINIMATCH_OPTIONS = { dot: true }; +const hrtimeBigint = process.hrtime.bigint; + +//----------------------------------------------------------------------------- +// Types +//----------------------------------------------------------------------------- + +/** + * @import { ESLintOptions } from "./eslint.js"; + * @import { Config as CalculatedConfig } from "../config/config.js"; + * @import { FlatConfigArray } from "../config/flat-config-array.js"; + * @import { WarningService } from "../services/warning-service.js"; + * @import { Retrier } from "@humanwhocodes/retry"; + */ + +/** @typedef {import("../types").Linter.Config} Config */ +/** @typedef {import("../types").Linter.LintMessage} LintMessage */ +/** @typedef {import("../types").ESLint.LintResult} LintResult */ +/** @typedef {import("../types").ESLint.Plugin} Plugin */ + +/** + * @typedef {Object} GlobSearch + * @property {Array} patterns The normalized patterns to use for a search. + * @property {Array} rawPatterns The patterns as entered by the user + * before doing any normalization. + */ + +//------------------------------------------------------------------------------ +// Debug Helpers +//------------------------------------------------------------------------------ + +// Add %t formatter to print bigint nanosecond times in milliseconds. +createDebug.formatters.t = timeDiff => + `${(timeDiff + 500_000n) / 1_000_000n} ms`; + +const debug = createDebug( + `eslint:eslint-helpers${isMainThread ? "" : `:thread-${threadId}`}`, +); + +//----------------------------------------------------------------------------- +// Errors +//----------------------------------------------------------------------------- + +/** + * The error type when no files match a glob. + */ +class NoFilesFoundError extends Error { + /** + * @param {string} pattern The glob pattern which was not found. + * @param {boolean} globEnabled If `false` then the pattern was a glob pattern, but glob was disabled. + */ + constructor(pattern, globEnabled) { + super( + `No files matching '${pattern}' were found${!globEnabled ? " (glob was disabled)" : ""}.`, + ); + this.messageTemplate = "file-not-found"; + this.messageData = { pattern, globDisabled: !globEnabled }; + } +} + +/** + * The error type when a search fails to match multiple patterns. + */ +class UnmatchedSearchPatternsError extends Error { + /** + * @param {Object} options The options for the error. + * @param {string} options.basePath The directory that was searched. + * @param {Array} options.unmatchedPatterns The glob patterns + * which were not found. + * @param {Array} options.patterns The glob patterns that were + * searched. + * @param {Array} options.rawPatterns The raw glob patterns that + * were searched. + */ + constructor({ basePath, unmatchedPatterns, patterns, rawPatterns }) { + super( + `No files matching '${rawPatterns}' in '${basePath}' were found.`, + ); + this.basePath = basePath; + this.unmatchedPatterns = unmatchedPatterns; + this.patterns = patterns; + this.rawPatterns = rawPatterns; + } +} + +/** + * The error type when there are files matched by a glob, but all of them have been ignored. + */ +class AllFilesIgnoredError extends Error { + /** + * @param {string} pattern The glob pattern which was not found. + */ + constructor(pattern) { + super(`All files matched by '${pattern}' are ignored.`); + this.messageTemplate = "all-matched-files-ignored"; + this.messageData = { pattern }; + } +} + +//----------------------------------------------------------------------------- +// General Helpers +//----------------------------------------------------------------------------- + +/** + * Check if a given value is a non-empty string or not. + * @param {any} value The value to check. + * @returns {boolean} `true` if `value` is a non-empty string. + */ +function isNonEmptyString(value) { + return typeof value === "string" && value.trim() !== ""; +} + +/** + * Check if a given value is an array of non-empty strings or not. + * @param {any} value The value to check. + * @returns {boolean} `true` if `value` is an array of non-empty strings. + */ +function isArrayOfNonEmptyString(value) { + return ( + Array.isArray(value) && !!value.length && value.every(isNonEmptyString) + ); +} + +/** + * Check if a given value is an empty array or an array of non-empty strings. + * @param {any} value The value to check. + * @returns {boolean} `true` if `value` is an empty array or an array of non-empty + * strings. + */ +function isEmptyArrayOrArrayOfNonEmptyString(value) { + return Array.isArray(value) && value.every(isNonEmptyString); +} + +/** + * Check if a given value is a positive integer. + * @param {unknown} value The value to check. + * @returns {boolean} `true` if `value` is a positive integer. + */ +function isPositiveInteger(value) { + return Number.isInteger(value) && value > 0; +} + +//----------------------------------------------------------------------------- +// File-related Helpers +//----------------------------------------------------------------------------- + +/** + * Normalizes slashes in a file pattern to posix-style. + * @param {string} pattern The pattern to replace slashes in. + * @returns {string} The pattern with slashes normalized. + */ +function normalizeToPosix(pattern) { + return pattern.replace(/\\/gu, "/"); +} + +/** + * Check if a string is a glob pattern or not. + * @param {string} pattern A glob pattern. + * @returns {boolean} `true` if the string is a glob pattern. + */ +function isGlobPattern(pattern) { + return isGlob(path.sep === "\\" ? normalizeToPosix(pattern) : pattern); +} + +/** + * Determines if a given glob pattern will return any results. + * Used primarily to help with useful error messages. + * @param {Object} options The options for the function. + * @param {string} options.basePath The directory to search. + * @param {string} options.pattern An absolute path glob pattern to match. + * @returns {Promise} True if there is a glob match, false if not. + */ +async function globMatch({ basePath, pattern }) { + let found = false; + const { hfs } = await import("@humanfs/node"); + const patternToUse = normalizeToPosix(path.relative(basePath, pattern)); + + const matcher = new Minimatch(patternToUse, MINIMATCH_OPTIONS); + + const walkSettings = { + directoryFilter(entry) { + return !found && matcher.match(entry.path, true); + }, + + entryFilter(entry) { + if (found || entry.isDirectory) { + return false; + } + + if (matcher.match(entry.path)) { + found = true; + return true; + } + + return false; + }, + }; + + if (await hfs.isDirectory(basePath)) { + return hfs + .walk(basePath, walkSettings) + .next() + .then(() => found); + } + + return found; +} + +/** + * Searches a directory looking for matching glob patterns. This uses + * the config array's logic to determine if a directory or file should + * be ignored, so it is consistent with how ignoring works throughout + * ESLint. + * @param {Object} options The options for this function. + * @param {string} options.basePath The directory to search. + * @param {Array} options.patterns An array of absolute path glob patterns + * to match. + * @param {Array} options.rawPatterns An array of glob patterns + * as the user inputted them. Used for errors. + * @param {ConfigLoader|LegacyConfigLoader} options.configLoader The config array to use for + * determining what to ignore. + * @param {boolean} options.errorOnUnmatchedPattern Determines if an error + * should be thrown when a pattern is unmatched. + * @returns {Promise>} An array of matching file paths + * or an empty array if there are no matches. + * @throws {UnmatchedSearchPatternsError} If there is a pattern that doesn't + * match any files. + */ +async function globSearch({ + basePath, + patterns, + rawPatterns, + configLoader, + errorOnUnmatchedPattern, +}) { + if (patterns.length === 0) { + return []; + } + + /* + * In this section we are converting the patterns into Minimatch + * instances for performance reasons. Because we are doing the same + * matches repeatedly, it's best to compile those patterns once and + * reuse them multiple times. + * + * To do that, we convert any patterns with an absolute path into a + * relative path and normalize it to Posix-style slashes. We also keep + * track of the relative patterns to map them back to the original + * patterns, which we need in order to throw an error if there are any + * unmatched patterns. + */ + const relativeToPatterns = new Map(); + const matchers = patterns.map((pattern, i) => { + const patternToUse = normalizeToPosix(path.relative(basePath, pattern)); + + relativeToPatterns.set(patternToUse, patterns[i]); + + return new Minimatch(patternToUse, MINIMATCH_OPTIONS); + }); + + /* + * We track unmatched patterns because we may want to throw an error when + * they occur. To start, this set is initialized with all of the patterns. + * Every time a match occurs, the pattern is removed from the set, making + * it easy to tell if we have any unmatched patterns left at the end of + * search. + */ + const unmatchedPatterns = new Set([...relativeToPatterns.keys()]); + const { hfs } = await import("@humanfs/node"); + + const walk = hfs.walk(basePath, { + async directoryFilter(entry) { + if (!matchers.some(matcher => matcher.match(entry.path, true))) { + return false; + } + + const absolutePath = path.resolve(basePath, entry.path); + const configs = + await configLoader.loadConfigArrayForDirectory(absolutePath); + + return !configs.isDirectoryIgnored(absolutePath); + }, + async entryFilter(entry) { + const absolutePath = path.resolve(basePath, entry.path); + + // entries may be directories or files so filter out directories + if (entry.isDirectory) { + return false; + } + + const configs = + await configLoader.loadConfigArrayForFile(absolutePath); + const config = configs.getConfig(absolutePath); + + /* + * Optimization: We need to track when patterns are left unmatched + * and so we use `unmatchedPatterns` to do that. There is a bit of + * complexity here because the same file can be matched by more than + * one pattern. So, when we start, we actually need to test every + * pattern against every file. Once we know there are no remaining + * unmatched patterns, then we can switch to just looking for the + * first matching pattern for improved speed. + */ + const matchesPattern = + unmatchedPatterns.size > 0 + ? matchers.reduce((previousValue, matcher) => { + const pathMatches = matcher.match(entry.path); + + /* + * We updated the unmatched patterns set only if the path + * matches and the file has a config. If the file has no + * config, that means there wasn't a match for the + * pattern so it should not be removed. + * + * Performance note: `getConfig()` aggressively caches + * results so there is no performance penalty for calling + * it multiple times with the same argument. + */ + if (pathMatches && config) { + unmatchedPatterns.delete(matcher.pattern); + } + + return pathMatches || previousValue; + }, false) + : matchers.some(matcher => matcher.match(entry.path)); + + return matchesPattern && config !== void 0; + }, + }); + + const filePaths = []; + + if (await hfs.isDirectory(basePath)) { + for await (const entry of walk) { + filePaths.push(path.resolve(basePath, entry.path)); + } + } + + // now check to see if we have any unmatched patterns + if (errorOnUnmatchedPattern && unmatchedPatterns.size > 0) { + throw new UnmatchedSearchPatternsError({ + basePath, + unmatchedPatterns: [...unmatchedPatterns].map(pattern => + relativeToPatterns.get(pattern), + ), + patterns, + rawPatterns, + }); + } + + return filePaths; +} + +/** + * Throws an error for unmatched patterns. The error will only contain information about the first one. + * Checks to see if there are any ignored results for a given search. + * @param {Object} options The options for this function. + * @param {string} options.basePath The directory to search. + * @param {Array} options.patterns An array of glob patterns + * that were used in the original search. + * @param {Array} options.rawPatterns An array of glob patterns + * as the user inputted them. Used for errors. + * @param {Array} options.unmatchedPatterns A non-empty array of absolute path glob patterns + * that were unmatched in the original search. + * @returns {Promise} Always throws an error. + * @throws {NoFilesFoundError} If the first unmatched pattern + * doesn't match any files even when there are no ignores. + * @throws {AllFilesIgnoredError} If the first unmatched pattern + * matches some files when there are no ignores. + */ +async function throwErrorForUnmatchedPatterns({ + basePath, + patterns, + rawPatterns, + unmatchedPatterns, +}) { + const pattern = unmatchedPatterns[0]; + const rawPattern = rawPatterns[patterns.indexOf(pattern)]; + + const patternHasMatch = await globMatch({ + basePath, + pattern, + }); + + if (patternHasMatch) { + throw new AllFilesIgnoredError(rawPattern); + } + + // if we get here there are truly no matches + throw new NoFilesFoundError(rawPattern, true); +} + +/** + * Performs multiple glob searches in parallel. + * @param {Object} options The options for this function. + * @param {Map} options.searches + * A map of absolute path glob patterns to match. + * @param {ConfigLoader|LegacyConfigLoader} options.configLoader The config loader to use for + * determining what to ignore. + * @param {boolean} options.errorOnUnmatchedPattern Determines if an + * unmatched glob pattern should throw an error. + * @returns {Promise>} An array of matching file paths + * or an empty array if there are no matches. + */ +async function globMultiSearch({ + searches, + configLoader, + errorOnUnmatchedPattern, +}) { + /* + * For convenience, we normalized the search map into an array of objects. + * Next, we filter out all searches that have no patterns. This happens + * primarily for the cwd, which is prepopulated in the searches map as an + * optimization. However, if it has no patterns, it means all patterns + * occur outside of the cwd and we can safely filter out that search. + */ + const normalizedSearches = [...searches] + .map(([basePath, { patterns, rawPatterns }]) => ({ + basePath, + patterns, + rawPatterns, + })) + .filter(({ patterns }) => patterns.length > 0); + + const results = await Promise.allSettled( + normalizedSearches.map(({ basePath, patterns, rawPatterns }) => + globSearch({ + basePath, + patterns, + rawPatterns, + configLoader, + errorOnUnmatchedPattern, + }), + ), + ); + + /* + * The first loop handles errors from the glob searches. Since we can't + * use `await` inside `flatMap`, we process errors separately in this loop. + * This results in two iterations over `results`, but since the length is + * less than or equal to the number of globs and directories passed on the + * command line, the performance impact should be minimal. + */ + for (let i = 0; i < results.length; i++) { + const result = results[i]; + const currentSearch = normalizedSearches[i]; + + if (result.status === "fulfilled") { + continue; + } + + // if we make it here then there was an error + const error = result.reason; + + // unexpected errors should be re-thrown + if (!error.basePath) { + throw error; + } + + if (errorOnUnmatchedPattern) { + await throwErrorForUnmatchedPatterns({ + ...currentSearch, + unmatchedPatterns: error.unmatchedPatterns, + }); + } + } + + // second loop for `fulfilled` results + return results.flatMap(result => result.value); +} + +/** + * Finds all files matching the options specified. + * @param {Object} args The arguments objects. + * @param {Array} args.patterns An array of glob patterns. + * @param {boolean} args.globInputPaths true to interpret glob patterns, + * false to not interpret glob patterns. + * @param {string} args.cwd The current working directory to find from. + * @param {ConfigLoader|LegacyConfigLoader} args.configLoader The config loader for the current run. + * @param {boolean} args.errorOnUnmatchedPattern Determines if an unmatched pattern + * should throw an error. + * @returns {Promise>} The fully resolved file paths. + * @throws {AllFilesIgnoredError} If there are no results due to an ignore pattern. + * @throws {NoFilesFoundError} If no files matched the given patterns. + */ +async function findFiles({ + patterns, + globInputPaths, + cwd, + configLoader, + errorOnUnmatchedPattern, +}) { + const results = []; + const missingPatterns = []; + let globbyPatterns = []; + let rawPatterns = []; + const searches = new Map([ + [cwd, { patterns: globbyPatterns, rawPatterns: [] }], + ]); + + /* + * This part is a bit involved because we need to account for + * the different ways that the patterns can match directories. + * For each different way, we need to decide if we should look + * for a config file or just use the default config. (Directories + * without a config file always use the default config.) + * + * Here are the cases: + * + * 1. A directory is passed directly (e.g., "subdir"). In this case, we + * can assume that the user intends to lint this directory and we should + * not look for a config file in the parent directory, because the only + * reason to do that would be to ignore this directory (which we already + * know we don't want to do). Instead, we use the default config until we + * get to the directory that was passed, at which point we start looking + * for config files again. + * + * 2. A dot (".") or star ("*"). In this case, we want to read + * the config file in the current directory because the user is + * explicitly asking to lint the current directory. Note that "." + * will traverse into subdirectories while "*" will not. + * + * 3. A directory is passed in the form of "subdir/subsubdir". + * In this case, we don't want to look for a config file in the + * parent directory ("subdir"). We can skip looking for a config + * file until `entry.depth` is greater than 1 because there's no + * way that the pattern can match `entry.path` yet. + * + * 4. A directory glob pattern is passed (e.g., "subd*"). We want + * this case to act like case 2 because it's unclear whether or not + * any particular directory is meant to be traversed. + * + * 5. A recursive glob pattern is passed (e.g., "**"). We want this + * case to act like case 2. + */ + + // check to see if we have explicit files and directories + const filePaths = patterns.map(filePath => path.resolve(cwd, filePath)); + const stats = await Promise.all( + filePaths.map(filePath => fsp.stat(filePath).catch(() => {})), + ); + + const promises = []; + stats.forEach((stat, index) => { + const filePath = filePaths[index]; + const pattern = normalizeToPosix(patterns[index]); + + if (stat) { + // files are added directly to the list + if (stat.isFile()) { + results.push(filePath); + promises.push(configLoader.loadConfigArrayForFile(filePath)); + } + + // directories need extensions attached + if (stat.isDirectory()) { + if (!searches.has(filePath)) { + searches.set(filePath, { patterns: [], rawPatterns: [] }); + } + ({ patterns: globbyPatterns, rawPatterns } = + searches.get(filePath)); + + globbyPatterns.push(`${normalizeToPosix(filePath)}/**`); + rawPatterns.push(pattern); + } + + return; + } + + // save patterns for later use based on whether globs are enabled + if (globInputPaths && isGlobPattern(pattern)) { + /* + * We are grouping patterns by their glob parent. This is done to + * make it easier to determine when a config file should be loaded. + */ + + const basePath = path.resolve(cwd, globParent(pattern)); + + if (!searches.has(basePath)) { + searches.set(basePath, { patterns: [], rawPatterns: [] }); + } + ({ patterns: globbyPatterns, rawPatterns } = + searches.get(basePath)); + + globbyPatterns.push(filePath); + rawPatterns.push(pattern); + } else { + missingPatterns.push(pattern); + } + }); + + // there were patterns that didn't match anything, tell the user + if (errorOnUnmatchedPattern && missingPatterns.length) { + throw new NoFilesFoundError(missingPatterns[0], globInputPaths); + } + + // now we are safe to do the search + promises.push( + globMultiSearch({ + searches, + configLoader, + errorOnUnmatchedPattern, + }), + ); + const globbyResults = (await Promise.all(promises)).at(-1); + + return [...new Set([...results, ...globbyResults])]; +} + +/** + * Return the absolute path of a file named `"__placeholder__.js"` in a given directory. + * This is used as a replacement for a missing file path. + * @param {string} cwd An absolute directory path. + * @returns {string} The absolute path of a file named `"__placeholder__.js"` in the given directory. + */ +function getPlaceholderPath(cwd) { + return path.join(cwd, "__placeholder__.js"); +} + +//----------------------------------------------------------------------------- +// Results-related Helpers +//----------------------------------------------------------------------------- + +/** + * Checks if the given message is an error message. + * @param {LintMessage} message The message to check. + * @returns {boolean} Whether or not the message is an error message. + * @private + */ +function isErrorMessage(message) { + return message.severity === 2; +} + +/** + * Returns result with warning by ignore settings + * @param {string} filePath Absolute file path of checked code + * @param {string} baseDir Absolute path of base directory + * @param {"ignored"|"external"|"unconfigured"} configStatus A status that determines why the file is ignored + * @returns {LintResult} Result with single warning + * @private + */ +function createIgnoreResult(filePath, baseDir, configStatus) { + let message; + + switch (configStatus) { + case "external": + message = "File ignored because outside of base path."; + break; + case "unconfigured": + message = + "File ignored because no matching configuration was supplied."; + break; + default: + { + const isInNodeModules = + baseDir && + path + .dirname(path.relative(baseDir, filePath)) + .split(path.sep) + .includes("node_modules"); + + if (isInNodeModules) { + message = + 'File ignored by default because it is located under the node_modules directory. Use ignore pattern "!**/node_modules/" to disable file ignore settings or use "--no-warn-ignored" to suppress this warning.'; + } else { + message = + 'File ignored because of a matching ignore pattern. Use "--no-ignore" to disable file ignore settings or use "--no-warn-ignored" to suppress this warning.'; + } + } + break; + } + + return { + filePath, + messages: [ + { + ruleId: null, + fatal: false, + severity: 1, + message, + nodeType: null, + }, + ], + suppressedMessages: [], + errorCount: 0, + warningCount: 1, + fatalErrorCount: 0, + fixableErrorCount: 0, + fixableWarningCount: 0, + }; +} + +/** + * It will calculate the error and warning count for collection of messages per file + * @param {LintMessage[]} messages Collection of messages + * @returns {Object} Contains the stats + * @private + */ +function calculateStatsPerFile(messages) { + const stat = { + errorCount: 0, + fatalErrorCount: 0, + warningCount: 0, + fixableErrorCount: 0, + fixableWarningCount: 0, + }; + + for (let i = 0; i < messages.length; i++) { + const message = messages[i]; + + if (message.fatal || message.severity === 2) { + stat.errorCount++; + if (message.fatal) { + stat.fatalErrorCount++; + } + if (message.fix) { + stat.fixableErrorCount++; + } + } else { + stat.warningCount++; + if (message.fix) { + stat.fixableWarningCount++; + } + } + } + return stat; +} + +//----------------------------------------------------------------------------- +// Options-related Helpers +//----------------------------------------------------------------------------- + +/** + * Check if a given value is a valid fix type or not. + * @param {any} x The value to check. + * @returns {boolean} `true` if `x` is valid fix type. + */ +function isFixType(x) { + return ( + x === "directive" || + x === "problem" || + x === "suggestion" || + x === "layout" + ); +} + +/** + * Check if a given value is an array of fix types or not. + * @param {any} x The value to check. + * @returns {boolean} `true` if `x` is an array of fix types. + */ +function isFixTypeArray(x) { + return Array.isArray(x) && x.every(isFixType); +} + +/** + * The error for invalid options. + */ +class ESLintInvalidOptionsError extends Error { + constructor(messages) { + super(`Invalid Options:\n- ${messages.join("\n- ")}`); + this.code = "ESLINT_INVALID_OPTIONS"; + Error.captureStackTrace(this, ESLintInvalidOptionsError); + } +} + +/** + * Validates and normalizes options for the wrapped CLIEngine instance. + * @param {ESLintOptions} options The options to process. + * @throws {ESLintInvalidOptionsError} If of any of a variety of type errors. + * @returns {ESLintOptions} The normalized options. + */ +function processOptions({ + allowInlineConfig = true, // ← we cannot use `overrideConfig.noInlineConfig` instead because `allowInlineConfig` has side-effect that suppress warnings that show inline configs are ignored. + baseConfig = null, + cache = false, + cacheLocation = ".eslintcache", + cacheStrategy = "metadata", + concurrency = "off", + cwd = process.cwd(), + errorOnUnmatchedPattern = true, + fix = false, + fixTypes = null, // ← should be null by default because if it's an array then it suppresses rules that don't have the `meta.type` property. + flags = [], + globInputPaths = true, + ignore = true, + ignorePatterns = null, + overrideConfig = null, + overrideConfigFile = null, + plugins = {}, + stats = false, + warnIgnored = true, + passOnNoPatterns = false, + ruleFilter = () => true, + ...unknownOptions +}) { + const errors = []; + const unknownOptionKeys = Object.keys(unknownOptions); + + if (unknownOptionKeys.length >= 1) { + errors.push(`Unknown options: ${unknownOptionKeys.join(", ")}`); + if (unknownOptionKeys.includes("cacheFile")) { + errors.push( + "'cacheFile' has been removed. Please use the 'cacheLocation' option instead.", + ); + } + if (unknownOptionKeys.includes("configFile")) { + errors.push( + "'configFile' has been removed. Please use the 'overrideConfigFile' option instead.", + ); + } + if (unknownOptionKeys.includes("envs")) { + errors.push("'envs' has been removed."); + } + if (unknownOptionKeys.includes("extensions")) { + errors.push("'extensions' has been removed."); + } + if (unknownOptionKeys.includes("resolvePluginsRelativeTo")) { + errors.push("'resolvePluginsRelativeTo' has been removed."); + } + if (unknownOptionKeys.includes("globals")) { + errors.push( + "'globals' has been removed. Please use the 'overrideConfig.languageOptions.globals' option instead.", + ); + } + if (unknownOptionKeys.includes("ignorePath")) { + errors.push("'ignorePath' has been removed."); + } + if (unknownOptionKeys.includes("ignorePattern")) { + errors.push( + "'ignorePattern' has been removed. Please use the 'overrideConfig.ignorePatterns' option instead.", + ); + } + if (unknownOptionKeys.includes("parser")) { + errors.push( + "'parser' has been removed. Please use the 'overrideConfig.languageOptions.parser' option instead.", + ); + } + if (unknownOptionKeys.includes("parserOptions")) { + errors.push( + "'parserOptions' has been removed. Please use the 'overrideConfig.languageOptions.parserOptions' option instead.", + ); + } + if (unknownOptionKeys.includes("rules")) { + errors.push( + "'rules' has been removed. Please use the 'overrideConfig.rules' option instead.", + ); + } + if (unknownOptionKeys.includes("rulePaths")) { + errors.push( + "'rulePaths' has been removed. Please define your rules using plugins.", + ); + } + if (unknownOptionKeys.includes("reportUnusedDisableDirectives")) { + errors.push( + "'reportUnusedDisableDirectives' has been removed. Please use the 'overrideConfig.linterOptions.reportUnusedDisableDirectives' option instead.", + ); + } + } + if (typeof allowInlineConfig !== "boolean") { + errors.push("'allowInlineConfig' must be a boolean."); + } + if (typeof baseConfig !== "object") { + errors.push("'baseConfig' must be an object or null."); + } + if (typeof cache !== "boolean") { + errors.push("'cache' must be a boolean."); + } + if (!isNonEmptyString(cacheLocation)) { + errors.push("'cacheLocation' must be a non-empty string."); + } + if (cacheStrategy !== "metadata" && cacheStrategy !== "content") { + errors.push('\'cacheStrategy\' must be any of "metadata", "content".'); + } + if ( + concurrency !== "off" && + concurrency !== "auto" && + !isPositiveInteger(concurrency) + ) { + errors.push( + '\'concurrency\' must be a positive integer, "auto", or "off".', + ); + } + if (!isNonEmptyString(cwd) || !path.isAbsolute(cwd)) { + errors.push("'cwd' must be an absolute path."); + } + if (typeof errorOnUnmatchedPattern !== "boolean") { + errors.push("'errorOnUnmatchedPattern' must be a boolean."); + } + if (typeof fix !== "boolean" && typeof fix !== "function") { + errors.push("'fix' must be a boolean or a function."); + } + if (fixTypes !== null && !isFixTypeArray(fixTypes)) { + errors.push( + '\'fixTypes\' must be an array of any of "directive", "problem", "suggestion", and "layout".', + ); + } + if (!isEmptyArrayOrArrayOfNonEmptyString(flags)) { + errors.push("'flags' must be an array of non-empty strings."); + } + if (typeof globInputPaths !== "boolean") { + errors.push("'globInputPaths' must be a boolean."); + } + if (typeof ignore !== "boolean") { + errors.push("'ignore' must be a boolean."); + } + if ( + !isEmptyArrayOrArrayOfNonEmptyString(ignorePatterns) && + ignorePatterns !== null + ) { + errors.push( + "'ignorePatterns' must be an array of non-empty strings or null.", + ); + } + if (typeof overrideConfig !== "object") { + errors.push("'overrideConfig' must be an object or null."); + } + if ( + !isNonEmptyString(overrideConfigFile) && + overrideConfigFile !== null && + overrideConfigFile !== true + ) { + errors.push( + "'overrideConfigFile' must be a non-empty string, null, or true.", + ); + } + if (typeof passOnNoPatterns !== "boolean") { + errors.push("'passOnNoPatterns' must be a boolean."); + } + if (typeof plugins !== "object") { + errors.push("'plugins' must be an object or null."); + } else if (plugins !== null && Object.keys(plugins).includes("")) { + errors.push("'plugins' must not include an empty string."); + } + if (Array.isArray(plugins)) { + errors.push( + "'plugins' doesn't add plugins to configuration to load. Please use the 'overrideConfig.plugins' option instead.", + ); + } + if (typeof stats !== "boolean") { + errors.push("'stats' must be a boolean."); + } + if (typeof warnIgnored !== "boolean") { + errors.push("'warnIgnored' must be a boolean."); + } + if (typeof ruleFilter !== "function") { + errors.push("'ruleFilter' must be a function."); + } + if (errors.length > 0) { + throw new ESLintInvalidOptionsError(errors); + } + + return { + allowInlineConfig, + baseConfig, + cache, + cacheLocation, + cacheStrategy, + concurrency, + + // when overrideConfigFile is true that means don't do config file lookup + configFile: overrideConfigFile === true ? false : overrideConfigFile, + overrideConfig, + cwd: path.normalize(cwd), + errorOnUnmatchedPattern, + fix, + fixTypes, + flags: [...flags], + globInputPaths, + ignore, + ignorePatterns, + stats, + passOnNoPatterns, + warnIgnored, + ruleFilter, + }; +} + +/** + * Loads ESLint constructor options from an options module. + * @param {string} optionsURL The URL string of the options module to load. + * @returns {Promise} ESLint constructor options. + */ +async function loadOptionsFromModule(optionsURL) { + return (await import(optionsURL)).default; +} + +//----------------------------------------------------------------------------- +// Cache-related helpers +//----------------------------------------------------------------------------- + +/** + * return the cacheFile to be used by eslint, based on whether the provided parameter is + * a directory or looks like a directory (ends in `path.sep`), in which case the file + * name will be the `cacheFile/.cache_hashOfCWD` + * + * if cacheFile points to a file or looks like a file then in will just use that file + * @param {string} cacheFile The name of file to be used to store the cache + * @param {string} cwd Current working directory + * @param {Object} options The options + * @param {string} [options.prefix] The prefix to use for the cache file + * @returns {string} the resolved path to the cache file + */ +function getCacheFile(cacheFile, cwd, { prefix = ".cache_" } = {}) { + /* + * make sure the path separators are normalized for the environment/os + * keeping the trailing path separator if present + */ + const normalizedCacheFile = path.normalize(cacheFile); + + const resolvedCacheFile = path.resolve(cwd, normalizedCacheFile); + const looksLikeADirectory = normalizedCacheFile.slice(-1) === path.sep; + + /** + * return the name for the cache file in case the provided parameter is a directory + * @returns {string} the resolved path to the cacheFile + */ + function getCacheFileForDirectory() { + return path.join(resolvedCacheFile, `${prefix}${hash(cwd)}`); + } + + let fileStats; + + try { + fileStats = fs.lstatSync(resolvedCacheFile); + } catch { + fileStats = null; + } + + /* + * in case the file exists we need to verify if the provided path + * is a directory or a file. If it is a directory we want to create a file + * inside that directory + */ + if (fileStats) { + /* + * is a directory or is a file, but the original file the user provided + * looks like a directory but `path.resolve` removed the `last path.sep` + * so we need to still treat this like a directory + */ + if (fileStats.isDirectory() || looksLikeADirectory) { + return getCacheFileForDirectory(); + } + + // is file so just use that file + return resolvedCacheFile; + } + + /* + * here we known the file or directory doesn't exist, + * so we will try to infer if its a directory if it looks like a directory + * for the current operating system. + */ + + // if the last character passed is a path separator we assume is a directory + if (looksLikeADirectory) { + return getCacheFileForDirectory(); + } + + return resolvedCacheFile; +} + +/** + * Creates a new lint result cache. + * @param {ESLintOptions} eslintOptions The processed ESLint options. + * @param {string} cacheFilePath The path to the cache file. + * @returns {?LintResultCache} A new lint result cache or `null`. + */ +function createLintResultCache({ cache, cacheStrategy }, cacheFilePath) { + return cache ? new LintResultCache(cacheFilePath, cacheStrategy) : null; +} + +//----------------------------------------------------------------------------- +// Lint helpers +//----------------------------------------------------------------------------- + +/** + * Checks whether a message's rule type should be fixed. + * @param {LintMessage} message The message to check. + * @param {CalculatedConfig} config The config for the file that generated the message. + * @param {string[]} fixTypes An array of fix types to check. + * @returns {boolean} Whether the message should be fixed. + */ +function shouldMessageBeFixed(message, config, fixTypes) { + if (!message.ruleId) { + return fixTypes.has("directive"); + } + + const rule = message.ruleId && config.getRuleDefinition(message.ruleId); + + return Boolean(rule && rule.meta && fixTypes.has(rule.meta.type)); +} + +/** + * Creates a fixer function based on the provided fix, fixTypesSet, and config. + * @param {Function|boolean} fix The original fix option. + * @param {Set} fixTypesSet A set of fix types to filter messages for fixing. + * @param {CalculatedConfig} config The config for the file that generated the message. + * @returns {Function|boolean} The fixer function or the original fix value. + */ +function getFixerForFixTypes(fix, fixTypesSet, config) { + if (!fix || !fixTypesSet) { + return fix; + } + + const originalFix = typeof fix === "function" ? fix : () => true; + + return message => + shouldMessageBeFixed(message, config, fixTypesSet) && + originalFix(message); +} + +/** + * Processes a source code using ESLint. + * @param {Object} config The config object. + * @param {string} config.text The source code to verify. + * @param {string} config.cwd The path to the current working directory. + * @param {string|undefined} config.filePath The path to the file of `text`. If this is undefined, it uses ``. + * @param {FlatConfigArray} config.configs The config. + * @param {boolean} config.fix If `true` then it does fix. + * @param {boolean} config.allowInlineConfig If `true` then it uses directive comments. + * @param {Function} config.ruleFilter A predicate function to filter which rules should be run. + * @param {boolean} config.stats If `true`, then if reports extra statistics with the lint results. + * @param {Linter} config.linter The linter instance to verify. + * @returns {LintResult} The result of linting. + * @private + */ +function verifyText({ + text, + cwd, + filePath: providedFilePath, + configs, + fix, + allowInlineConfig, + ruleFilter, + stats, + linter, +}) { + const startTime = hrtimeBigint(); + + const filePath = providedFilePath || ""; + + /* + * Verify. + * `config.extractConfig(filePath)` requires an absolute path, but `linter` + * doesn't know CWD, so it gives `linter` an absolute path always. + */ + const filePathToVerify = + filePath === "" ? getPlaceholderPath(cwd) : filePath; + const { fixed, messages, output } = linter.verifyAndFix(text, configs, { + allowInlineConfig, + filename: filePathToVerify, + fix, + ruleFilter, + stats, + + /** + * Check if the linter should adopt a given code block or not. + * @param {string} blockFilename The virtual filename of a code block. + * @returns {boolean} `true` if the linter should adopt the code block. + */ + filterCodeBlock(blockFilename) { + return configs.getConfig(blockFilename) !== void 0; + }, + }); + + // Tweak and return. + const result = { + filePath: filePath === "" ? filePath : path.resolve(filePath), + messages, + suppressedMessages: linter.getSuppressedMessages(), + ...calculateStatsPerFile(messages), + }; + + if (fixed) { + result.output = output; + } + + if ( + result.errorCount + result.warningCount > 0 && + typeof result.output === "undefined" + ) { + result.source = text; + } + + if (stats) { + result.stats = { + times: linter.getTimes(), + fixPasses: linter.getFixPassCount(), + }; + } + + const endTime = hrtimeBigint(); + debug('File "%s" linted in %t', filePath, endTime - startTime); + + return result; +} + +/** + * Lints a single file. + * @param {string} filePath File path to lint. + * @param {FlatConfigArray} configs The config array for the file. + * @param {ESLintOptions} eslintOptions The processed ESLint options. + * @param {Linter} linter The linter instance to use. + * @param {?LintResultCache} lintResultCache The result cache or `null`. + * @param {?{ duration: bigint; }} readFileCounter Used to keep track of the time spent reading files. + * @param {Retrier} [retrier] Used to retry linting on certain errors. + * @param {AbortController} [controller] Used to stop linting when an error occurs. + * @returns {Promise} The lint result. + */ +async function lintFile( + filePath, + configs, + eslintOptions, + linter, + lintResultCache, + readFileCounter, + retrier, + controller, +) { + const config = configs.getConfig(filePath); + const { + allowInlineConfig, + cwd, + fix, + fixTypes, + ruleFilter, + stats, + warnIgnored, + } = eslintOptions; + const fixTypesSet = fixTypes ? new Set(fixTypes) : null; + + /* + * If a filename was entered that cannot be matched + * to a config, then notify the user. + */ + if (!config) { + if (warnIgnored) { + const configStatus = configs.getConfigStatus(filePath); + + return createIgnoreResult(filePath, cwd, configStatus); + } + + return void 0; + } + + // Skip if there is cached result. + if (lintResultCache) { + const cachedResult = lintResultCache.getCachedLintResults( + filePath, + config, + ); + + if (cachedResult) { + const hadMessages = + cachedResult.messages && cachedResult.messages.length > 0; + + if (hadMessages && fix) { + debug(`Reprocessing cached file to allow autofix: ${filePath}`); + } else { + debug(`Skipping file since it hasn't changed: ${filePath}`); + return cachedResult; + } + } + } + + // set up fixer for fixTypes if necessary + const fixer = getFixerForFixTypes(fix, fixTypesSet, config); + + /** + * Reads the file and lints its content. + * @returns {Promise} A lint result. + */ + async function readAndVerifyFile() { + const readFileEnterTime = hrtimeBigint(); + const text = await fsp.readFile(filePath, { + encoding: "utf8", + signal: controller?.signal, + }); + const readFileExitTime = hrtimeBigint(); + const readFileDuration = readFileExitTime - readFileEnterTime; + debug('File "%s" read in %t', filePath, readFileDuration); + if (readFileCounter) { + readFileCounter.duration += readFileDuration; + } + + // fail immediately if an error occurred in another file + controller?.signal.throwIfAborted(); + + // do the linting + return verifyText({ + text, + filePath, + configs, + cwd, + fix: fixer, + allowInlineConfig, + ruleFilter, + stats, + linter, + }); + } + + // Use the retrier if provided, otherwise just call the function. + const readAndVerifyFilePromise = retrier + ? retrier.retry(readAndVerifyFile, { signal: controller?.signal }) + : readAndVerifyFile(); + + return readAndVerifyFilePromise.catch(error => { + controller?.abort(error); + throw error; + }); +} + +/** + * Retrieves flags from the environment variable ESLINT_FLAGS. + * @param {string[]} flags The flags defined via the API. + * @returns {string[]} The merged flags to use. + */ +function mergeEnvironmentFlags(flags) { + if (!process.env.ESLINT_FLAGS) { + return flags; + } + + const envFlags = process.env.ESLINT_FLAGS.trim().split(/\s*,\s*/gu); + return Array.from(new Set([...envFlags, ...flags])); +} + +/** + * Creates a new linter instance. + * @param {ESLintOptions} eslintOptions The processed ESLint options. + * @param {WarningService} warningService The warning service to use. + * @returns {Linter} The linter instance. + */ +function createLinter({ cwd, flags }, warningService) { + return new Linter({ + configType: "flat", + cwd, + flags: mergeEnvironmentFlags(flags), + warningService, + }); +} + +/** + * Creates default configs with the specified plugins. + * @param {Record | undefined} optionPlugins The plugins specified in the ESLint options. + * @returns {Config[]} The default configs. + */ +function createDefaultConfigs(optionPlugins) { + const defaultConfigs = []; + + // Add plugins + if (optionPlugins) { + const plugins = {}; + + for (const [pluginName, plugin] of Object.entries(optionPlugins)) { + plugins[getShorthandName(pluginName, "eslint-plugin")] = plugin; + } + + defaultConfigs.push({ plugins }); + } + + return defaultConfigs; +} + +/** + * Creates a config loader. + * @param {ESLintOptions} eslintOptions The processed ESLint options. + * @param {Config[]} defaultConfigs The default configs. + * @param {Linter} linter The linter instance. + * @param {WarningService} warningService The warning service to use. + * @returns {ConfigLoader} The config loader. + */ +function createConfigLoader( + { + cwd, + baseConfig, + overrideConfig, + configFile, + ignore: ignoreEnabled, + ignorePatterns, + }, + defaultConfigs, + linter, + warningService, +) { + const configLoaderOptions = { + cwd, + baseConfig, + overrideConfig, + configFile, + ignoreEnabled, + ignorePatterns, + defaultConfigs, + hasUnstableNativeNodeJsTSConfigFlag: linter.hasFlag( + "unstable_native_nodejs_ts_config", + ), + warningService, + }; + + return linter.hasFlag("v10_config_lookup_from_file") + ? new ConfigLoader(configLoaderOptions) + : new LegacyConfigLoader(configLoaderOptions); +} + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +module.exports = { + createDebug, + + findFiles, + + isNonEmptyString, + isArrayOfNonEmptyString, + + createIgnoreResult, + isErrorMessage, + calculateStatsPerFile, + getPlaceholderPath, + + processOptions, + loadOptionsFromModule, + + getCacheFile, + createLintResultCache, + + getFixerForFixTypes, + verifyText, + lintFile, + createLinter, + createDefaultConfigs, + createConfigLoader, +}; diff --git a/tools/ui/node_modules/eslint/lib/eslint/eslint.js b/tools/ui/node_modules/eslint/lib/eslint/eslint.js new file mode 100644 index 0000000000000000000000000000000000000000..92e90b3e2cde00a476b832f8370fe3fa23ef1ac4 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/eslint/eslint.js @@ -0,0 +1,1362 @@ +/** + * @fileoverview Main class using flat config + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { existsSync } = require("node:fs"); +const fs = require("node:fs/promises"); +const os = require("node:os"); +const path = require("node:path"); +const { pathToFileURL } = require("node:url"); +const { SHARE_ENV, Worker } = require("node:worker_threads"); +const { version } = require("../../package.json"); +const { defaultConfig } = require("../config/default-config"); +const timing = require("../linter/timing"); + +const { + createDebug, + + findFiles, + getCacheFile, + + isNonEmptyString, + isArrayOfNonEmptyString, + + createIgnoreResult, + isErrorMessage, + getPlaceholderPath, + + processOptions, + loadOptionsFromModule, + + getFixerForFixTypes, + verifyText, + lintFile, + createLinter, + createLintResultCache, + createDefaultConfigs, + createConfigLoader, +} = require("./eslint-helpers"); +const { Retrier } = require("@humanwhocodes/retry"); +const { ConfigLoader } = require("../config/config-loader"); +const { WarningService } = require("../services/warning-service"); +const { Config } = require("../config/config.js"); +const { + getShorthandName, + getNamespaceFromTerm, + normalizePackageName, +} = require("../shared/naming.js"); +const { resolve } = require("../shared/relative-module-resolver.js"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +// For VSCode IntelliSense +/** + * @import { Config as CalculatedConfig } from "../config/config.js"; + * @import { FlatConfigArray } from "../config/flat-config-array.js"; + * @import { RuleDefinition, RulesMeta } from "@eslint/core"; + * @import { WorkerLintResults } from "./worker.js"; + */ + +/** @typedef {import("../types").Linter.Config} Config */ +/** @typedef {import("../types").ESLint.DeprecatedRuleUse} DeprecatedRuleInfo */ +/** @typedef {import("../types").ESLint.LintResult} LintResult */ +/** @typedef {import("../types").ESLint.Plugin} Plugin */ +/** @typedef {import("../types").ESLint.ResultsMeta} ResultsMeta */ + +/** + * The options with which to configure the ESLint instance. + * @typedef {Object} ESLintOptions + * @property {boolean} [allowInlineConfig] Enable or disable inline configuration comments. + * @property {Config|Array} [baseConfig] Base config, extended by all configs used with this instance + * @property {boolean} [cache] Enable result caching. + * @property {string} [cacheLocation] The cache file to use instead of .eslintcache. + * @property {"metadata" | "content"} [cacheStrategy] The strategy used to detect changed files. + * @property {number | "auto" | "off"} [concurrency] Maximum number of linting threads, "auto" to choose automatically, "off" for no multithreading. + * @property {string} [cwd] The value to use for the current working directory. + * @property {boolean} [errorOnUnmatchedPattern] If `false` then `ESLint#lintFiles()` doesn't throw even if no target files found. Defaults to `true`. + * @property {boolean|Function} [fix] Execute in autofix mode. If a function, should return a boolean. + * @property {string[]} [fixTypes] Array of rule types to apply fixes for. + * @property {string[]} [flags] Array of feature flags to enable. + * @property {boolean} [globInputPaths] Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file. + * @property {boolean} [ignore] False disables all ignore patterns except for the default ones. + * @property {string[]} [ignorePatterns] Ignore file patterns to use in addition to config ignores. These patterns are relative to `cwd`. + * @property {Config|Array} [overrideConfig] Override config, overrides all configs used with this instance + * @property {boolean|string} [overrideConfigFile] Searches for default config file when falsy; + * doesn't do any config file lookup when `true`; considered to be a config filename + * when a string. + * @property {boolean} [passOnNoPatterns=false] When set to true, missing patterns cause + * the linting operation to short circuit and not report any failures. + * @property {Record} [plugins] An array of plugin implementations. + * @property {boolean} [stats] True enables added statistics on lint results. + * @property {boolean} [warnIgnored] Show warnings when the file list includes ignored files + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const hrtimeBigint = process.hrtime.bigint; + +const debug = createDebug("eslint:eslint"); +const privateMembers = new WeakMap(); +const removedFormatters = new Set([ + "checkstyle", + "codeframe", + "compact", + "jslint-xml", + "junit", + "table", + "tap", + "unix", + "visualstudio", +]); +const fileRetryCodes = new Set(["ENFILE", "EMFILE"]); + +/** + * Create rulesMeta object. + * @param {Map} rules a map of rules from which to generate the object. + * @returns {Record} metadata for all enabled rules. + */ +function createRulesMeta(rules) { + return Array.from(rules).reduce((retVal, [id, rule]) => { + retVal[id] = rule.meta; + return retVal; + }, {}); +} + +/** @type {WeakMap} */ +const usedDeprecatedRulesCache = new WeakMap(); + +/** + * Create used deprecated rule list. + * @param {ESLint} eslint The ESLint instance. + * @param {string} maybeFilePath The absolute path to a lint target file or `""`. + * @returns {DeprecatedRuleInfo[]} The used deprecated rule list. + */ +function getOrFindUsedDeprecatedRules(eslint, maybeFilePath) { + const { + options: { cwd }, + configLoader, + } = privateMembers.get(eslint); + const filePath = path.isAbsolute(maybeFilePath) + ? maybeFilePath + : getPlaceholderPath(cwd); + const configs = configLoader.getCachedConfigArrayForFile(filePath); + const config = configs.getConfig(filePath); + + // Most files use the same config, so cache it. + if (config && !usedDeprecatedRulesCache.has(config)) { + const retv = []; + + if (config.rules) { + for (const [ruleId, ruleConf] of Object.entries(config.rules)) { + if (Config.getRuleNumericSeverity(ruleConf) === 0) { + continue; + } + const rule = config.getRuleDefinition(ruleId); + const meta = rule && rule.meta; + + if (meta && meta.deprecated) { + const usesNewFormat = typeof meta.deprecated === "object"; + + retv.push({ + ruleId, + replacedBy: usesNewFormat + ? (meta.deprecated.replacedBy?.map( + replacement => + `${replacement.plugin?.name !== void 0 ? `${getShorthandName(replacement.plugin.name, "eslint-plugin")}/` : ""}${replacement.rule?.name ?? ""}`, + ) ?? []) + : meta.replacedBy || [], + info: usesNewFormat ? meta.deprecated : void 0, + }); + } + } + } + + usedDeprecatedRulesCache.set(config, Object.freeze(retv)); + } + + return config ? usedDeprecatedRulesCache.get(config) : Object.freeze([]); +} + +/** + * Processes the linting results generated by a CLIEngine linting report to + * match the ESLint class's API. + * @param {ESLint} eslint The ESLint instance. + * @param {LintResult[]} results The linting results to process. + * @returns {LintResult[]} The processed linting results. + */ +function processLintReport(eslint, results) { + const descriptor = { + configurable: true, + enumerable: true, + get() { + return getOrFindUsedDeprecatedRules(eslint, this.filePath); + }, + }; + + for (const result of results) { + Object.defineProperty(result, "usedDeprecatedRules", descriptor); + } + + return results; +} + +/** + * An Array.prototype.sort() compatible compare function to order results by their file path. + * @param {LintResult} a The first lint result. + * @param {LintResult} b The second lint result. + * @returns {number} An integer representing the order in which the two results should occur. + */ +function compareResultsByFilePath(a, b) { + if (a.filePath < b.filePath) { + return -1; + } + + if (a.filePath > b.filePath) { + return 1; + } + + return 0; +} + +/** + * Determines which config file to use. This is determined by seeing if an + * override config file was passed, and if so, using it; otherwise, as long + * as override config file is not explicitly set to `false`, it will search + * upwards from the cwd for a file named `eslint.config.js`. + * + * This function is used primarily by the `--inspect-config` option. For now, + * we will maintain the existing behavior, which is to search up from the cwd. + * @param {ESLintOptions} options The ESLint instance options. + * @returns {Promise<{configFilePath:string|undefined;basePath:string}>} Location information for + * the config file. + */ +async function locateConfigFileToUse({ configFile, cwd }) { + const configLoader = new ConfigLoader({ + cwd, + configFile, + }); + + const configFilePath = await configLoader.findConfigFileForPath( + path.join(cwd, "__placeholder__.js"), + ); + + if (!configFilePath) { + throw new Error("No ESLint configuration file was found."); + } + + return { + configFilePath, + basePath: configFile ? cwd : path.dirname(configFilePath), + }; +} + +/** + * Creates an error to be thrown when an array of results passed to `getRulesMetaForResults` was not created by the current engine. + * @param {Error|undefined} cause The original error that led to this symptom error being thrown. Might not always be available. + * @returns {TypeError} An error object. + */ +function createExtraneousResultsError(cause) { + return new TypeError( + "Results object was not created from this ESLint instance.", + { + cause, + }, + ); +} + +/** + * Maximum number of files assumed to be best handled by one worker thread. + * This value is a heuristic estimation that can be adjusted if required. + */ +const AUTO_FILES_PER_WORKER = 50; + +/** + * Calculates the number of worker threads to run for "auto" concurrency depending on the number of + * files that need to be processed. + * + * The number of worker threads is calculated as the number of files that need to be processed + * (`processableFileCount`) divided by the number of files assumed to be best handled by one worker + * thread (`AUTO_FILES_PER_WORKER`), rounded up to the next integer. + * Two adjustments are made to this calculation: first, the number of workers is capped at half the + * number of available CPU cores (`maxWorkers`); second, a value of 1 is converted to 0. + * The following table shows the relationship between the number of files to be processed and the + * number of workers: + * + * Files to be processed | Workers + * -------------------------------------------------------------------|----------------- + * 0 | 0 + * 1, 2, …, AUTO_FILES_PER_WORKER | 0 (there's no 1) + * AUTO_FILES_PER_WORKER + 1, …, AUTO_FILES_PER_WORKER * 2 | 2 + * AUTO_FILES_PER_WORKER * 2 + 1, …, AUTO_FILES_PER_WORKER * 3 | 3 + * ⋯ | ⋯ + * AUTO_FILES_PER_WORKER * (𝑛 - 1) + 1, …, AUTO_FILES_PER_WORKER * 𝑛 | 𝑛 + * ⋯ | ⋯ + * AUTO_FILES_PER_WORKER * (maxWorkers - 1) + 1, … | maxWorkers + * + * The number of files to be processed should be determined by the calling function. + * @param {number} processableFileCount The number of files that need to be processed. + * @param {number} maxWorkers The maximum number of workers to run. + * @returns {number} The number of worker threads to run. + */ +function getWorkerCountFor(processableFileCount, maxWorkers) { + let workerCount = Math.ceil(processableFileCount / AUTO_FILES_PER_WORKER); + if (workerCount > maxWorkers) { + workerCount = maxWorkers; + } + if (workerCount <= 1) { + workerCount = 0; + } + return workerCount; +} + +/** + * Returns true if a file has no valid cached results or if it needs to be reprocessed because there are violations that may need fixing. + * This function will access the filesystem. + * @param {LintResultCache} lintResultCache The lint result cache. + * @param {boolean} fix The fix option. + * @param {string} filePath The file for which to retrieve lint results. + * @param {Config} config The config of the file. + * @returns {boolean} True if the file needs to be reprocessed. + */ +function needsReprocessing(lintResultCache, fix, filePath, config) { + const results = lintResultCache.getValidCachedLintResults(filePath, config); + + // This reflects the reprocessing logic of the `lintFile` helper function. + return !results || (fix && results.messages && results.messages.length > 0); +} + +/** + * Calculates the number of worker threads to run for "auto" concurrency. + * + * The number of worker threads depends on the number files that need to be processed. + * Typically, this includes all non-ignored files. + * In a cached run with "metadata" strategy, files with a valid cached result aren't counted. + * @param {ESLint} eslint ESLint instance. + * @param {string[]} filePaths File paths to lint. + * @param {number} maxWorkers The maximum number of workers to run. + * @returns {number} The number of worker threads to run for "auto" concurrency. + */ +function calculateAutoWorkerCount(eslint, filePaths, maxWorkers) { + const startTime = hrtimeBigint(); + const { + configLoader, + lintResultCache, + options: { cacheStrategy, fix }, + } = privateMembers.get(eslint); + /** True if cache is not used or if strategy is "content". */ + const countAllMatched = !lintResultCache || cacheStrategy === "content"; + + let processableFileCount = 0; + let remainingFiles = filePaths.length; + + /** The number of workers if none of the remaining files were to be counted. */ + let lowWorkerCount = 0; + + /* + * Rather than counting all files to be processed in advance, we stop iterating as soon as we reach + * a point where adding more files doesn't change the number of workers anymore. + */ + for (const filePath of filePaths) { + /** The number of workers if all of the remaining files were to be counted. */ + const highWorkerCount = getWorkerCountFor( + processableFileCount + remainingFiles, + maxWorkers, + ); + if (lowWorkerCount >= highWorkerCount) { + // The highest possible number of workers has been reached, so stop counting. + break; + } + remainingFiles--; + const configs = configLoader.getCachedConfigArrayForFile(filePath); + const config = configs.getConfig(filePath); + if (!config) { + // file is ignored + continue; + } + if ( + countAllMatched || + needsReprocessing(lintResultCache, fix, filePath, config) + ) { + processableFileCount++; + lowWorkerCount = getWorkerCountFor( + processableFileCount, + maxWorkers, + ); + } + } + debug( + "%d file(s) to process counted in %t", + processableFileCount, + hrtimeBigint() - startTime, + ); + return lowWorkerCount; +} + +/** + * Calculates the number of workers to run based on the concurrency setting and the number of files to lint. + * @param {ESLint} eslint The ESLint instance. + * @param {string[]} filePaths File paths to lint. + * @param {{ availableParallelism: () => number }} [os] Node.js `os` module, or a mock for testing. + * @returns {number} The effective number of worker threads to be started. A value of zero disables multithread linting. + */ +function calculateWorkerCount( + eslint, + filePaths, + { availableParallelism } = os, +) { + const { concurrency } = privateMembers.get(eslint).options; + switch (concurrency) { + case "off": + return 0; + case "auto": { + const maxWorkers = availableParallelism() >> 1; + return calculateAutoWorkerCount(eslint, filePaths, maxWorkers); + } + default: { + const workerCount = Math.min(concurrency, filePaths.length); + return workerCount > 1 ? workerCount : 0; + } + } +} + +// Used internally. Do not expose. +const disableCloneabilityCheck = Symbol( + "Do not check for uncloneable options.", +); + +/** + * The smallest net linting ratio that doesn't trigger a poor concurrency warning. + * The net linting ratio is defined as the net linting duration divided by the thread's total runtime, + * where the net linting duration is the total linting time minus the time spent on I/O-intensive operations: + * **Net Linting Ratio** = (**Linting Time** – **I/O Time**) / **Thread Runtime**. + * - **Linting Time**: Total time spent linting files + * - **I/O Time**: Portion of linting time spent loading configs and reading files + * - **Thread Runtime**: End-to-end execution time of the thread + * + * This value is a heuristic estimation that can be adjusted if required. + */ +const LOW_NET_LINTING_RATIO = 0.7; + +/** + * Runs worker threads to lint files. + * @param {string[]} filePaths File paths to lint. + * @param {number} workerCount The number of worker threads to run. + * @param {ESLintOptions | string} eslintOptionsOrURL The unprocessed ESLint options or the URL of the options module. + * @param {() => void} warnOnLowNetLintingRatio A function to call if the net linting ratio is low. + * @returns {Promise} Lint results. + */ +async function runWorkers( + filePaths, + workerCount, + eslintOptionsOrURL, + warnOnLowNetLintingRatio, +) { + const fileCount = filePaths.length; + const results = Array(fileCount); + const workerURL = pathToFileURL(path.join(__dirname, "./worker.js")); + const filePathIndexArray = new Uint32Array( + new SharedArrayBuffer(Uint32Array.BYTES_PER_ELEMENT), + ); + const abortController = new AbortController(); + const abortSignal = abortController.signal; + const workerOptions = { + env: SHARE_ENV, + workerData: { + eslintOptionsOrURL, + filePathIndexArray, + filePaths, + }, + }; + + let worstNetLintingRatio = 1; + + /** + * A promise executor function that starts a worker thread on each invocation. + * @param {() => void} resolve_ Called when the worker thread terminates successfully. + * @param {(error: Error) => void} reject Called when the worker thread terminates with an error. + * @returns {void} + */ + function workerExecutor(resolve_, reject) { + const workerStartTime = hrtimeBigint(); + const worker = new Worker(workerURL, workerOptions); + worker.once( + "message", + (/** @type {WorkerLintResults} */ indexedResults) => { + const workerDuration = hrtimeBigint() - workerStartTime; + + // The net linting ratio provides an approximate measure of worker thread efficiency, defined as the net linting duration divided by the thread's total runtime. + const netLintingRatio = + Number(indexedResults.netLintingDuration) / + Number(workerDuration); + + worstNetLintingRatio = Math.min( + worstNetLintingRatio, + netLintingRatio, + ); + + if (timing.enabled && indexedResults.timings) { + timing.mergeData(indexedResults.timings); + } + + for (const result of indexedResults) { + const { index } = result; + delete result.index; + results[index] = result; + } + resolve_(); + }, + ); + worker.once("error", error => { + abortController.abort(error); + reject(error); + }); + abortSignal.addEventListener("abort", () => worker.terminate()); + } + + const promises = Array(workerCount); + for (let index = 0; index < workerCount; ++index) { + promises[index] = new Promise(workerExecutor); + } + + try { + await Promise.all(promises); + } catch (error) { + /* + * If any worker fails, suppress timing display in the main thread + * to avoid printing partial or misleading timing output. + */ + timing.disableDisplay(); + throw error; + } + + if (worstNetLintingRatio < LOW_NET_LINTING_RATIO) { + warnOnLowNetLintingRatio(); + } + + return results; +} + +/** + * Lint files in multithread mode. + * @param {ESLint} eslint ESLint instance. + * @param {string[]} filePaths File paths to lint. + * @param {number} workerCount The number of worker threads to run. + * @param {ESLintOptions | string} eslintOptionsOrURL The unprocessed ESLint options or the URL of the options module. + * @param {() => void} warnOnLowNetLintingRatio A function to call if the net linting ratio is low. + * @returns {Promise} Lint results. + */ +async function lintFilesWithMultithreading( + eslint, + filePaths, + workerCount, + eslintOptionsOrURL, + warnOnLowNetLintingRatio, +) { + const { configLoader, lintResultCache } = privateMembers.get(eslint); + + const results = await runWorkers( + filePaths, + workerCount, + eslintOptionsOrURL, + warnOnLowNetLintingRatio, + ); + // Persist the cache to disk. + if (lintResultCache) { + results.forEach((result, index) => { + if (result) { + const filePath = filePaths[index]; + const configs = + configLoader.getCachedConfigArrayForFile(filePath); + const config = configs.getConfig(filePath); + + if (config) { + /* + * Store the lint result in the LintResultCache. + * NOTE: The LintResultCache will remove the file source and any + * other properties that are difficult to serialize, and will + * hydrate those properties back in on future lint runs. + */ + lintResultCache.setCachedLintResults( + filePath, + config, + result, + ); + } + } + }); + } + return results; +} + +/** + * Lint files in single-thread mode. + * @param {ESLint} eslint ESLint instance. + * @param {string[]} filePaths File paths to lint. + * @returns {Promise} Lint results. + */ +async function lintFilesWithoutMultithreading(eslint, filePaths) { + const { + configLoader, + linter, + lintResultCache, + options: eslintOptions, + } = privateMembers.get(eslint); + + const controller = new AbortController(); + const retrier = new Retrier(error => fileRetryCodes.has(error.code), { + concurrency: 100, + }); + + /* + * Because we need to process multiple files, including reading from disk, + * it is most efficient to start by reading each file via promises so that + * they can be done in parallel. Then, we can lint the returned text. This + * ensures we are waiting the minimum amount of time in between lints. + */ + const results = await Promise.all( + filePaths.map(async filePath => { + const configs = configLoader.getCachedConfigArrayForFile(filePath); + const config = configs.getConfig(filePath); + + const result = await lintFile( + filePath, + configs, + eslintOptions, + linter, + lintResultCache, + null, + retrier, + controller, + ); + + if (config) { + /* + * Store the lint result in the LintResultCache. + * NOTE: The LintResultCache will remove the file source and any + * other properties that are difficult to serialize, and will + * hydrate those properties back in on future lint runs. + */ + lintResultCache?.setCachedLintResults(filePath, config, result); + } + + return result; + }), + ); + return results; +} + +/** + * Throws an error if the given options are not cloneable. + * @param {ESLintOptions} options The options to check. + * @returns {void} + * @throws {TypeError} If the options are not cloneable. + */ +function validateOptionCloneability(options) { + try { + structuredClone(options); + return; + } catch { + // continue + } + const uncloneableOptionKeys = Object.keys(options) + .filter(key => { + try { + structuredClone(options[key]); + } catch { + return true; + } + return false; + }) + .sort(); + const error = new TypeError( + `The ${uncloneableOptionKeys.length === 1 ? "option" : "options"} ${new Intl.ListFormat("en-US").format(uncloneableOptionKeys.map(key => `"${key}"`))} cannot be cloned. When concurrency is enabled, all options must be cloneable values (JSON values). Remove uncloneable options or use an options module.`, + ); + error.code = "ESLINT_UNCLONEABLE_OPTIONS"; + throw error; +} + +//----------------------------------------------------------------------------- +// Main API +//----------------------------------------------------------------------------- + +/** + * Primary Node.js API for ESLint. + */ +class ESLint { + /** + * The type of configuration used by this class. + * @type {string} + */ + static configType = "flat"; + + /** + * The loader to use for finding config files. + * @type {ConfigLoader} + */ + #configLoader; + + /** + * The unprocessed options or the URL of the options module. Only set when concurrency is enabled. + * @type {ESLintOptions | string | undefined} + */ + #optionsOrURL; + + /** + * Creates a new instance of the main ESLint API. + * @param {ESLintOptions} options The options for this instance. + */ + constructor(options = {}) { + const processedOptions = processOptions(options); + if ( + !options[disableCloneabilityCheck] && + processedOptions.concurrency !== "off" + ) { + validateOptionCloneability(options); + + // Save the unprocessed options in an instance field to pass to worker threads in `lintFiles()`. + this.#optionsOrURL = options; + } + const warningService = new WarningService(); + const linter = createLinter(processedOptions, warningService); + + const cacheFilePath = getCacheFile( + processedOptions.cacheLocation, + processedOptions.cwd, + ); + + const lintResultCache = createLintResultCache( + processedOptions, + cacheFilePath, + ); + const defaultConfigs = createDefaultConfigs(options.plugins); + + this.#configLoader = createConfigLoader( + processedOptions, + defaultConfigs, + linter, + warningService, + ); + + debug(`Using config loader ${this.#configLoader.constructor.name}`); + + privateMembers.set(this, { + options: processedOptions, + linter, + cacheFilePath, + lintResultCache, + defaultConfigs, + configs: null, + configLoader: this.#configLoader, + warningService, + }); + + // Check for the .eslintignore file, and warn if it's present. + if (existsSync(path.resolve(processedOptions.cwd, ".eslintignore"))) { + warningService.emitESLintIgnoreWarning(); + } + } + + /** + * The version text. + * @type {string} + */ + static get version() { + return version; + } + + /** + * The default configuration that ESLint uses internally. This is provided for tooling that wants to calculate configurations using the same defaults as ESLint. + * Keep in mind that the default configuration may change from version to version, so you shouldn't rely on any particular keys or values to be present. + * @type {FlatConfigArray} + */ + static get defaultConfig() { + return defaultConfig; + } + + /** + * Outputs fixes from the given results to files. + * @param {LintResult[]} results The lint results. + * @returns {Promise} Returns a promise that is used to track side effects. + */ + static async outputFixes(results) { + if (!Array.isArray(results)) { + throw new Error("'results' must be an array"); + } + + const retrier = new Retrier(error => fileRetryCodes.has(error.code), { + concurrency: 100, + }); + + await Promise.all( + results + .filter(result => { + if (typeof result !== "object" || result === null) { + throw new Error("'results' must include only objects"); + } + return ( + typeof result.output === "string" && + path.isAbsolute(result.filePath) + ); + }) + .map(r => + retrier.retry(() => fs.writeFile(r.filePath, r.output)), + ), + ); + } + + /** + * Returns results that only contains errors. + * @param {LintResult[]} results The results to filter. + * @returns {LintResult[]} The filtered results. + */ + static getErrorResults(results) { + const filtered = []; + + results.forEach(result => { + const filteredMessages = result.messages.filter(isErrorMessage); + const filteredSuppressedMessages = + result.suppressedMessages.filter(isErrorMessage); + + if (filteredMessages.length > 0) { + filtered.push({ + ...result, + messages: filteredMessages, + suppressedMessages: filteredSuppressedMessages, + errorCount: filteredMessages.length, + warningCount: 0, + fixableErrorCount: result.fixableErrorCount, + fixableWarningCount: 0, + }); + } + }); + + return filtered; + } + + /** + * Creates a new ESLint instance using options loaded from a module. + * @param {URL} optionsURL The URL of the options module. + * @returns {ESLint} The new ESLint instance. + */ + static async fromOptionsModule(optionsURL) { + if (!(optionsURL instanceof URL)) { + throw new TypeError("Argument must be a URL object"); + } + const optionsURLString = optionsURL.href; + const loadedOptions = await loadOptionsFromModule(optionsURLString); + const options = { ...loadedOptions, [disableCloneabilityCheck]: true }; + const eslint = new ESLint(options); + + if (options.concurrency !== "off") { + // Save the options module URL in an instance field to pass to worker threads in `lintFiles()`. + eslint.#optionsOrURL = optionsURLString; + } + return eslint; + } + + /** + * Returns meta objects for each rule represented in the lint results. + * @param {LintResult[]} results The results to fetch rules meta for. + * @returns {Record} A mapping of ruleIds to rule meta objects. + * @throws {TypeError} When the results object wasn't created from this ESLint instance. + * @throws {TypeError} When a plugin or rule is missing. + */ + getRulesMetaForResults(results) { + // short-circuit simple case + if (results.length === 0) { + return {}; + } + + const resultRules = new Map(); + const { + configLoader, + options: { cwd }, + } = privateMembers.get(this); + + for (const result of results) { + /* + * Normalize filename for . + */ + const filePath = + result.filePath === "" + ? getPlaceholderPath(cwd) + : result.filePath; + const allMessages = result.messages.concat( + result.suppressedMessages, + ); + + for (const { ruleId } of allMessages) { + if (!ruleId) { + continue; + } + + /* + * All of the plugin and rule information is contained within the + * calculated config for the given file. + */ + let configs; + + try { + configs = + configLoader.getCachedConfigArrayForFile(filePath); + } catch (err) { + throw createExtraneousResultsError(err); + } + + const config = configs.getConfig(filePath); + + if (!config) { + throw createExtraneousResultsError(); + } + const rule = config.getRuleDefinition(ruleId); + + // ignore unknown rules + if (rule) { + resultRules.set(ruleId, rule); + } + } + } + + return createRulesMeta(resultRules); + } + + /** + * Indicates if the given feature flag is enabled for this instance. + * @param {string} flag The feature flag to check. + * @returns {boolean} `true` if the feature flag is enabled, `false` if not. + */ + hasFlag(flag) { + // note: Linter does validation of the flags + return privateMembers.get(this).linter.hasFlag(flag); + } + + /** + * Executes the current configuration on an array of file and directory names. + * @param {string|string[]} patterns An array of file and directory names. + * @returns {Promise} The results of linting the file patterns given. + */ + async lintFiles(patterns) { + let normalizedPatterns = patterns; + const { + cacheFilePath, + lintResultCache, + options: eslintOptions, + warningService, + } = privateMembers.get(this); + + /* + * Special cases: + * 1. `patterns` is an empty string + * 2. `patterns` is an empty array + * + * In both cases, we use the cwd as the directory to lint. + */ + if ( + patterns === "" || + (Array.isArray(patterns) && patterns.length === 0) + ) { + /* + * Special case: If `passOnNoPatterns` is true, then we just exit + * without doing any work. + */ + if (eslintOptions.passOnNoPatterns) { + return []; + } + + normalizedPatterns = ["."]; + } else { + if ( + !isNonEmptyString(patterns) && + !isArrayOfNonEmptyString(patterns) + ) { + throw new Error( + "'patterns' must be a non-empty string or an array of non-empty strings", + ); + } + + if (typeof patterns === "string") { + normalizedPatterns = [patterns]; + } + } + + debug(`Using file patterns: ${normalizedPatterns}`); + + const { concurrency, cwd, globInputPaths, errorOnUnmatchedPattern } = + eslintOptions; + + // Delete cache file; should this be done here? + if (!lintResultCache && cacheFilePath) { + debug(`Deleting cache file at ${cacheFilePath}`); + + try { + if (existsSync(cacheFilePath)) { + await fs.unlink(cacheFilePath); + } + } catch (error) { + if (existsSync(cacheFilePath)) { + throw error; + } + } + } + + const startTime = hrtimeBigint(); + const filePaths = await findFiles({ + patterns: normalizedPatterns, + cwd, + globInputPaths, + configLoader: this.#configLoader, + errorOnUnmatchedPattern, + }); + debug( + "%d file(s) found in %t", + filePaths.length, + hrtimeBigint() - startTime, + ); + + /** @type {LintResult[]} */ + let results; + + // The value of `module.exports.calculateWorkerCount` can be overridden in tests. + const workerCount = module.exports.calculateWorkerCount( + this, + filePaths, + ); + if (workerCount) { + debug(`Linting using ${workerCount} worker thread(s).`); + let poorConcurrencyNotice; + if (workerCount <= 2) { + poorConcurrencyNotice = "disable concurrency"; + } else { + if (concurrency === "auto") { + poorConcurrencyNotice = + "disable concurrency or use a numeric concurrency setting"; + } else { + poorConcurrencyNotice = "reduce or disable concurrency"; + } + } + results = await lintFilesWithMultithreading( + this, + filePaths, + workerCount, + this.#optionsOrURL, + () => + warningService.emitPoorConcurrencyWarning( + poorConcurrencyNotice, + ), + ); + } else { + debug(`Linting in single-thread mode.`); + results = await lintFilesWithoutMultithreading(this, filePaths); + } + + // Persist the cache to disk. + if (lintResultCache) { + lintResultCache.reconcile(); + } + + const finalResults = results.filter(result => !!result); + + return processLintReport(this, finalResults); + } + + /** + * Executes the current configuration on text. + * @param {string} code A string of JavaScript code to lint. + * @param {Object} [options] The options. + * @param {string} [options.filePath] The path to the file of the source code. + * @param {boolean} [options.warnIgnored] When set to true, warn if given filePath is an ignored path. + * @returns {Promise} The results of linting the string of code given. + */ + async lintText(code, options = {}) { + // Parameter validation + + if (typeof code !== "string") { + throw new Error("'code' must be a string"); + } + + if (typeof options !== "object") { + throw new Error("'options' must be an object, null, or undefined"); + } + + // Options validation + + const { filePath, warnIgnored, ...unknownOptions } = options || {}; + + const unknownOptionKeys = Object.keys(unknownOptions); + + if (unknownOptionKeys.length > 0) { + throw new Error( + `'options' must not include the unknown option(s): ${unknownOptionKeys.join(", ")}`, + ); + } + + if (filePath !== void 0 && !isNonEmptyString(filePath)) { + throw new Error( + "'options.filePath' must be a non-empty string or undefined", + ); + } + + if ( + typeof warnIgnored !== "boolean" && + typeof warnIgnored !== "undefined" + ) { + throw new Error( + "'options.warnIgnored' must be a boolean or undefined", + ); + } + + // Now we can get down to linting + + const { linter, options: eslintOptions } = privateMembers.get(this); + const { + allowInlineConfig, + cwd, + fix, + fixTypes, + warnIgnored: constructorWarnIgnored, + ruleFilter, + stats, + } = eslintOptions; + const results = []; + const startTime = hrtimeBigint(); + const fixTypesSet = fixTypes ? new Set(fixTypes) : null; + const resolvedFilename = path.resolve( + cwd, + filePath || "__placeholder__.js", + ); + const configs = + await this.#configLoader.loadConfigArrayForFile(resolvedFilename); + const configStatus = + configs?.getConfigStatus(resolvedFilename) ?? "unconfigured"; + + // Clear the last used config arrays. + if (resolvedFilename && configStatus !== "matched") { + const shouldWarnIgnored = + typeof warnIgnored === "boolean" + ? warnIgnored + : constructorWarnIgnored; + + if (shouldWarnIgnored) { + results.push( + createIgnoreResult(resolvedFilename, cwd, configStatus), + ); + } + } else { + const config = configs.getConfig(resolvedFilename); + const fixer = getFixerForFixTypes(fix, fixTypesSet, config); + + // Do lint. + results.push( + verifyText({ + text: code, + filePath: resolvedFilename.endsWith("__placeholder__.js") + ? "" + : resolvedFilename, + configs, + cwd, + fix: fixer, + allowInlineConfig, + ruleFilter, + stats, + linter, + }), + ); + } + + debug("Linting complete in %t", hrtimeBigint() - startTime); + + return processLintReport(this, results); + } + + /** + * Returns the formatter representing the given formatter name. + * @param {string} [name] The name of the formatter to load. + * The following values are allowed: + * - `undefined` ... Load `stylish` builtin formatter. + * - A builtin formatter name ... Load the builtin formatter. + * - A third-party formatter name: + * - `foo` → `eslint-formatter-foo` + * - `@foo` → `@foo/eslint-formatter` + * - `@foo/bar` → `@foo/eslint-formatter-bar` + * - A file path ... Load the file. + * @returns {Promise} A promise resolving to the formatter object. + * This promise will be rejected if the given formatter was not found or not + * a function. + */ + async loadFormatter(name = "stylish") { + if (typeof name !== "string") { + throw new Error("'name' must be a string"); + } + + // replace \ with / for Windows compatibility + const normalizedFormatName = name.replace(/\\/gu, "/"); + const namespace = getNamespaceFromTerm(normalizedFormatName); + + // grab our options + const { cwd } = privateMembers.get(this).options; + + let formatterPath; + + // if there's a slash, then it's a file (TODO: this check seems dubious for scoped npm packages) + if (!namespace && normalizedFormatName.includes("/")) { + formatterPath = path.resolve(cwd, normalizedFormatName); + } else { + try { + const npmFormat = normalizePackageName( + normalizedFormatName, + "eslint-formatter", + ); + + // TODO: This is pretty dirty...would be nice to clean up at some point. + formatterPath = resolve(npmFormat, getPlaceholderPath(cwd)); + } catch { + formatterPath = path.resolve( + __dirname, + "../", + "cli-engine", + "formatters", + `${normalizedFormatName}.js`, + ); + } + } + + let formatter; + + try { + formatter = (await import(pathToFileURL(formatterPath))).default; + } catch (ex) { + // check for formatters that have been removed + if (removedFormatters.has(name)) { + ex.message = `The ${name} formatter is no longer part of core ESLint. Install it manually with \`npm install -D eslint-formatter-${name}\``; + } else { + ex.message = `There was a problem loading formatter: ${formatterPath}\nError: ${ex.message}`; + } + + throw ex; + } + + if (typeof formatter !== "function") { + throw new TypeError( + `Formatter must be a function, but got a ${typeof formatter}.`, + ); + } + + const eslint = this; + + return { + /** + * The main formatter method. + * @param {LintResult[]} results The lint results to format. + * @param {ResultsMeta} resultsMeta Warning count and max threshold. + * @returns {string} The formatted lint results. + */ + format(results, resultsMeta) { + let rulesMeta = null; + + results.sort(compareResultsByFilePath); + + return formatter(results, { + ...resultsMeta, + cwd, + get rulesMeta() { + if (!rulesMeta) { + rulesMeta = eslint.getRulesMetaForResults(results); + } + + return rulesMeta; + }, + }); + }, + }; + } + + /** + * Returns a configuration object for the given file based on the CLI options. + * This is the same logic used by the ESLint CLI executable to determine + * configuration for each file it processes. + * @param {string} filePath The path of the file to retrieve a config object for. + * @returns {Promise} A configuration object for the file + * or `undefined` if there is no configuration data for the object. + */ + async calculateConfigForFile(filePath) { + if (!isNonEmptyString(filePath)) { + throw new Error("'filePath' must be a non-empty string"); + } + const options = privateMembers.get(this).options; + const absolutePath = path.resolve(options.cwd, filePath); + const configs = + await this.#configLoader.loadConfigArrayForFile(absolutePath); + + if (!configs) { + const error = new Error("Could not find config file."); + + error.messageTemplate = "config-file-missing"; + throw error; + } + + return configs.getConfig(absolutePath); + } + + /** + * Finds the config file being used by this instance based on the options + * passed to the constructor. + * @param {string} [filePath] The path of the file to find the config file for. + * @returns {Promise} The path to the config file being used or + * `undefined` if no config file is being used. + */ + async findConfigFile(filePath) { + const options = privateMembers.get(this).options; + + /* + * Because the new config lookup scheme skips the current directory + * and looks into the parent directories, we need to use a placeholder + * directory to ensure the file in cwd is checked. + */ + const fakeCwd = path.join(options.cwd, "__placeholder__"); + + return this.#configLoader + .findConfigFileForPath(filePath ?? fakeCwd) + .catch(() => void 0); + } + + /** + * Checks if a given path is ignored by ESLint. + * @param {string} filePath The path of the file to check. + * @returns {Promise} Whether or not the given path is ignored. + */ + async isPathIgnored(filePath) { + const config = await this.calculateConfigForFile(filePath); + + return config === void 0; + } +} + +/** + * Returns whether flat config should be used. + * @returns {Promise} Whether flat config should be used. + */ +async function shouldUseFlatConfig() { + return process.env.ESLINT_USE_FLAT_CONFIG !== "false"; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = { + ESLint, + shouldUseFlatConfig, + locateConfigFileToUse, + calculateWorkerCount, +}; diff --git a/tools/ui/node_modules/eslint/lib/eslint/index.js b/tools/ui/node_modules/eslint/lib/eslint/index.js new file mode 100644 index 0000000000000000000000000000000000000000..40588d5d4d8edfbc2616f677b5cfa1eb966ca727 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/eslint/index.js @@ -0,0 +1,9 @@ +"use strict"; + +const { ESLint } = require("./eslint"); +const { LegacyESLint } = require("./legacy-eslint"); + +module.exports = { + ESLint, + LegacyESLint, +}; diff --git a/tools/ui/node_modules/eslint/lib/eslint/legacy-eslint.js b/tools/ui/node_modules/eslint/lib/eslint/legacy-eslint.js new file mode 100644 index 0000000000000000000000000000000000000000..36d30e5a340e9c77cea0b0d399d2ad85decb9114 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/eslint/legacy-eslint.js @@ -0,0 +1,786 @@ +/** + * @fileoverview Main API Class + * @author Kai Cataldo + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const path = require("node:path"); +const fs = require("node:fs"); +const { promisify } = require("node:util"); +const { + CLIEngine, + getCLIEngineInternalSlots, +} = require("../cli-engine/cli-engine"); +const BuiltinRules = require("../rules"); +const { + Legacy: { + ConfigOps: { getRuleSeverity }, + }, +} = require("@eslint/eslintrc"); +const { version } = require("../../package.json"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** @typedef {import("../cli-engine/cli-engine").LintReport} CLIEngineLintReport */ +/** @typedef {import("../types").ESLint.ConfigData} ConfigData */ +/** @typedef {import("../types").ESLint.DeprecatedRuleUse} DeprecatedRuleInfo */ +/** @typedef {import("../types").Linter.LintMessage} LintMessage */ +/** @typedef {import("../types").ESLint.LintResult} LintResult */ +/** @typedef {import("../types").ESLint.Plugin} Plugin */ +/** @typedef {import("../types").ESLint.ResultsMeta} ResultsMeta */ +/** @typedef {import("../types").Rule.RuleModule} Rule */ +/** @typedef {import("../types").Linter.SuppressedLintMessage} SuppressedLintMessage */ + +/** + * The main formatter object. + * @typedef LoadedFormatter + * @property {(results: LintResult[], resultsMeta: ResultsMeta) => string | Promise} format format function. + */ + +/** + * The options with which to configure the LegacyESLint instance. + * @typedef {Object} LegacyESLintOptions + * @property {boolean} [allowInlineConfig] Enable or disable inline configuration comments. + * @property {ConfigData} [baseConfig] Base config object, extended by all configs used with this instance + * @property {boolean} [cache] Enable result caching. + * @property {string} [cacheLocation] The cache file to use instead of .eslintcache. + * @property {"metadata" | "content"} [cacheStrategy] The strategy used to detect changed files. + * @property {string} [cwd] The value to use for the current working directory. + * @property {boolean} [errorOnUnmatchedPattern] If `false` then `ESLint#lintFiles()` doesn't throw even if no target files found. Defaults to `true`. + * @property {string[]} [extensions] An array of file extensions to check. + * @property {boolean|Function} [fix] Execute in autofix mode. If a function, should return a boolean. + * @property {string[]} [fixTypes] Array of rule types to apply fixes for. + * @property {boolean} [globInputPaths] Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file. + * @property {boolean} [ignore] False disables use of .eslintignore. + * @property {string} [ignorePath] The ignore file to use instead of .eslintignore. + * @property {ConfigData} [overrideConfig] Override config object, overrides all configs used with this instance + * @property {string} [overrideConfigFile] The configuration file to use. + * @property {Record|null} [plugins] Preloaded plugins. This is a map-like object, keys are plugin IDs and each value is implementation. + * @property {"error" | "warn" | "off"} [reportUnusedDisableDirectives] the severity to report unused eslint-disable directives. + * @property {string} [resolvePluginsRelativeTo] The folder where plugins should be resolved from, defaulting to the CWD. + * @property {string[]} [rulePaths] An array of directories to load custom rules from. + * @property {boolean} [useEslintrc] False disables looking for .eslintrc.* files. + * @property {boolean} [passOnNoPatterns=false] When set to true, missing patterns cause + * the linting operation to short circuit and not report any failures. + */ + +/** + * A rules metadata object. + * @typedef {Object} RulesMeta + * @property {string} id The plugin ID. + * @property {Object} definition The plugin definition. + */ + +/** + * Private members for the `ESLint` instance. + * @typedef {Object} ESLintPrivateMembers + * @property {CLIEngine} cliEngine The wrapped CLIEngine instance. + * @property {LegacyESLintOptions} options The options used to instantiate the ESLint instance. + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const writeFile = promisify(fs.writeFile); + +/** + * The map with which to store private class members. + * @type {WeakMap} + */ +const privateMembersMap = new WeakMap(); + +/** + * Check if a given value is a non-empty string or not. + * @param {any} value The value to check. + * @returns {boolean} `true` if `value` is a non-empty string. + */ +function isNonEmptyString(value) { + return typeof value === "string" && value.trim() !== ""; +} + +/** + * Check if a given value is an array of non-empty strings or not. + * @param {any} value The value to check. + * @returns {boolean} `true` if `value` is an array of non-empty strings. + */ +function isArrayOfNonEmptyString(value) { + return ( + Array.isArray(value) && value.length && value.every(isNonEmptyString) + ); +} + +/** + * Check if a given value is an empty array or an array of non-empty strings. + * @param {any} value The value to check. + * @returns {boolean} `true` if `value` is an empty array or an array of non-empty + * strings. + */ +function isEmptyArrayOrArrayOfNonEmptyString(value) { + return Array.isArray(value) && value.every(isNonEmptyString); +} + +/** + * Check if a given value is a valid fix type or not. + * @param {any} value The value to check. + * @returns {boolean} `true` if `value` is valid fix type. + */ +function isFixType(value) { + return ( + value === "directive" || + value === "problem" || + value === "suggestion" || + value === "layout" + ); +} + +/** + * Check if a given value is an array of fix types or not. + * @param {any} value The value to check. + * @returns {boolean} `true` if `value` is an array of fix types. + */ +function isFixTypeArray(value) { + return Array.isArray(value) && value.every(isFixType); +} + +/** + * The error for invalid options. + */ +class ESLintInvalidOptionsError extends Error { + constructor(messages) { + super(`Invalid Options:\n- ${messages.join("\n- ")}`); + this.code = "ESLINT_INVALID_OPTIONS"; + Error.captureStackTrace(this, ESLintInvalidOptionsError); + } +} + +/** + * Validates and normalizes options for the wrapped CLIEngine instance. + * @param {LegacyESLintOptions} options The options to process. + * @throws {ESLintInvalidOptionsError} If of any of a variety of type errors. + * @returns {LegacyESLintOptions} The normalized options. + */ +function processOptions({ + allowInlineConfig = true, // ← we cannot use `overrideConfig.noInlineConfig` instead because `allowInlineConfig` has side-effect that suppress warnings that show inline configs are ignored. + baseConfig = null, + cache = false, + cacheLocation = ".eslintcache", + cacheStrategy = "metadata", + cwd = process.cwd(), + errorOnUnmatchedPattern = true, + extensions = null, // ← should be null by default because if it's an array then it suppresses RFC20 feature. + fix = false, + fixTypes = null, // ← should be null by default because if it's an array then it suppresses rules that don't have the `meta.type` property. + flags /* eslint-disable-line no-unused-vars -- leaving for compatibility with ESLint#hasFlag */, + globInputPaths = true, + ignore = true, + ignorePath = null, // ← should be null by default because if it's a string then it may throw ENOENT. + overrideConfig = null, + overrideConfigFile = null, + plugins = {}, + reportUnusedDisableDirectives = null, // ← should be null by default because if it's a string then it overrides the 'reportUnusedDisableDirectives' setting in config files. And we cannot use `overrideConfig.reportUnusedDisableDirectives` instead because we cannot configure the `error` severity with that. + resolvePluginsRelativeTo = null, // ← should be null by default because if it's a string then it suppresses RFC47 feature. + rulePaths = [], + useEslintrc = true, + passOnNoPatterns = false, + ...unknownOptions +}) { + const errors = []; + const unknownOptionKeys = Object.keys(unknownOptions); + + if (unknownOptionKeys.length >= 1) { + errors.push(`Unknown options: ${unknownOptionKeys.join(", ")}`); + if (unknownOptionKeys.includes("cacheFile")) { + errors.push( + "'cacheFile' has been removed. Please use the 'cacheLocation' option instead.", + ); + } + if (unknownOptionKeys.includes("configFile")) { + errors.push( + "'configFile' has been removed. Please use the 'overrideConfigFile' option instead.", + ); + } + if (unknownOptionKeys.includes("envs")) { + errors.push( + "'envs' has been removed. Please use the 'overrideConfig.env' option instead.", + ); + } + if (unknownOptionKeys.includes("globals")) { + errors.push( + "'globals' has been removed. Please use the 'overrideConfig.globals' option instead.", + ); + } + if (unknownOptionKeys.includes("ignorePattern")) { + errors.push( + "'ignorePattern' has been removed. Please use the 'overrideConfig.ignorePatterns' option instead.", + ); + } + if (unknownOptionKeys.includes("parser")) { + errors.push( + "'parser' has been removed. Please use the 'overrideConfig.parser' option instead.", + ); + } + if (unknownOptionKeys.includes("parserOptions")) { + errors.push( + "'parserOptions' has been removed. Please use the 'overrideConfig.parserOptions' option instead.", + ); + } + if (unknownOptionKeys.includes("rules")) { + errors.push( + "'rules' has been removed. Please use the 'overrideConfig.rules' option instead.", + ); + } + } + if (typeof allowInlineConfig !== "boolean") { + errors.push("'allowInlineConfig' must be a boolean."); + } + if (typeof baseConfig !== "object") { + errors.push("'baseConfig' must be an object or null."); + } + if (typeof cache !== "boolean") { + errors.push("'cache' must be a boolean."); + } + if (!isNonEmptyString(cacheLocation)) { + errors.push("'cacheLocation' must be a non-empty string."); + } + if (cacheStrategy !== "metadata" && cacheStrategy !== "content") { + errors.push('\'cacheStrategy\' must be any of "metadata", "content".'); + } + if (!isNonEmptyString(cwd) || !path.isAbsolute(cwd)) { + errors.push("'cwd' must be an absolute path."); + } + if (typeof errorOnUnmatchedPattern !== "boolean") { + errors.push("'errorOnUnmatchedPattern' must be a boolean."); + } + if ( + !isEmptyArrayOrArrayOfNonEmptyString(extensions) && + extensions !== null + ) { + errors.push( + "'extensions' must be an array of non-empty strings or null.", + ); + } + if (typeof fix !== "boolean" && typeof fix !== "function") { + errors.push("'fix' must be a boolean or a function."); + } + if (fixTypes !== null && !isFixTypeArray(fixTypes)) { + errors.push( + '\'fixTypes\' must be an array of any of "directive", "problem", "suggestion", and "layout".', + ); + } + if (typeof globInputPaths !== "boolean") { + errors.push("'globInputPaths' must be a boolean."); + } + if (typeof ignore !== "boolean") { + errors.push("'ignore' must be a boolean."); + } + if (!isNonEmptyString(ignorePath) && ignorePath !== null) { + errors.push("'ignorePath' must be a non-empty string or null."); + } + if (typeof overrideConfig !== "object") { + errors.push("'overrideConfig' must be an object or null."); + } + if (!isNonEmptyString(overrideConfigFile) && overrideConfigFile !== null) { + errors.push("'overrideConfigFile' must be a non-empty string or null."); + } + if (typeof plugins !== "object") { + errors.push("'plugins' must be an object or null."); + } else if (plugins !== null && Object.keys(plugins).includes("")) { + errors.push("'plugins' must not include an empty string."); + } + if (Array.isArray(plugins)) { + errors.push( + "'plugins' doesn't add plugins to configuration to load. Please use the 'overrideConfig.plugins' option instead.", + ); + } + if ( + reportUnusedDisableDirectives !== "error" && + reportUnusedDisableDirectives !== "warn" && + reportUnusedDisableDirectives !== "off" && + reportUnusedDisableDirectives !== null + ) { + errors.push( + '\'reportUnusedDisableDirectives\' must be any of "error", "warn", "off", and null.', + ); + } + if ( + !isNonEmptyString(resolvePluginsRelativeTo) && + resolvePluginsRelativeTo !== null + ) { + errors.push( + "'resolvePluginsRelativeTo' must be a non-empty string or null.", + ); + } + if (!isEmptyArrayOrArrayOfNonEmptyString(rulePaths)) { + errors.push("'rulePaths' must be an array of non-empty strings."); + } + if (typeof useEslintrc !== "boolean") { + errors.push("'useEslintrc' must be a boolean."); + } + if (typeof passOnNoPatterns !== "boolean") { + errors.push("'passOnNoPatterns' must be a boolean."); + } + + if (errors.length > 0) { + throw new ESLintInvalidOptionsError(errors); + } + + return { + allowInlineConfig, + baseConfig, + cache, + cacheLocation, + cacheStrategy, + configFile: overrideConfigFile, + cwd: path.normalize(cwd), + errorOnUnmatchedPattern, + extensions, + fix, + fixTypes, + flags: [], // LegacyESLint does not support flags, so just ignore them. + globInputPaths, + ignore, + ignorePath, + reportUnusedDisableDirectives, + resolvePluginsRelativeTo, + rulePaths, + useEslintrc, + passOnNoPatterns, + }; +} + +/** + * Check if a value has one or more properties and that value is not undefined. + * @param {any} obj The value to check. + * @returns {boolean} `true` if `obj` has one or more properties that value is not undefined. + */ +function hasDefinedProperty(obj) { + if (typeof obj === "object" && obj !== null) { + for (const key in obj) { + if (typeof obj[key] !== "undefined") { + return true; + } + } + } + return false; +} + +/** + * Create rulesMeta object. + * @param {Map} rules a map of rules from which to generate the object. + * @returns {Object} metadata for all enabled rules. + */ +function createRulesMeta(rules) { + return Array.from(rules).reduce((retVal, [id, rule]) => { + retVal[id] = rule.meta; + return retVal; + }, {}); +} + +/** @type {WeakMap} */ +const usedDeprecatedRulesCache = new WeakMap(); + +/** + * Create used deprecated rule list. + * @param {CLIEngine} cliEngine The CLIEngine instance. + * @param {string} maybeFilePath The absolute path to a lint target file or `""`. + * @returns {DeprecatedRuleInfo[]} The used deprecated rule list. + */ +function getOrFindUsedDeprecatedRules(cliEngine, maybeFilePath) { + const { + configArrayFactory, + options: { cwd }, + } = getCLIEngineInternalSlots(cliEngine); + const filePath = path.isAbsolute(maybeFilePath) + ? maybeFilePath + : path.join(cwd, "__placeholder__.js"); + const configArray = configArrayFactory.getConfigArrayForFile(filePath); + const config = configArray.extractConfig(filePath); + + // Most files use the same config, so cache it. + if (!usedDeprecatedRulesCache.has(config)) { + const pluginRules = configArray.pluginRules; + const retv = []; + + for (const [ruleId, ruleConf] of Object.entries(config.rules)) { + if (getRuleSeverity(ruleConf) === 0) { + continue; + } + const rule = pluginRules.get(ruleId) || BuiltinRules.get(ruleId); + const meta = rule && rule.meta; + + if (meta && meta.deprecated) { + retv.push({ ruleId, replacedBy: meta.replacedBy || [] }); + } + } + + usedDeprecatedRulesCache.set(config, Object.freeze(retv)); + } + + return usedDeprecatedRulesCache.get(config); +} + +/** + * Processes the linting results generated by a CLIEngine linting report to + * match the ESLint class's API. + * @param {CLIEngine} cliEngine The CLIEngine instance. + * @param {CLIEngineLintReport} report The CLIEngine linting report to process. + * @returns {LintResult[]} The processed linting results. + */ +function processCLIEngineLintReport(cliEngine, { results }) { + const descriptor = { + configurable: true, + enumerable: true, + get() { + return getOrFindUsedDeprecatedRules(cliEngine, this.filePath); + }, + }; + + for (const result of results) { + Object.defineProperty(result, "usedDeprecatedRules", descriptor); + } + + return results; +} + +/** + * An Array.prototype.sort() compatible compare function to order results by their file path. + * @param {LintResult} a The first lint result. + * @param {LintResult} b The second lint result. + * @returns {number} An integer representing the order in which the two results should occur. + */ +function compareResultsByFilePath(a, b) { + if (a.filePath < b.filePath) { + return -1; + } + + if (a.filePath > b.filePath) { + return 1; + } + + return 0; +} + +/** + * Main API. + */ +class LegacyESLint { + /** + * The type of configuration used by this class. + * @type {string} + */ + static configType = "eslintrc"; + + /** + * Creates a new instance of the main ESLint API. + * @param {LegacyESLintOptions} options The options for this instance. + */ + constructor(options = {}) { + const processedOptions = processOptions(options); + const cliEngine = new CLIEngine(processedOptions, { + preloadedPlugins: options.plugins, + }); + const { configArrayFactory, lastConfigArrays } = + getCLIEngineInternalSlots(cliEngine); + let updated = false; + + /* + * Address `overrideConfig` to set override config. + * Operate the `configArrayFactory` internal slot directly because this + * functionality doesn't exist as the public API of CLIEngine. + */ + if (hasDefinedProperty(options.overrideConfig)) { + configArrayFactory.setOverrideConfig(options.overrideConfig); + updated = true; + } + + // Update caches. + if (updated) { + configArrayFactory.clearCache(); + lastConfigArrays[0] = configArrayFactory.getConfigArrayForFile(); + } + + // Initialize private properties. + privateMembersMap.set(this, { + cliEngine, + options: processedOptions, + }); + } + + /** + * The version text. + * @type {string} + */ + static get version() { + return version; + } + + /** + * Outputs fixes from the given results to files. + * @param {LintResult[]} results The lint results. + * @returns {Promise} Returns a promise that is used to track side effects. + */ + static async outputFixes(results) { + if (!Array.isArray(results)) { + throw new Error("'results' must be an array"); + } + + await Promise.all( + results + .filter(result => { + if (typeof result !== "object" || result === null) { + throw new Error("'results' must include only objects"); + } + return ( + typeof result.output === "string" && + path.isAbsolute(result.filePath) + ); + }) + .map(r => writeFile(r.filePath, r.output)), + ); + } + + /** + * Returns results that only contains errors. + * @param {LintResult[]} results The results to filter. + * @returns {LintResult[]} The filtered results. + */ + static getErrorResults(results) { + return CLIEngine.getErrorResults(results); + } + + /** + * Returns meta objects for each rule represented in the lint results. + * @param {LintResult[]} results The results to fetch rules meta for. + * @returns {Object} A mapping of ruleIds to rule meta objects. + */ + getRulesMetaForResults(results) { + const resultRuleIds = new Set(); + + // first gather all ruleIds from all results + + for (const result of results) { + for (const { ruleId } of result.messages) { + resultRuleIds.add(ruleId); + } + for (const { ruleId } of result.suppressedMessages) { + resultRuleIds.add(ruleId); + } + } + + // create a map of all rules in the results + + const { cliEngine } = privateMembersMap.get(this); + const rules = cliEngine.getRules(); + const resultRules = new Map(); + + for (const [ruleId, rule] of rules) { + if (resultRuleIds.has(ruleId)) { + resultRules.set(ruleId, rule); + } + } + + return createRulesMeta(resultRules); + } + + /* eslint-disable no-unused-vars, class-methods-use-this -- leaving for compatibility with ESLint#hasFlag */ + /** + * Indicates if the given feature flag is enabled for this instance. For this + * class, this always returns `false` because it does not support feature flags. + * @param {string} flag The feature flag to check. + * @returns {boolean} Always false. + */ + hasFlag(flag) { + return false; + } + /* eslint-enable no-unused-vars, class-methods-use-this -- reenable rules for the rest of the file */ + + /** + * Executes the current configuration on an array of file and directory names. + * @param {string[]} patterns An array of file and directory names. + * @returns {Promise} The results of linting the file patterns given. + */ + async lintFiles(patterns) { + const { cliEngine, options } = privateMembersMap.get(this); + + if ( + options.passOnNoPatterns && + (patterns === "" || + (Array.isArray(patterns) && patterns.length === 0)) + ) { + return []; + } + + if (!isNonEmptyString(patterns) && !isArrayOfNonEmptyString(patterns)) { + throw new Error( + "'patterns' must be a non-empty string or an array of non-empty strings", + ); + } + + return processCLIEngineLintReport( + cliEngine, + cliEngine.executeOnFiles(patterns), + ); + } + + /** + * Executes the current configuration on text. + * @param {string} code A string of JavaScript code to lint. + * @param {Object} [options] The options. + * @param {string} [options.filePath] The path to the file of the source code. + * @param {boolean} [options.warnIgnored] When set to true, warn if given filePath is an ignored path. + * @returns {Promise} The results of linting the string of code given. + */ + async lintText(code, options = {}) { + if (typeof code !== "string") { + throw new Error("'code' must be a string"); + } + if (typeof options !== "object") { + throw new Error("'options' must be an object, null, or undefined"); + } + const { + filePath, + warnIgnored = false, + ...unknownOptions + } = options || {}; + + const unknownOptionKeys = Object.keys(unknownOptions); + + if (unknownOptionKeys.length > 0) { + throw new Error( + `'options' must not include the unknown option(s): ${unknownOptionKeys.join(", ")}`, + ); + } + + if (filePath !== void 0 && !isNonEmptyString(filePath)) { + throw new Error( + "'options.filePath' must be a non-empty string or undefined", + ); + } + if (typeof warnIgnored !== "boolean") { + throw new Error( + "'options.warnIgnored' must be a boolean or undefined", + ); + } + + const { cliEngine } = privateMembersMap.get(this); + + return processCLIEngineLintReport( + cliEngine, + cliEngine.executeOnText(code, filePath, warnIgnored), + ); + } + + /** + * Returns the formatter representing the given formatter name. + * @param {string} [name] The name of the formatter to load. + * The following values are allowed: + * - `undefined` ... Load `stylish` builtin formatter. + * - A builtin formatter name ... Load the builtin formatter. + * - A third-party formatter name: + * - `foo` → `eslint-formatter-foo` + * - `@foo` → `@foo/eslint-formatter` + * - `@foo/bar` → `@foo/eslint-formatter-bar` + * - A file path ... Load the file. + * @returns {Promise} A promise resolving to the formatter object. + * This promise will be rejected if the given formatter was not found or not + * a function. + */ + async loadFormatter(name = "stylish") { + if (typeof name !== "string") { + throw new Error("'name' must be a string"); + } + + const { cliEngine, options } = privateMembersMap.get(this); + const formatter = cliEngine.getFormatter(name); + + if (typeof formatter !== "function") { + throw new Error( + `Formatter must be a function, but got a ${typeof formatter}.`, + ); + } + + return { + /** + * The main formatter method. + * @param {LintResult[]} results The lint results to format. + * @param {ResultsMeta} resultsMeta Warning count and max threshold. + * @returns {string | Promise} The formatted lint results. + */ + format(results, resultsMeta) { + let rulesMeta = null; + + results.sort(compareResultsByFilePath); + + return formatter(results, { + ...resultsMeta, + get cwd() { + return options.cwd; + }, + get rulesMeta() { + if (!rulesMeta) { + rulesMeta = createRulesMeta(cliEngine.getRules()); + } + + return rulesMeta; + }, + }); + }, + }; + } + + /** + * Returns a configuration object for the given file based on the CLI options. + * This is the same logic used by the ESLint CLI executable to determine + * configuration for each file it processes. + * @param {string} filePath The path of the file to retrieve a config object for. + * @returns {Promise} A configuration object for the file. + */ + async calculateConfigForFile(filePath) { + if (!isNonEmptyString(filePath)) { + throw new Error("'filePath' must be a non-empty string"); + } + const { cliEngine } = privateMembersMap.get(this); + + return cliEngine.getConfigForFile(filePath); + } + + /** + * Checks if a given path is ignored by ESLint. + * @param {string} filePath The path of the file to check. + * @returns {Promise} Whether or not the given path is ignored. + */ + async isPathIgnored(filePath) { + if (!isNonEmptyString(filePath)) { + throw new Error("'filePath' must be a non-empty string"); + } + const { cliEngine } = privateMembersMap.get(this); + + return cliEngine.isPathIgnored(filePath); + } +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = { + LegacyESLint, + + /** + * Get the private class members of a given ESLint instance for tests. + * @param {ESLint} instance The ESLint instance to get. + * @returns {ESLintPrivateMembers} The instance's private class members. + */ + getESLintPrivateMembers(instance) { + return privateMembersMap.get(instance); + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/eslint/worker.js b/tools/ui/node_modules/eslint/lib/eslint/worker.js new file mode 100644 index 0000000000000000000000000000000000000000..7001bf2143047eed0d9a167e9240322d23c9d0b9 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/eslint/worker.js @@ -0,0 +1,173 @@ +/** + * @fileoverview Worker thread for multithread linting. + * @author Francesco Trotta + */ + +"use strict"; + +const hrtimeBigint = process.hrtime.bigint; + +const startTime = hrtimeBigint(); + +// eslint-disable-next-line n/no-unsupported-features/node-builtins -- enable V8's code cache if supported +require("node:module").enableCompileCache?.(); + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { parentPort, threadId, workerData } = require("node:worker_threads"); +const { + createConfigLoader, + createDebug, + createDefaultConfigs, + createLinter, + createLintResultCache, + getCacheFile, + lintFile, + loadOptionsFromModule, + processOptions, +} = require("./eslint-helpers"); +const { WarningService } = require("../services/warning-service"); +const timing = require("../linter/timing"); + +const depsLoadedTime = hrtimeBigint(); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** @typedef {import("../types").ESLint.LintResult} LintResult */ +/** @typedef {import("../types").ESLint.Options} ESLintOptions */ +/** @typedef {LintResult & { index?: number; }} IndexedLintResult */ +/** @typedef {IndexedLintResult[] & { netLintingDuration: bigint; timings?: Record; }} WorkerLintResults */ +/** + * @typedef {Object} WorkerData - Data passed to the worker thread. + * @property {ESLintOptions | string} eslintOptionsOrURL - The unprocessed ESLint options or the URL of the options module. + * @property {Uint32Array} filePathIndexArray - Shared counter used to track the next file to lint. + * @property {string[]} filePaths - File paths to lint. + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const debug = createDebug(`eslint:worker:thread-${threadId}`); + +//------------------------------------------------------------------------------ +// Main +//------------------------------------------------------------------------------ + +/* + * Prevent timing module from printing profiling output from worker threads. + * The main thread is responsible for displaying any aggregated timings. + */ +timing.disableDisplay(); + +debug("Dependencies loaded in %t", depsLoadedTime - startTime); + +(async () => { + /** @type {WorkerData} */ + const { eslintOptionsOrURL, filePathIndexArray, filePaths } = workerData; + const eslintOptions = + typeof eslintOptionsOrURL === "object" + ? eslintOptionsOrURL + : await loadOptionsFromModule(eslintOptionsOrURL); + const processedESLintOptions = processOptions(eslintOptions); + + const warningService = new WarningService(); + + // These warnings are always emitted by the controlling thread. + warningService.emitEmptyConfigWarning = + warningService.emitInactiveFlagWarning = () => {}; + + const linter = createLinter(processedESLintOptions, warningService); + + const cacheFilePath = getCacheFile( + processedESLintOptions.cacheLocation, + processedESLintOptions.cwd, + ); + + const lintResultCache = createLintResultCache( + processedESLintOptions, + cacheFilePath, + ); + const defaultConfigs = createDefaultConfigs(eslintOptions.plugins); + + const configLoader = createConfigLoader( + processedESLintOptions, + defaultConfigs, + linter, + warningService, + ); + + /** @type {WorkerLintResults} */ + const indexedResults = []; + let loadConfigTotalDuration = 0n; + const readFileCounter = { duration: 0n }; + + const lintingStartTime = hrtimeBigint(); + debug( + "Linting started %t after dependencies loaded", + lintingStartTime - depsLoadedTime, + ); + + for (;;) { + const fileLintingStartTime = hrtimeBigint(); + + // It seems hard to produce an arithmetic overflow under realistic conditions here. + const index = Atomics.add(filePathIndexArray, 0, 1); + + const filePath = filePaths[index]; + if (!filePath) { + break; + } + + const loadConfigEnterTime = hrtimeBigint(); + const configs = await configLoader.loadConfigArrayForFile(filePath); + const loadConfigExitTime = hrtimeBigint(); + const loadConfigDuration = loadConfigExitTime - loadConfigEnterTime; + debug( + 'Config array for file "%s" loaded in %t', + filePath, + loadConfigDuration, + ); + loadConfigTotalDuration += loadConfigDuration; + + /** @type {IndexedLintResult} */ + const result = await lintFile( + filePath, + configs, + processedESLintOptions, + linter, + lintResultCache, + readFileCounter, + ); + if (result) { + result.index = index; + indexedResults.push(result); + } + + const fileLintingEndTime = hrtimeBigint(); + debug( + 'File "%s" processed in %t', + filePath, + fileLintingEndTime - fileLintingStartTime, + ); + } + + const lintingDuration = hrtimeBigint() - lintingStartTime; + + /* + * The net linting duration is the total linting time minus the time spent loading configs and reading files. + * It captures the processing time dedicated to computation-intensive tasks that are highly parallelizable and not repeated across threads. + */ + indexedResults.netLintingDuration = + lintingDuration - loadConfigTotalDuration - readFileCounter.duration; + + if (timing.enabled) { + indexedResults.timings = timing.getData(); + } + + parentPort.postMessage(indexedResults); +})(); diff --git a/tools/ui/node_modules/eslint/lib/languages/js/index.js b/tools/ui/node_modules/eslint/lib/languages/js/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a6bf0d7f6de288d02e739fee8602f851233c0ceb --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/languages/js/index.js @@ -0,0 +1,336 @@ +/** + * @fileoverview JavaScript Language Object + * @author Nicholas C. Zakas + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Requirements +//----------------------------------------------------------------------------- + +const { SourceCode } = require("./source-code"); +const createDebug = require("debug"); +const astUtils = require("../../shared/ast-utils"); +const espree = require("espree"); +const eslintScope = require("eslint-scope"); +const evk = require("eslint-visitor-keys"); +const { validateLanguageOptions } = require("./validate-language-options"); +const { LATEST_ECMA_VERSION } = require("../../../conf/ecma-version"); + +//----------------------------------------------------------------------------- +// Type Definitions +//----------------------------------------------------------------------------- + +/** @typedef {import("@eslint/core").File} File */ +/** @typedef {import("@eslint/core").Language} Language */ +/** @typedef {import("@eslint/core").OkParseResult} OkParseResult */ +/** @typedef {import("../../types").Linter.LanguageOptions} JSLanguageOptions */ + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +const debug = createDebug("eslint:languages:js"); +const DEFAULT_ECMA_VERSION = 5; +const parserSymbol = Symbol.for("eslint.RuleTester.parser"); + +/** + * Analyze scope of the given AST. + * @param {ASTNode} ast The `Program` node to analyze. + * @param {JSLanguageOptions} languageOptions The parser options. + * @param {Record} visitorKeys The visitor keys. + * @returns {ScopeManager} The analysis result. + */ +function analyzeScope(ast, languageOptions, visitorKeys) { + const parserOptions = languageOptions.parserOptions; + const ecmaFeatures = parserOptions.ecmaFeatures || {}; + const ecmaVersion = languageOptions.ecmaVersion || DEFAULT_ECMA_VERSION; + + return eslintScope.analyze(ast, { + ignoreEval: true, + nodejsScope: ecmaFeatures.globalReturn, + impliedStrict: ecmaFeatures.impliedStrict, + ecmaVersion: typeof ecmaVersion === "number" ? ecmaVersion : 6, + sourceType: languageOptions.sourceType || "script", + childVisitorKeys: visitorKeys || evk.KEYS, + fallback: evk.getKeys, + }); +} + +/** + * Determines if a given object is Espree. + * @param {Object} parser The parser to check. + * @returns {boolean} True if the parser is Espree or false if not. + */ +function isEspree(parser) { + return !!(parser === espree || parser[parserSymbol] === espree); +} + +/** + * Normalize ECMAScript version from the initial config into languageOptions (year) + * format. + * @param {any} [ecmaVersion] ECMAScript version from the initial config + * @returns {number} normalized ECMAScript version + */ +function normalizeEcmaVersionForLanguageOptions(ecmaVersion) { + switch (ecmaVersion) { + case 3: + return 3; + + // void 0 = no ecmaVersion specified so use the default + case 5: + case void 0: + return 5; + + default: + if (typeof ecmaVersion === "number") { + return ecmaVersion >= 2015 ? ecmaVersion : ecmaVersion + 2009; + } + } + + /* + * We default to the latest supported ecmaVersion for everything else. + * Remember, this is for languageOptions.ecmaVersion, which sets the version + * that is used for a number of processes inside of ESLint. It's normally + * safe to assume people want the latest unless otherwise specified. + */ + return LATEST_ECMA_VERSION; +} + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * @type {Language} + */ +module.exports = { + fileType: "text", + lineStart: 1, + columnStart: 0, + nodeTypeKey: "type", + visitorKeys: evk.KEYS, + + defaultLanguageOptions: { + sourceType: "module", + ecmaVersion: "latest", + parser: espree, + parserOptions: {}, + }, + + validateLanguageOptions, + + /** + * Normalizes the language options. + * @param {Object} languageOptions The language options to normalize. + * @returns {Object} The normalized language options. + */ + normalizeLanguageOptions(languageOptions) { + languageOptions.ecmaVersion = normalizeEcmaVersionForLanguageOptions( + languageOptions.ecmaVersion, + ); + + // Espree expects this information to be passed in + if (isEspree(languageOptions.parser)) { + const parserOptions = languageOptions.parserOptions; + + if (languageOptions.sourceType) { + parserOptions.sourceType = languageOptions.sourceType; + + if ( + parserOptions.sourceType === "module" && + parserOptions.ecmaFeatures && + parserOptions.ecmaFeatures.globalReturn + ) { + parserOptions.ecmaFeatures.globalReturn = false; + } + } + } + + return languageOptions; + }, + + /** + * Determines if a given node matches a given selector class. + * @param {string} className The class name to check. + * @param {ASTNode} node The node to check. + * @param {Array} ancestry The ancestry of the node. + * @returns {boolean} True if there's a match, false if not. + * @throws {Error} When an unknown class name is passed. + */ + matchesSelectorClass(className, node, ancestry) { + /* + * Copyright (c) 2013, Joel Feenstra + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the ESQuery nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL JOEL FEENSTRA BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + switch (className.toLowerCase()) { + case "statement": + if (node.type.slice(-9) === "Statement") { + return true; + } + + // fallthrough: interface Declaration <: Statement { } + + case "declaration": + return node.type.slice(-11) === "Declaration"; + + case "pattern": + if (node.type.slice(-7) === "Pattern") { + return true; + } + + // fallthrough: interface Expression <: Node, Pattern { } + + case "expression": + return ( + node.type.slice(-10) === "Expression" || + node.type.slice(-7) === "Literal" || + (node.type === "Identifier" && + (ancestry.length === 0 || + ancestry[0].type !== "MetaProperty")) || + node.type === "MetaProperty" + ); + + case "function": + return ( + node.type === "FunctionDeclaration" || + node.type === "FunctionExpression" || + node.type === "ArrowFunctionExpression" + ); + + default: + throw new Error(`Unknown class name: ${className}`); + } + }, + + /** + * Parses the given file into an AST. + * @param {File} file The virtual file to parse. + * @param {Object} options Additional options passed from ESLint. + * @param {JSLanguageOptions} options.languageOptions The language options. + * @returns {Object} The result of parsing. + */ + parse(file, { languageOptions }) { + // Note: BOM already removed + const { body: text, path: filePath } = file; + const textToParse = text.replace( + astUtils.shebangPattern, + (match, captured) => `//${captured}`, + ); + const { ecmaVersion, sourceType, parser } = languageOptions; + const parserOptions = Object.assign( + { ecmaVersion, sourceType }, + languageOptions.parserOptions, + { + loc: true, + range: true, + raw: true, + tokens: true, + comment: true, + eslintVisitorKeys: true, + eslintScopeManager: true, + filePath, + }, + ); + + /* + * Check for parsing errors first. If there's a parsing error, nothing + * else can happen. However, a parsing error does not throw an error + * from this method - it's just considered a fatal error message, a + * problem that ESLint identified just like any other. + */ + try { + debug("Parsing:", filePath); + const parseResult = + typeof parser.parseForESLint === "function" + ? parser.parseForESLint(textToParse, parserOptions) + : { ast: parser.parse(textToParse, parserOptions) }; + + debug("Parsing successful:", filePath); + + const { + ast, + services: parserServices = {}, + visitorKeys = evk.KEYS, + scopeManager, + } = parseResult; + + return { + ok: true, + ast, + parserServices, + visitorKeys, + scopeManager, + }; + } catch (ex) { + // If the message includes a leading line number, strip it: + const message = ex.message.replace(/^line \d+:/iu, "").trim(); + + debug("%s\n%s", message, ex.stack); + + return { + ok: false, + errors: [ + { + message, + line: ex.lineNumber, + column: ex.column, + }, + ], + }; + } + }, + + /** + * Creates a new `SourceCode` object from the given information. + * @param {File} file The virtual file to create a `SourceCode` object from. + * @param {OkParseResult} parseResult The result returned from `parse()`. + * @param {Object} options Additional options passed from ESLint. + * @param {JSLanguageOptions} options.languageOptions The language options. + * @returns {SourceCode} The new `SourceCode` object. + */ + createSourceCode(file, parseResult, { languageOptions }) { + const { body: text, path: filePath, bom: hasBOM } = file; + const { ast, parserServices, visitorKeys } = parseResult; + + debug("Scope analysis:", filePath); + const scopeManager = + parseResult.scopeManager || + analyzeScope(ast, languageOptions, visitorKeys); + + debug("Scope analysis successful:", filePath); + + return new SourceCode({ + text, + ast, + hasBOM, + parserServices, + scopeManager, + visitorKeys, + }); + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/languages/js/source-code/index.js b/tools/ui/node_modules/eslint/lib/languages/js/source-code/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f4003e393ae84f572865792442663371e61140a6 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/languages/js/source-code/index.js @@ -0,0 +1,7 @@ +"use strict"; + +const SourceCode = require("./source-code"); + +module.exports = { + SourceCode, +}; diff --git a/tools/ui/node_modules/eslint/lib/languages/js/source-code/source-code.js b/tools/ui/node_modules/eslint/lib/languages/js/source-code/source-code.js new file mode 100644 index 0000000000000000000000000000000000000000..f31b0933b27a34cd77aa805734ba6b75c79b70e4 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/languages/js/source-code/source-code.js @@ -0,0 +1,1364 @@ +/** + * @fileoverview Abstraction of JavaScript source code. + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { isCommentToken } = require("@eslint-community/eslint-utils"), + TokenStore = require("./token-store"), + astUtils = require("../../../shared/ast-utils"), + Traverser = require("../../../shared/traverser"), + globals = require("../../../../conf/globals"), + { directivesPattern } = require("../../../shared/directives"), + CodePathAnalyzer = require("../../../linter/code-path-analysis/code-path-analyzer"), + { + ConfigCommentParser, + VisitNodeStep, + CallMethodStep, + Directive, + } = require("@eslint/plugin-kit"), + eslintScope = require("eslint-scope"); + +//------------------------------------------------------------------------------ +// Type Definitions +//------------------------------------------------------------------------------ + +/** @typedef {import("eslint-scope").Variable} Variable */ +/** @typedef {import("eslint-scope").Scope} Scope */ +/** @typedef {import("@eslint/core").SourceCode} ISourceCode */ +/** @typedef {import("@eslint/core").Directive} IDirective */ +/** @typedef {import("@eslint/core").TraversalStep} ITraversalStep */ + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ + +const commentParser = new ConfigCommentParser(); + +/** + * Validates that the given AST has the required information. + * @param {ASTNode} ast The Program node of the AST to check. + * @throws {TypeError} If the AST doesn't contain the correct information. + * @returns {void} + * @private + */ +function validate(ast) { + if (!ast) { + throw new TypeError(`Unexpected empty AST. (${ast})`); + } + + if (!ast.tokens) { + throw new TypeError("AST is missing the tokens array."); + } + + if (!ast.comments) { + throw new TypeError("AST is missing the comments array."); + } + + if (!ast.loc) { + throw new TypeError("AST is missing location information."); + } + + if (!ast.range) { + throw new TypeError("AST is missing range information"); + } +} + +/** + * Retrieves globals for the given ecmaVersion. + * @param {number} ecmaVersion The version to retrieve globals for. + * @returns {Object} The globals for the given ecmaVersion. + */ +function getGlobalsForEcmaVersion(ecmaVersion) { + switch (ecmaVersion) { + case 3: + return globals.es3; + + case 5: + return globals.es5; + + default: + if (ecmaVersion < 2015) { + return globals[`es${ecmaVersion + 2009}`]; + } + + return globals[`es${ecmaVersion}`]; + } +} + +/** + * Check to see if its a ES6 export declaration. + * @param {ASTNode} astNode An AST node. + * @returns {boolean} whether the given node represents an export declaration. + * @private + */ +function looksLikeExport(astNode) { + return ( + astNode.type === "ExportDefaultDeclaration" || + astNode.type === "ExportNamedDeclaration" || + astNode.type === "ExportAllDeclaration" || + astNode.type === "ExportSpecifier" + ); +} + +/** + * Merges two sorted lists into a larger sorted list in O(n) time. + * @param {Token[]} tokens The list of tokens. + * @param {Token[]} comments The list of comments. + * @returns {Token[]} A sorted list of tokens and comments. + * @private + */ +function sortedMerge(tokens, comments) { + const result = []; + let tokenIndex = 0; + let commentIndex = 0; + + while (tokenIndex < tokens.length || commentIndex < comments.length) { + if ( + commentIndex >= comments.length || + (tokenIndex < tokens.length && + tokens[tokenIndex].range[0] < comments[commentIndex].range[0]) + ) { + result.push(tokens[tokenIndex++]); + } else { + result.push(comments[commentIndex++]); + } + } + + return result; +} + +/** + * Normalizes a value for a global in a config + * @param {(boolean|string|null)} configuredValue The value given for a global in configuration or in + * a global directive comment + * @returns {("readonly"|"writable"|"off")} The value normalized as a string + * @throws {Error} if global value is invalid + */ +function normalizeConfigGlobal(configuredValue) { + switch (configuredValue) { + case "off": + return "off"; + + case true: + case "true": + case "writeable": + case "writable": + return "writable"; + + case null: + case false: + case "false": + case "readable": + case "readonly": + return "readonly"; + + default: + throw new Error( + `'${configuredValue}' is not a valid configuration for a global (use 'readonly', 'writable', or 'off')`, + ); + } +} + +/** + * Determines if two nodes or tokens overlap. + * @param {ASTNode|Token} first The first node or token to check. + * @param {ASTNode|Token} second The second node or token to check. + * @returns {boolean} True if the two nodes or tokens overlap. + * @private + */ +function nodesOrTokensOverlap(first, second) { + return ( + (first.range[0] <= second.range[0] && + first.range[1] >= second.range[0]) || + (second.range[0] <= first.range[0] && second.range[1] >= first.range[0]) + ); +} + +/** + * Determines if two nodes or tokens have at least one whitespace character + * between them. Order does not matter. Returns false if the given nodes or + * tokens overlap. + * @param {SourceCode} sourceCode The source code object. + * @param {ASTNode|Token} first The first node or token to check between. + * @param {ASTNode|Token} second The second node or token to check between. + * @param {boolean} checkInsideOfJSXText If `true` is present, check inside of JSXText tokens for backward compatibility. + * @returns {boolean} True if there is a whitespace character between + * any of the tokens found between the two given nodes or tokens. + * @public + */ +function isSpaceBetween(sourceCode, first, second, checkInsideOfJSXText) { + if (nodesOrTokensOverlap(first, second)) { + return false; + } + + const [startingNodeOrToken, endingNodeOrToken] = + first.range[1] <= second.range[0] ? [first, second] : [second, first]; + const firstToken = + sourceCode.getLastToken(startingNodeOrToken) || startingNodeOrToken; + const finalToken = + sourceCode.getFirstToken(endingNodeOrToken) || endingNodeOrToken; + let currentToken = firstToken; + + while (currentToken !== finalToken) { + const nextToken = sourceCode.getTokenAfter(currentToken, { + includeComments: true, + }); + + if ( + currentToken.range[1] !== nextToken.range[0] || + /* + * For backward compatibility, check spaces in JSXText. + * https://github.com/eslint/eslint/issues/12614 + */ + (checkInsideOfJSXText && + nextToken !== finalToken && + nextToken.type === "JSXText" && + /\s/u.test(nextToken.value)) + ) { + return true; + } + + currentToken = nextToken; + } + + return false; +} + +/** + * Performs binary search to find the line number containing a given character index. + * Returns the lower bound - the index of the first element greater than the target. + * **Please note that the `lineStartIndices` should be sorted in ascending order**. + * - Time Complexity: O(log n) - Significantly faster than linear search for large files. + * @param {number[]} lineStartIndices Sorted array of line start indices. + * @param {number} target The character index to find the line number for. + * @returns {number} The 1-based line number for the target index. + * @private + */ +function findLineNumberBinarySearch(lineStartIndices, target) { + let low = 0; + let high = lineStartIndices.length; + + while (low < high) { + const mid = ((low + high) / 2) | 0; // Use bitwise OR to floor the division + + if (target < lineStartIndices[mid]) { + high = mid; + } else { + low = mid + 1; + } + } + + return low; +} + +//----------------------------------------------------------------------------- +// Directive Comments +//----------------------------------------------------------------------------- + +/** + * Ensures that variables representing built-in properties of the Global Object, + * and any globals declared by special block comments, are present in the global + * scope. + * @param {Scope} globalScope The global scope. + * @param {Object|undefined} configGlobals The globals declared in configuration + * @param {Object|undefined} inlineGlobals The globals declared in the source code + * @returns {void} + */ +function addDeclaredGlobals( + globalScope, + configGlobals = {}, + inlineGlobals = {}, +) { + // Define configured global variables. + for (const id of new Set([ + ...Object.keys(configGlobals), + ...Object.keys(inlineGlobals), + ])) { + /* + * `normalizeConfigGlobal` will throw an error if a configured global value is invalid. However, these errors would + * typically be caught when validating a config anyway (validity for inline global comments is checked separately). + */ + const configValue = + configGlobals[id] === void 0 + ? void 0 + : normalizeConfigGlobal(configGlobals[id]); + const commentValue = inlineGlobals[id] && inlineGlobals[id].value; + const value = commentValue || configValue; + const sourceComments = inlineGlobals[id] && inlineGlobals[id].comments; + + if (value === "off") { + continue; + } + + let variable = globalScope.set.get(id); + + if (!variable) { + variable = new eslintScope.Variable(id, globalScope); + + globalScope.variables.push(variable); + globalScope.set.set(id, variable); + } + + variable.eslintImplicitGlobalSetting = configValue; + variable.eslintExplicitGlobal = sourceComments !== void 0; + variable.eslintExplicitGlobalComments = sourceComments; + variable.writeable = value === "writable"; + } + + /* + * "through" contains all references which definitions cannot be found. + * Since we augment the global scope using configuration, we need to update + * references and remove the ones that were added by configuration. + */ + globalScope.through = globalScope.through.filter(reference => { + const name = reference.identifier.name; + const variable = globalScope.set.get(name); + + if (variable) { + /* + * Links the variable and the reference. + * And this reference is removed from `Scope#through`. + */ + reference.resolved = variable; + variable.references.push(reference); + + return false; + } + + return true; + }); + + /* + * "implicit" contains information about implicit global variables (those created + * implicitly by assigning values to undeclared variables in non-strict code). + * Since we augment the global scope using configuration, we need to remove + * the ones that were added by configuration, as they are either built-in + * or declared elsewhere, therefore not implicit. + * Since the "implicit" property was not documented, first we'll check if it exists + * because it's possible that not all custom scope managers create this property. + * If it exists, we assume it has properties `variables` and `set`. Property + * `left` is considered optional (for example, typescript-eslint's scope manage + * has this property named `leftToBeResolved`). + */ + const { implicit } = globalScope; + if (typeof implicit === "object" && implicit !== null) { + implicit.variables = implicit.variables.filter(variable => { + const name = variable.name; + if (globalScope.set.has(name)) { + implicit.set.delete(name); + return false; + } + return true; + }); + + if (implicit.left) { + implicit.left = implicit.left.filter( + reference => !globalScope.set.has(reference.identifier.name), + ); + } + } +} + +/** + * Sets the given variable names as exported so they won't be triggered by + * the `no-unused-vars` rule. + * @param {eslint.Scope} globalScope The global scope to define exports in. + * @param {Record} variables An object whose keys are the variable + * names to export. + * @returns {void} + */ +function markExportedVariables(globalScope, variables) { + Object.keys(variables).forEach(name => { + const variable = globalScope.set.get(name); + + if (variable) { + variable.eslintUsed = true; + variable.eslintExported = true; + } + }); +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +const caches = Symbol("caches"); + +/** + * Represents parsed source code. + * @implements {ISourceCode} + */ +class SourceCode extends TokenStore { + /** + * The cache of steps that were taken while traversing the source code. + * @type {Array} + */ + #steps; + + /** + * Creates a new instance. + * @param {string|Object} textOrConfig The source code text or config object. + * @param {string} textOrConfig.text The source code text. + * @param {ASTNode} textOrConfig.ast The Program node of the AST representing the code. This AST should be created from the text that BOM was stripped. + * @param {boolean} textOrConfig.hasBOM Indicates if the text has a Unicode BOM. + * @param {Object|null} textOrConfig.parserServices The parser services. + * @param {ScopeManager|null} textOrConfig.scopeManager The scope of this source code. + * @param {Object|null} textOrConfig.visitorKeys The visitor keys to traverse AST. + * @param {ASTNode} [astIfNoConfig] The Program node of the AST representing the code. This AST should be created from the text that BOM was stripped. + */ + constructor(textOrConfig, astIfNoConfig) { + let text, hasBOM, ast, parserServices, scopeManager, visitorKeys; + + // Process overloading of arguments + if (typeof textOrConfig === "string") { + text = textOrConfig; + ast = astIfNoConfig; + hasBOM = false; + } else if (typeof textOrConfig === "object" && textOrConfig !== null) { + text = textOrConfig.text; + ast = textOrConfig.ast; + hasBOM = textOrConfig.hasBOM; + parserServices = textOrConfig.parserServices; + scopeManager = textOrConfig.scopeManager; + visitorKeys = textOrConfig.visitorKeys; + } + + validate(ast); + super(ast.tokens, ast.comments); + + /** + * General purpose caching for the class. + */ + this[caches] = new Map([ + ["scopes", new WeakMap()], + ["vars", new Map()], + ["configNodes", void 0], + ["isGlobalReference", new WeakMap()], + ]); + + /** + * Indicates if the AST is ESTree compatible. + * @type {boolean} + */ + this.isESTree = ast.type === "Program"; + + /* + * Backwards compatibility for BOM handling. + * + * The `hasBOM` property has been available on the `SourceCode` object + * for a long time and is used to indicate if the source contains a BOM. + * The linter strips the BOM and just passes the `hasBOM` property to the + * `SourceCode` constructor to make it easier for languages to not deal with + * the BOM. + * + * However, the text passed in to the `SourceCode` constructor might still + * have a BOM if the constructor is called outside of the linter, so we still + * need to check for the BOM in the text. + */ + const textHasBOM = text.charCodeAt(0) === 0xfeff; + + /** + * The flag to indicate that the source code has Unicode BOM. + * @type {boolean} + */ + this.hasBOM = textHasBOM || !!hasBOM; + + /** + * The original text source code. + * BOM was stripped from this text. + * @type {string} + */ + this.text = textHasBOM ? text.slice(1) : text; + + /** + * The parsed AST for the source code. + * @type {ASTNode} + */ + this.ast = ast; + + /** + * The parser services of this source code. + * @type {Object} + */ + this.parserServices = parserServices || {}; + + /** + * The scope of this source code. + * @type {ScopeManager|null} + */ + this.scopeManager = scopeManager || null; + + /** + * The visitor keys to traverse AST. + * @type {Object} + */ + this.visitorKeys = visitorKeys || Traverser.DEFAULT_VISITOR_KEYS; + + // Check the source text for the presence of a shebang since it is parsed as a standard line comment. + const shebangMatched = this.text.match(astUtils.shebangPattern); + const hasShebang = + shebangMatched && + ast.comments.length && + ast.comments[0].value === shebangMatched[1]; + + if (hasShebang) { + ast.comments[0].type = "Shebang"; + } + + this.tokensAndComments = sortedMerge(ast.tokens, ast.comments); + + /** + * The source code split into lines according to ECMA-262 specification. + * This is done to avoid each rule needing to do so separately. + * @type {string[]} + */ + this.lines = []; + + /** + * @type {number[]} + */ + this.lineStartIndices = [0]; + + const lineEndingPattern = astUtils.createGlobalLinebreakMatcher(); + let match; + + /* + * Previously, this was implemented using a regex that + * matched a sequence of non-linebreak characters followed by a + * linebreak, then adding the lengths of the matches. However, + * this caused a catastrophic backtracking issue when the end + * of a file contained a large number of non-newline characters. + * To avoid this, the current implementation just matches newlines + * and uses match.index to get the correct line start indices. + */ + while ((match = lineEndingPattern.exec(this.text))) { + this.lines.push( + this.text.slice(this.lineStartIndices.at(-1), match.index), + ); + this.lineStartIndices.push(match.index + match[0].length); + } + this.lines.push(this.text.slice(this.lineStartIndices.at(-1))); + + // don't allow further modification of this object + Object.freeze(this); + Object.freeze(this.lines); + } + + /** + * Split the source code into multiple lines based on the line delimiters. + * @param {string} text Source code as a string. + * @returns {string[]} Array of source code lines. + * @public + */ + static splitLines(text) { + return text.split(astUtils.createGlobalLinebreakMatcher()); + } + + /** + * Gets the source code for the given node. + * @param {ASTNode} [node] The AST node to get the text for. + * @param {number} [beforeCount] The number of characters before the node to retrieve. + * @param {number} [afterCount] The number of characters after the node to retrieve. + * @returns {string} The text representing the AST node. + * @public + */ + getText(node, beforeCount, afterCount) { + if (node) { + return this.text.slice( + Math.max(node.range[0] - (beforeCount || 0), 0), + node.range[1] + (afterCount || 0), + ); + } + return this.text; + } + + /** + * Gets the entire source text split into an array of lines. + * @returns {string[]} The source text as an array of lines. + * @public + */ + getLines() { + return this.lines; + } + + /** + * Retrieves an array containing all comments in the source code. + * @returns {ASTNode[]} An array of comment nodes. + * @public + */ + getAllComments() { + return this.ast.comments; + } + + /** + * Retrieves the JSDoc comment for a given node. + * @param {ASTNode} node The AST node to get the comment for. + * @returns {Token|null} The Block comment token containing the JSDoc comment + * for the given node or null if not found. + * @public + * @deprecated + */ + getJSDocComment(node) { + /** + * Checks for the presence of a JSDoc comment for the given node and returns it. + * @param {ASTNode} astNode The AST node to get the comment for. + * @returns {Token|null} The Block comment token containing the JSDoc comment + * for the given node or null if not found. + * @private + */ + const findJSDocComment = astNode => { + const tokenBefore = this.getTokenBefore(astNode, { + includeComments: true, + }); + + if ( + tokenBefore && + isCommentToken(tokenBefore) && + tokenBefore.type === "Block" && + tokenBefore.value.charAt(0) === "*" && + astNode.loc.start.line - tokenBefore.loc.end.line <= 1 + ) { + return tokenBefore; + } + + return null; + }; + let parent = node.parent; + + switch (node.type) { + case "ClassDeclaration": + case "FunctionDeclaration": + return findJSDocComment( + looksLikeExport(parent) ? parent : node, + ); + + case "ClassExpression": + return findJSDocComment(parent.parent); + + case "ArrowFunctionExpression": + case "FunctionExpression": + if ( + parent.type !== "CallExpression" && + parent.type !== "NewExpression" + ) { + while ( + !this.getCommentsBefore(parent).length && + !/Function/u.test(parent.type) && + parent.type !== "MethodDefinition" && + parent.type !== "Property" + ) { + parent = parent.parent; + + if (!parent) { + break; + } + } + + if ( + parent && + parent.type !== "FunctionDeclaration" && + parent.type !== "Program" + ) { + return findJSDocComment(parent); + } + } + + return findJSDocComment(node); + + // falls through + default: + return null; + } + } + + /** + * Gets the deepest node containing a range index. + * @param {number} index Range index of the desired node. + * @returns {ASTNode} The node if found or null if not found. + * @public + */ + getNodeByRangeIndex(index) { + let result = null; + + Traverser.traverse(this.ast, { + visitorKeys: this.visitorKeys, + enter(node) { + if (node.range[0] <= index && index < node.range[1]) { + result = node; + } else { + this.skip(); + } + }, + leave(node) { + if (node === result) { + this.break(); + } + }, + }); + + return result; + } + + /** + * Determines if two nodes or tokens have at least one whitespace character + * between them. Order does not matter. Returns false if the given nodes or + * tokens overlap. + * @param {ASTNode|Token} first The first node or token to check between. + * @param {ASTNode|Token} second The second node or token to check between. + * @returns {boolean} True if there is a whitespace character between + * any of the tokens found between the two given nodes or tokens. + * @public + */ + isSpaceBetween(first, second) { + return isSpaceBetween(this, first, second, false); + } + + /** + * Determines if two nodes or tokens have at least one whitespace character + * between them. Order does not matter. Returns false if the given nodes or + * tokens overlap. + * For backward compatibility, this method returns true if there are + * `JSXText` tokens that contain whitespaces between the two. + * @param {ASTNode|Token} first The first node or token to check between. + * @param {ASTNode|Token} second The second node or token to check between. + * @returns {boolean} True if there is a whitespace character between + * any of the tokens found between the two given nodes or tokens. + * @deprecated in favor of isSpaceBetween(). + * @public + */ + isSpaceBetweenTokens(first, second) { + return isSpaceBetween(this, first, second, true); + } + + /** + * Converts a source text index into a (line, column) pair. + * @param {number} index The index of a character in a file. + * @throws {TypeError|RangeError} If non-numeric index or index out of range. + * @returns {{line: number, column: number}} A {line, column} location object with 1-indexed line and 0-indexed column. + * @public + */ + getLocFromIndex(index) { + if (typeof index !== "number") { + throw new TypeError("Expected `index` to be a number."); + } + + if (index < 0 || index > this.text.length) { + throw new RangeError( + `Index out of range (requested index ${index}, but source text has length ${this.text.length}).`, + ); + } + + /* + * For an argument of this.text.length, return the location one "spot" past the last character + * of the file. If the last character is a linebreak, the location will be column 0 of the next + * line; otherwise, the location will be in the next column on the same line. + * + * See getIndexFromLoc for the motivation for this special case. + */ + if (index === this.text.length) { + return { + line: this.lines.length, + column: this.lines.at(-1).length, + }; + } + + /* + * To figure out which line index is on, determine the last place at which index could + * be inserted into lineStartIndices to keep the list sorted. + */ + const lineNumber = + index >= this.lineStartIndices.at(-1) + ? this.lineStartIndices.length + : findLineNumberBinarySearch(this.lineStartIndices, index); + + return { + line: lineNumber, + column: index - this.lineStartIndices[lineNumber - 1], + }; + } + + /** + * Converts a (line, column) pair into a range index. + * @param {Object} loc A line/column location + * @param {number} loc.line The line number of the location (1-indexed) + * @param {number} loc.column The column number of the location (0-indexed) + * @throws {TypeError|RangeError} If `loc` is not an object with a numeric + * `line` and `column`, if the `line` is less than or equal to zero or + * the line or column is out of the expected range. + * @returns {number} The range index of the location in the file. + * @public + */ + getIndexFromLoc(loc) { + if ( + loc === null || + typeof loc !== "object" || + typeof loc.line !== "number" || + typeof loc.column !== "number" + ) { + throw new TypeError( + "Expected `loc` to be an object with numeric `line` and `column` properties.", + ); + } + + if (loc.line <= 0) { + throw new RangeError( + `Line number out of range (line ${loc.line} requested). Line numbers should be 1-based.`, + ); + } + + if (loc.line > this.lineStartIndices.length) { + throw new RangeError( + `Line number out of range (line ${loc.line} requested, but only ${this.lineStartIndices.length} lines present).`, + ); + } + + if (loc.column < 0) { + throw new RangeError( + `Invalid column number (column ${loc.column} requested).`, + ); + } + + const lineStartIndex = this.lineStartIndices[loc.line - 1]; + const lineEndIndex = + loc.line === this.lineStartIndices.length + ? this.text.length + : this.lineStartIndices[loc.line]; + const positionIndex = lineStartIndex + loc.column; + + /* + * By design, getIndexFromLoc({ line: lineNum, column: 0 }) should return the start index of + * the given line, provided that the line number is valid element of this.lines. Since the + * last element of this.lines is an empty string for files with trailing newlines, add a + * special case where getting the index for the first location after the end of the file + * will return the length of the file, rather than throwing an error. This allows rules to + * use getIndexFromLoc consistently without worrying about edge cases at the end of a file. + */ + if ( + (loc.line === this.lineStartIndices.length && + positionIndex > lineEndIndex) || + (loc.line < this.lineStartIndices.length && + positionIndex >= lineEndIndex) + ) { + throw new RangeError( + `Column number out of range (column ${loc.column} requested, but the length of line ${loc.line} is ${lineEndIndex - lineStartIndex}).`, + ); + } + + return positionIndex; + } + + /** + * Gets the scope for the given node + * @param {ASTNode} currentNode The node to get the scope of + * @returns {Scope} The scope information for this node + * @throws {TypeError} If the `currentNode` argument is missing. + */ + getScope(currentNode) { + if (!currentNode) { + throw new TypeError("Missing required argument: node."); + } + + // check cache first + const cache = this[caches].get("scopes"); + const cachedScope = cache.get(currentNode); + + if (cachedScope) { + return cachedScope; + } + + // On Program node, get the outermost scope to avoid return Node.js special function scope or ES modules scope. + const inner = currentNode.type !== "Program"; + + for (let node = currentNode; node; node = node.parent) { + const scope = this.scopeManager.acquire(node, inner); + + if (scope) { + if (scope.type === "function-expression-name") { + cache.set(currentNode, scope.childScopes[0]); + return scope.childScopes[0]; + } + + cache.set(currentNode, scope); + return scope; + } + } + + cache.set(currentNode, this.scopeManager.scopes[0]); + return this.scopeManager.scopes[0]; + } + + /** + * Get the variables that `node` defines. + * This is a convenience method that passes through + * to the same method on the `scopeManager`. + * @param {ASTNode} node The node for which the variables are obtained. + * @returns {Array} An array of variable nodes representing + * the variables that `node` defines. + */ + getDeclaredVariables(node) { + return this.scopeManager.getDeclaredVariables(node); + } + + /* eslint-disable class-methods-use-this -- node is owned by SourceCode */ + /** + * Gets all the ancestors of a given node + * @param {ASTNode} node The node + * @returns {Array} All the ancestor nodes in the AST, not including the provided node, starting + * from the root node at index 0 and going inwards to the parent node. + * @throws {TypeError} When `node` is missing. + */ + getAncestors(node) { + if (!node) { + throw new TypeError("Missing required argument: node."); + } + + const ancestorsStartingAtParent = []; + + for (let ancestor = node.parent; ancestor; ancestor = ancestor.parent) { + ancestorsStartingAtParent.push(ancestor); + } + + return ancestorsStartingAtParent.reverse(); + } + + /** + * Determines whether the given identifier node is a reference to a global variable. + * @param {ASTNode} node `Identifier` node to check. + * @returns {boolean} True if the identifier is a reference to a global variable. + */ + isGlobalReference(node) { + if (!node) { + throw new TypeError("Missing required argument: node."); + } + + const cache = this[caches].get("isGlobalReference"); + + if (cache.has(node)) { + return cache.get(node); + } + + if (node.type !== "Identifier") { + cache.set(node, false); + return false; + } + + const variable = this.scopeManager.scopes[0].set.get(node.name); + + if (!variable || variable.defs.length > 0) { + cache.set(node, false); + return false; + } + + const result = variable.references.some( + ({ identifier }) => identifier === node, + ); + cache.set(node, result); + return result; + } + + /** + * Returns the location of the given node or token. + * @param {ASTNode|Token} nodeOrToken The node or token to get the location of. + * @returns {SourceLocation} The location of the node or token. + */ + getLoc(nodeOrToken) { + return nodeOrToken.loc; + } + + /** + * Returns the range of the given node or token. + * @param {ASTNode|Token} nodeOrToken The node or token to get the range of. + * @returns {[number, number]} The range of the node or token. + */ + getRange(nodeOrToken) { + return nodeOrToken.range; + } + + /* eslint-enable class-methods-use-this -- node is owned by SourceCode */ + + /** + * Marks a variable as used in the current scope + * @param {string} name The name of the variable to mark as used. + * @param {ASTNode} [refNode] The closest node to the variable reference. + * @returns {boolean} True if the variable was found and marked as used, false if not. + */ + markVariableAsUsed(name, refNode = this.ast) { + const currentScope = this.getScope(refNode); + let initialScope = currentScope; + + /* + * When we are in an ESM or CommonJS module, we need to start searching + * from the top-level scope, not the global scope. For ESM the top-level + * scope is the module scope; for CommonJS the top-level scope is the + * outer function scope. + * + * Without this check, we might miss a variable declared with `var` at + * the top-level because it won't exist in the global scope. + */ + if ( + currentScope.type === "global" && + currentScope.childScopes.length > 0 && + // top-level scopes refer to a `Program` node + currentScope.childScopes[0].block === this.ast + ) { + initialScope = currentScope.childScopes[0]; + } + + for (let scope = initialScope; scope; scope = scope.upper) { + const variable = scope.variables.find( + scopeVar => scopeVar.name === name, + ); + + if (variable) { + variable.eslintUsed = true; + return true; + } + } + + return false; + } + + /** + * Returns an array of all inline configuration nodes found in the + * source code. + * @returns {Array} An array of all inline configuration nodes. + */ + getInlineConfigNodes() { + // check the cache first + let configNodes = this[caches].get("configNodes"); + + if (configNodes) { + return configNodes; + } + + // calculate fresh config nodes + configNodes = this.ast.comments.filter(comment => { + // shebang comments are never directives + if (comment.type === "Shebang") { + return false; + } + + const directive = commentParser.parseDirective(comment.value); + + if (!directive) { + return false; + } + + if (!directivesPattern.test(directive.label)) { + return false; + } + + // only certain comment types are supported as line comments + return ( + comment.type !== "Line" || + !!/^eslint-disable-(?:next-)?line$/u.test(directive.label) + ); + }); + + this[caches].set("configNodes", configNodes); + + return configNodes; + } + + /** + * Returns an all directive nodes that enable or disable rules along with any problems + * encountered while parsing the directives. + * @returns {{problems:Array,directives:Array}} Information + * that ESLint needs to further process the directives. + */ + getDisableDirectives() { + // check the cache first + const cachedDirectives = this[caches].get("disableDirectives"); + + if (cachedDirectives) { + return cachedDirectives; + } + + const problems = []; + const directives = []; + + this.getInlineConfigNodes().forEach(comment => { + // Step 1: Parse the directive + const { + label, + value, + justification: justificationPart, + } = commentParser.parseDirective(comment.value); + + // Step 2: Extract the directive value + const lineCommentSupported = + /^eslint-disable-(?:next-)?line$/u.test(label); + + if (comment.type === "Line" && !lineCommentSupported) { + return; + } + + // Step 3: Validate the directive does not span multiple lines + if ( + label === "eslint-disable-line" && + comment.loc.start.line !== comment.loc.end.line + ) { + const message = `${label} comment should not span multiple lines.`; + + problems.push({ + ruleId: null, + message, + loc: comment.loc, + }); + return; + } + + // Step 4: Extract the directive value and create the Directive object + switch (label) { + case "eslint-disable": + case "eslint-enable": + case "eslint-disable-next-line": + case "eslint-disable-line": { + const directiveType = label.slice("eslint-".length); + + directives.push( + new Directive({ + type: directiveType, + node: comment, + value, + justification: justificationPart, + }), + ); + } + + // no default + } + }); + + const result = { problems, directives }; + + this[caches].set("disableDirectives", result); + + return result; + } + + /** + * Applies language options sent in from the core. + * @param {Object} languageOptions The language options for this run. + * @returns {void} + */ + applyLanguageOptions(languageOptions) { + /* + * Add configured globals and language globals + * + * Using Object.assign instead of object spread for performance reasons + * https://github.com/eslint/eslint/issues/16302 + */ + const configGlobals = Object.assign( + Object.create(null), // https://github.com/eslint/eslint/issues/18363 + getGlobalsForEcmaVersion(languageOptions.ecmaVersion), + languageOptions.sourceType === "commonjs" + ? globals.commonjs + : void 0, + languageOptions.globals, + ); + const varsCache = this[caches].get("vars"); + + varsCache.set("configGlobals", configGlobals); + } + + /** + * Applies configuration found inside of the source code. This method is only + * called when ESLint is running with inline configuration allowed. + * @returns {{problems:Array,configs:{config:FlatConfigArray,loc:Location}}} Information + * that ESLint needs to further process the inline configuration. + */ + applyInlineConfig() { + const problems = []; + const configs = []; + const exportedVariables = {}; + const inlineGlobals = Object.create(null); + + this.getInlineConfigNodes().forEach(comment => { + const { label, value } = commentParser.parseDirective( + comment.value, + ); + + switch (label) { + case "exported": + Object.assign( + exportedVariables, + commentParser.parseListConfig(value), + ); + break; + + case "globals": + case "global": + for (const [id, idSetting] of Object.entries( + commentParser.parseStringConfig(value), + )) { + let normalizedValue; + + try { + normalizedValue = normalizeConfigGlobal(idSetting); + } catch (err) { + problems.push({ + ruleId: null, + loc: comment.loc, + message: err.message, + }); + continue; + } + + if (inlineGlobals[id]) { + inlineGlobals[id].comments.push(comment); + inlineGlobals[id].value = normalizedValue; + } else { + inlineGlobals[id] = { + comments: [comment], + value: normalizedValue, + }; + } + } + break; + + case "eslint": { + const parseResult = + commentParser.parseJSONLikeConfig(value); + + if (parseResult.ok) { + configs.push({ + config: { + rules: parseResult.config, + }, + loc: comment.loc, + }); + } else { + problems.push({ + ruleId: null, + loc: comment.loc, + message: parseResult.error.message, + }); + } + + break; + } + + // no default + } + }); + + // save all the new variables for later + const varsCache = this[caches].get("vars"); + + varsCache.set("inlineGlobals", inlineGlobals); + varsCache.set("exportedVariables", exportedVariables); + + return { + configs, + problems, + }; + } + + /** + * Called by ESLint core to indicate that it has finished providing + * information. We now add in all the missing variables and ensure that + * state-changing methods cannot be called by rules. + * @returns {void} + */ + finalize() { + const varsCache = this[caches].get("vars"); + const configGlobals = varsCache.get("configGlobals"); + const inlineGlobals = varsCache.get("inlineGlobals"); + const exportedVariables = varsCache.get("exportedVariables"); + const globalScope = this.scopeManager.scopes[0]; + + addDeclaredGlobals(globalScope, configGlobals, inlineGlobals); + + if (exportedVariables) { + markExportedVariables(globalScope, exportedVariables); + } + } + + /** + * Traverse the source code and return the steps that were taken. + * @returns {Array} The steps that were taken while traversing the source code. + */ + traverse() { + // Because the AST doesn't mutate, we can cache the steps + if (this.#steps) { + return this.#steps; + } + + const steps = (this.#steps = []); + + /* + * This logic works for any AST, not just ESTree. Because ESLint has allowed + * custom parsers to return any AST, we need to ensure that the traversal + * logic works for any AST. + */ + let analyzer = { + enterNode(node) { + steps.push( + new VisitNodeStep({ + target: node, + phase: 1, + args: [node], + }), + ); + }, + leaveNode(node) { + steps.push( + new VisitNodeStep({ + target: node, + phase: 2, + args: [node], + }), + ); + }, + emit(eventName, args) { + steps.push( + new CallMethodStep({ + target: eventName, + args, + }), + ); + }, + }; + + /* + * We do code path analysis for ESTree only. Code path analysis is not + * necessary for other ASTs, and it's also not possible to do for other + * ASTs because the necessary information is not available. + * + * Generally speaking, we can tell that the AST is an ESTree if it has a + * Program node at the top level. This is not a perfect heuristic, but it + * is good enough for now. + */ + if (this.isESTree) { + analyzer = new CodePathAnalyzer(analyzer); + } + + /* + * The actual AST traversal is done by the `Traverser` class. This class + * is responsible for walking the AST and calling the appropriate methods + * on the `analyzer` object, which is appropriate for the given AST. + */ + Traverser.traverse(this.ast, { + enter(node, parent) { + // save the parent node on a property for backwards compatibility + node.parent = parent; + + analyzer.enterNode(node); + }, + leave(node) { + analyzer.leaveNode(node); + }, + visitorKeys: this.visitorKeys, + }); + + return steps; + } +} + +module.exports = SourceCode; diff --git a/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/backward-token-comment-cursor.js b/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/backward-token-comment-cursor.js new file mode 100644 index 0000000000000000000000000000000000000000..56f920a47e89a9984ac9080f0179d51cb417395e --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/backward-token-comment-cursor.js @@ -0,0 +1,61 @@ +/** + * @fileoverview Define the cursor which iterates tokens and comments in reverse. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const Cursor = require("./cursor"); +const utils = require("./utils"); + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The cursor which iterates tokens and comments in reverse. + */ +module.exports = class BackwardTokenCommentCursor extends Cursor { + /** + * Initializes this cursor. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @param {Object} indexMap The map from locations to indices in `tokens`. + * @param {number} startLoc The start location of the iteration range. + * @param {number} endLoc The end location of the iteration range. + */ + constructor(tokens, comments, indexMap, startLoc, endLoc) { + super(); + this.tokens = tokens; + this.comments = comments; + this.tokenIndex = utils.getLastIndex(tokens, indexMap, endLoc); + this.commentIndex = utils.search(comments, endLoc) - 1; + this.border = startLoc; + } + + /** @inheritdoc */ + moveNext() { + const token = + this.tokenIndex >= 0 ? this.tokens[this.tokenIndex] : null; + const comment = + this.commentIndex >= 0 ? this.comments[this.commentIndex] : null; + + if (token && (!comment || token.range[1] > comment.range[1])) { + this.current = token; + this.tokenIndex -= 1; + } else if (comment) { + this.current = comment; + this.commentIndex -= 1; + } else { + this.current = null; + } + + return ( + Boolean(this.current) && + (this.border === -1 || this.current.range[0] >= this.border) + ); + } +}; diff --git a/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/backward-token-cursor.js b/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/backward-token-cursor.js new file mode 100644 index 0000000000000000000000000000000000000000..b6b2e120d1fd419011bb289f272062677d88a0b1 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/backward-token-cursor.js @@ -0,0 +1,57 @@ +/** + * @fileoverview Define the cursor which iterates tokens only in reverse. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const Cursor = require("./cursor"); +const { getLastIndex, getFirstIndex } = require("./utils"); + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The cursor which iterates tokens only in reverse. + */ +module.exports = class BackwardTokenCursor extends Cursor { + /** + * Initializes this cursor. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @param {Object} indexMap The map from locations to indices in `tokens`. + * @param {number} startLoc The start location of the iteration range. + * @param {number} endLoc The end location of the iteration range. + */ + constructor(tokens, comments, indexMap, startLoc, endLoc) { + super(); + this.tokens = tokens; + this.index = getLastIndex(tokens, indexMap, endLoc); + this.indexEnd = getFirstIndex(tokens, indexMap, startLoc); + } + + /** @inheritdoc */ + moveNext() { + if (this.index >= this.indexEnd) { + this.current = this.tokens[this.index]; + this.index -= 1; + return true; + } + return false; + } + + /* + * + * Shorthand for performance. + * + */ + + /** @inheritdoc */ + getOneToken() { + return this.index >= this.indexEnd ? this.tokens[this.index] : null; + } +}; diff --git a/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/cursor.js b/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/cursor.js new file mode 100644 index 0000000000000000000000000000000000000000..e640d23fb90a157770f8781a8083376dd75749da --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/cursor.js @@ -0,0 +1,76 @@ +/** + * @fileoverview Define the abstract class about cursors which iterate tokens. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The abstract class about cursors which iterate tokens. + * + * This class has 2 abstract methods. + * + * - `current: Token | Comment | null` ... The current token. + * - `moveNext(): boolean` ... Moves this cursor to the next token. If the next token didn't exist, it returns `false`. + * + * This is similar to ES2015 Iterators. + * However, Iterators were slow (at 2017-01), so I created this class as similar to C# IEnumerable. + * + * There are the following known sub classes. + * + * - ForwardTokenCursor .......... The cursor which iterates tokens only. + * - BackwardTokenCursor ......... The cursor which iterates tokens only in reverse. + * - ForwardTokenCommentCursor ... The cursor which iterates tokens and comments. + * - BackwardTokenCommentCursor .. The cursor which iterates tokens and comments in reverse. + * - DecorativeCursor + * - FilterCursor ............ The cursor which ignores the specified tokens. + * - SkipCursor .............. The cursor which ignores the first few tokens. + * - LimitCursor ............. The cursor which limits the count of tokens. + * + */ +module.exports = class Cursor { + /** + * Initializes this cursor. + */ + constructor() { + this.current = null; + } + + /** + * Gets the first token. + * This consumes this cursor. + * @returns {Token|Comment} The first token or null. + */ + getOneToken() { + return this.moveNext() ? this.current : null; + } + + /** + * Gets the first tokens. + * This consumes this cursor. + * @returns {(Token|Comment)[]} All tokens. + */ + getAllTokens() { + const tokens = []; + + while (this.moveNext()) { + tokens.push(this.current); + } + + return tokens; + } + + /** + * Moves this cursor to the next token. + * @returns {boolean} `true` if the next token exists. + * @abstract + */ + /* c8 ignore next */ + // eslint-disable-next-line class-methods-use-this -- Unused + moveNext() { + throw new Error("Not implemented."); + } +}; diff --git a/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/cursors.js b/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/cursors.js new file mode 100644 index 0000000000000000000000000000000000000000..1e9c084cf65402279b1864b3ec86e2537fc9cae8 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/cursors.js @@ -0,0 +1,120 @@ +/** + * @fileoverview Define 2 token factories; forward and backward. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const BackwardTokenCommentCursor = require("./backward-token-comment-cursor"); +const BackwardTokenCursor = require("./backward-token-cursor"); +const FilterCursor = require("./filter-cursor"); +const ForwardTokenCommentCursor = require("./forward-token-comment-cursor"); +const ForwardTokenCursor = require("./forward-token-cursor"); +const LimitCursor = require("./limit-cursor"); +const SkipCursor = require("./skip-cursor"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * The cursor factory. + * @private + */ +class CursorFactory { + /** + * Initializes this cursor. + * @param {Function} TokenCursor The class of the cursor which iterates tokens only. + * @param {Function} TokenCommentCursor The class of the cursor which iterates the mix of tokens and comments. + */ + constructor(TokenCursor, TokenCommentCursor) { + this.TokenCursor = TokenCursor; + this.TokenCommentCursor = TokenCommentCursor; + } + + /** + * Creates a base cursor instance that can be decorated by createCursor. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @param {Object} indexMap The map from locations to indices in `tokens`. + * @param {number} startLoc The start location of the iteration range. + * @param {number} endLoc The end location of the iteration range. + * @param {boolean} includeComments The flag to iterate comments as well. + * @returns {Cursor} The created base cursor. + */ + createBaseCursor( + tokens, + comments, + indexMap, + startLoc, + endLoc, + includeComments, + ) { + const Cursor = includeComments + ? this.TokenCommentCursor + : this.TokenCursor; + + return new Cursor(tokens, comments, indexMap, startLoc, endLoc); + } + + /** + * Creates a cursor that iterates tokens with normalized options. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @param {Object} indexMap The map from locations to indices in `tokens`. + * @param {number} startLoc The start location of the iteration range. + * @param {number} endLoc The end location of the iteration range. + * @param {boolean} includeComments The flag to iterate comments as well. + * @param {Function|null} filter The predicate function to choose tokens. + * @param {number} skip The count of tokens the cursor skips. + * @param {number} count The maximum count of tokens the cursor iterates. Zero is no iteration for backward compatibility. + * @returns {Cursor} The created cursor. + */ + createCursor( + tokens, + comments, + indexMap, + startLoc, + endLoc, + includeComments, + filter, + skip, + count, + ) { + let cursor = this.createBaseCursor( + tokens, + comments, + indexMap, + startLoc, + endLoc, + includeComments, + ); + + if (filter) { + cursor = new FilterCursor(cursor, filter); + } + if (skip >= 1) { + cursor = new SkipCursor(cursor, skip); + } + if (count >= 0) { + cursor = new LimitCursor(cursor, count); + } + + return cursor; + } +} + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +module.exports = { + forward: new CursorFactory(ForwardTokenCursor, ForwardTokenCommentCursor), + backward: new CursorFactory( + BackwardTokenCursor, + BackwardTokenCommentCursor, + ), +}; diff --git a/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/decorative-cursor.js b/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/decorative-cursor.js new file mode 100644 index 0000000000000000000000000000000000000000..3a1d21ecc0340ea82c3ab6e851dac395b306bb15 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/decorative-cursor.js @@ -0,0 +1,38 @@ +/** + * @fileoverview Define the abstract class about cursors which manipulate another cursor. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const Cursor = require("./cursor"); + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The abstract class about cursors which manipulate another cursor. + */ +module.exports = class DecorativeCursor extends Cursor { + /** + * Initializes this cursor. + * @param {Cursor} cursor The cursor to be decorated. + */ + constructor(cursor) { + super(); + this.cursor = cursor; + } + + /** @inheritdoc */ + moveNext() { + const retv = this.cursor.moveNext(); + + this.current = this.cursor.current; + + return retv; + } +}; diff --git a/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/filter-cursor.js b/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/filter-cursor.js new file mode 100644 index 0000000000000000000000000000000000000000..1e2ec9969a7f1d407bbf3988fc32a86437085260 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/filter-cursor.js @@ -0,0 +1,42 @@ +/** + * @fileoverview Define the cursor which ignores specified tokens. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const DecorativeCursor = require("./decorative-cursor"); + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The decorative cursor which ignores specified tokens. + */ +module.exports = class FilterCursor extends DecorativeCursor { + /** + * Initializes this cursor. + * @param {Cursor} cursor The cursor to be decorated. + * @param {Function} predicate The predicate function to decide tokens this cursor iterates. + */ + constructor(cursor, predicate) { + super(cursor); + this.predicate = predicate; + } + + /** @inheritdoc */ + moveNext() { + const predicate = this.predicate; + + while (super.moveNext()) { + if (predicate(this.current)) { + return true; + } + } + return false; + } +}; diff --git a/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/forward-token-comment-cursor.js b/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/forward-token-comment-cursor.js new file mode 100644 index 0000000000000000000000000000000000000000..d4a1439fe2915b4bef3b9649d603f8eb1e0c7541 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/forward-token-comment-cursor.js @@ -0,0 +1,65 @@ +/** + * @fileoverview Define the cursor which iterates tokens and comments. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const Cursor = require("./cursor"); +const { getFirstIndex, search } = require("./utils"); + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The cursor which iterates tokens and comments. + */ +module.exports = class ForwardTokenCommentCursor extends Cursor { + /** + * Initializes this cursor. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @param {Object} indexMap The map from locations to indices in `tokens`. + * @param {number} startLoc The start location of the iteration range. + * @param {number} endLoc The end location of the iteration range. + */ + constructor(tokens, comments, indexMap, startLoc, endLoc) { + super(); + this.tokens = tokens; + this.comments = comments; + this.tokenIndex = getFirstIndex(tokens, indexMap, startLoc); + this.commentIndex = search(comments, startLoc); + this.border = endLoc; + } + + /** @inheritdoc */ + moveNext() { + const token = + this.tokenIndex < this.tokens.length + ? this.tokens[this.tokenIndex] + : null; + const comment = + this.commentIndex < this.comments.length + ? this.comments[this.commentIndex] + : null; + + if (token && (!comment || token.range[0] < comment.range[0])) { + this.current = token; + this.tokenIndex += 1; + } else if (comment) { + this.current = comment; + this.commentIndex += 1; + } else { + this.current = null; + } + + return ( + Boolean(this.current) && + (this.border === -1 || this.current.range[1] <= this.border) + ); + } +}; diff --git a/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/forward-token-cursor.js b/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/forward-token-cursor.js new file mode 100644 index 0000000000000000000000000000000000000000..5ca2290f1dd53cbe76b8c5d9a6ac095877ff07df --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/forward-token-cursor.js @@ -0,0 +1,62 @@ +/** + * @fileoverview Define the cursor which iterates tokens only. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const Cursor = require("./cursor"); +const { getFirstIndex, getLastIndex } = require("./utils"); + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The cursor which iterates tokens only. + */ +module.exports = class ForwardTokenCursor extends Cursor { + /** + * Initializes this cursor. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @param {Object} indexMap The map from locations to indices in `tokens`. + * @param {number} startLoc The start location of the iteration range. + * @param {number} endLoc The end location of the iteration range. + */ + constructor(tokens, comments, indexMap, startLoc, endLoc) { + super(); + this.tokens = tokens; + this.index = getFirstIndex(tokens, indexMap, startLoc); + this.indexEnd = getLastIndex(tokens, indexMap, endLoc); + } + + /** @inheritdoc */ + moveNext() { + if (this.index <= this.indexEnd) { + this.current = this.tokens[this.index]; + this.index += 1; + return true; + } + return false; + } + + /* + * + * Shorthand for performance. + * + */ + + /** @inheritdoc */ + getOneToken() { + return this.index <= this.indexEnd ? this.tokens[this.index] : null; + } + + /** @inheritdoc */ + getAllTokens() { + return this.tokens.slice(this.index, this.indexEnd + 1); + } +}; diff --git a/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/index.js b/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/index.js new file mode 100644 index 0000000000000000000000000000000000000000..120438a9d9e42958a0b089dee7ee71001058a01f --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/index.js @@ -0,0 +1,721 @@ +/** + * @fileoverview Object to handle access and retrieval of tokens. + * @author Brandon Mills + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { isCommentToken } = require("@eslint-community/eslint-utils"); +const assert = require("../../../../shared/assert"); +const cursors = require("./cursors"); +const ForwardTokenCursor = require("./forward-token-cursor"); +const PaddedTokenCursor = require("./padded-token-cursor"); +const utils = require("./utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const TOKENS = Symbol("tokens"); +const COMMENTS = Symbol("comments"); +const INDEX_MAP = Symbol("indexMap"); + +/** + * Creates the map from locations to indices in `tokens`. + * + * The first/last location of tokens is mapped to the index of the token. + * The first/last location of comments is mapped to the index of the next token of each comment. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @returns {Object} The map from locations to indices in `tokens`. + * @private + */ +function createIndexMap(tokens, comments) { + const map = Object.create(null); + let tokenIndex = 0; + let commentIndex = 0; + let nextStart; + let range; + + while (tokenIndex < tokens.length || commentIndex < comments.length) { + nextStart = + commentIndex < comments.length + ? comments[commentIndex].range[0] + : Number.MAX_SAFE_INTEGER; + while ( + tokenIndex < tokens.length && + (range = tokens[tokenIndex].range)[0] < nextStart + ) { + map[range[0]] = tokenIndex; + map[range[1] - 1] = tokenIndex; + tokenIndex += 1; + } + + nextStart = + tokenIndex < tokens.length + ? tokens[tokenIndex].range[0] + : Number.MAX_SAFE_INTEGER; + while ( + commentIndex < comments.length && + (range = comments[commentIndex].range)[0] < nextStart + ) { + map[range[0]] = tokenIndex; + map[range[1] - 1] = tokenIndex; + commentIndex += 1; + } + } + + return map; +} + +/** + * Creates the cursor iterates tokens with options. + * @param {CursorFactory} factory The cursor factory to initialize cursor. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @param {Object} indexMap The map from locations to indices in `tokens`. + * @param {number} startLoc The start location of the iteration range. + * @param {number} endLoc The end location of the iteration range. + * @param {number|Function|Object} [opts=0] The option object. If this is a number then it's `opts.skip`. If this is a function then it's `opts.filter`. + * @param {boolean} [opts.includeComments=false] The flag to iterate comments as well. + * @param {Function|null} [opts.filter=null] The predicate function to choose tokens. + * @param {number} [opts.skip=0] The count of tokens the cursor skips. + * @returns {Cursor} The created cursor. + * @private + */ +function createCursorWithSkip( + factory, + tokens, + comments, + indexMap, + startLoc, + endLoc, + opts, +) { + let includeComments = false; + let skip = 0; + let filter = null; + + if (typeof opts === "number") { + skip = opts | 0; + } else if (typeof opts === "function") { + filter = opts; + } else if (opts) { + includeComments = !!opts.includeComments; + skip = opts.skip | 0; + filter = opts.filter || null; + } + assert(skip >= 0, "options.skip should be zero or a positive integer."); + assert( + !filter || typeof filter === "function", + "options.filter should be a function.", + ); + + return factory.createCursor( + tokens, + comments, + indexMap, + startLoc, + endLoc, + includeComments, + filter, + skip, + -1, + ); +} + +/** + * Creates the cursor iterates tokens with options. + * @param {CursorFactory} factory The cursor factory to initialize cursor. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @param {Object} indexMap The map from locations to indices in `tokens`. + * @param {number} startLoc The start location of the iteration range. + * @param {number} endLoc The end location of the iteration range. + * @param {number|Function|Object} [opts=0] The option object. If this is a number then it's `opts.count`. If this is a function then it's `opts.filter`. + * @param {boolean} [opts.includeComments] The flag to iterate comments as well. + * @param {Function|null} [opts.filter=null] The predicate function to choose tokens. + * @param {number} [opts.count=0] The maximum count of tokens the cursor iterates. Zero is no iteration for backward compatibility. + * @returns {Cursor} The created cursor. + * @private + */ +function createCursorWithCount( + factory, + tokens, + comments, + indexMap, + startLoc, + endLoc, + opts, +) { + let includeComments = false; + let count = 0; + let countExists = false; + let filter = null; + + if (typeof opts === "number") { + count = opts | 0; + countExists = true; + } else if (typeof opts === "function") { + filter = opts; + } else if (opts) { + includeComments = !!opts.includeComments; + count = opts.count | 0; + countExists = typeof opts.count === "number"; + filter = opts.filter || null; + } + assert(count >= 0, "options.count should be zero or a positive integer."); + assert( + !filter || typeof filter === "function", + "options.filter should be a function.", + ); + + return factory.createCursor( + tokens, + comments, + indexMap, + startLoc, + endLoc, + includeComments, + filter, + 0, + countExists ? count : -1, + ); +} + +/** + * Creates the cursor iterates tokens with options. + * This is overload function of the below. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @param {Object} indexMap The map from locations to indices in `tokens`. + * @param {number} startLoc The start location of the iteration range. + * @param {number} endLoc The end location of the iteration range. + * @param {Function|Object} opts The option object. If this is a function then it's `opts.filter`. + * @param {boolean} [opts.includeComments] The flag to iterate comments as well. + * @param {Function|null} [opts.filter=null] The predicate function to choose tokens. + * @param {number} [opts.count=0] The maximum count of tokens the cursor iterates. Zero is no iteration for backward compatibility. + * @returns {Cursor} The created cursor. + * @private + */ +/** + * Creates the cursor iterates tokens with options. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @param {Object} indexMap The map from locations to indices in `tokens`. + * @param {number} startLoc The start location of the iteration range. + * @param {number} endLoc The end location of the iteration range. + * @param {number} [beforeCount=0] The number of tokens before the node to retrieve. + * @param {boolean} [afterCount=0] The number of tokens after the node to retrieve. + * @returns {Cursor} The created cursor. + * @private + */ +function createCursorWithPadding( + tokens, + comments, + indexMap, + startLoc, + endLoc, + beforeCount, + afterCount, +) { + if ( + typeof beforeCount === "undefined" && + typeof afterCount === "undefined" + ) { + return new ForwardTokenCursor( + tokens, + comments, + indexMap, + startLoc, + endLoc, + ); + } + if (typeof beforeCount === "number" || typeof beforeCount === "undefined") { + return new PaddedTokenCursor( + tokens, + comments, + indexMap, + startLoc, + endLoc, + beforeCount | 0, + afterCount | 0, + ); + } + return createCursorWithCount( + cursors.forward, + tokens, + comments, + indexMap, + startLoc, + endLoc, + beforeCount, + ); +} + +/** + * Gets comment tokens that are adjacent to the current cursor position. + * @param {Cursor} cursor A cursor instance. + * @returns {Array} An array of comment tokens adjacent to the current cursor position. + * @private + */ +function getAdjacentCommentTokensFromCursor(cursor) { + const tokens = []; + let currentToken = cursor.getOneToken(); + + while (currentToken && isCommentToken(currentToken)) { + tokens.push(currentToken); + currentToken = cursor.getOneToken(); + } + + return tokens; +} + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The token store. + * + * This class provides methods to get tokens by locations as fast as possible. + * The methods are a part of public API, so we should be careful if it changes this class. + * + * People can get tokens in O(1) by the hash map which is mapping from the location of tokens/comments to tokens. + * Also people can get a mix of tokens and comments in O(log k), the k is the number of comments. + * Assuming that comments to be much fewer than tokens, this does not make hash map from token's locations to comments to reduce memory cost. + * This uses binary-searching instead for comments. + */ +module.exports = class TokenStore { + /** + * Initializes this token store. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + */ + constructor(tokens, comments) { + this[TOKENS] = tokens; + this[COMMENTS] = comments; + this[INDEX_MAP] = createIndexMap(tokens, comments); + } + + //-------------------------------------------------------------------------- + // Gets single token. + //-------------------------------------------------------------------------- + + /** + * Gets the token starting at the specified index. + * @param {number} offset Index of the start of the token's range. + * @param {Object} [options=0] The option object. + * @param {boolean} [options.includeComments=false] The flag to iterate comments as well. + * @returns {Token|null} The token starting at index, or null if no such token. + */ + getTokenByRangeStart(offset, options) { + const includeComments = options && options.includeComments; + const token = cursors.forward + .createBaseCursor( + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + offset, + -1, + includeComments, + ) + .getOneToken(); + + if (token && token.range[0] === offset) { + return token; + } + return null; + } + + /** + * Gets the first token of the given node. + * @param {ASTNode} node The AST node. + * @param {number|Function|Object} [options=0] The option object. If this is a number then it's `options.skip`. If this is a function then it's `options.filter`. + * @param {boolean} [options.includeComments=false] The flag to iterate comments as well. + * @param {Function|null} [options.filter=null] The predicate function to choose tokens. + * @param {number} [options.skip=0] The count of tokens the cursor skips. + * @returns {Token|null} An object representing the token. + */ + getFirstToken(node, options) { + return createCursorWithSkip( + cursors.forward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + node.range[0], + node.range[1], + options, + ).getOneToken(); + } + + /** + * Gets the last token of the given node. + * @param {ASTNode} node The AST node. + * @param {number|Function|Object} [options=0] The option object. Same options as getFirstToken() + * @returns {Token|null} An object representing the token. + */ + getLastToken(node, options) { + return createCursorWithSkip( + cursors.backward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + node.range[0], + node.range[1], + options, + ).getOneToken(); + } + + /** + * Gets the token that precedes a given node or token. + * @param {ASTNode|Token|Comment} node The AST node or token. + * @param {number|Function|Object} [options=0] The option object. Same options as getFirstToken() + * @returns {Token|null} An object representing the token. + */ + getTokenBefore(node, options) { + return createCursorWithSkip( + cursors.backward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + -1, + node.range[0], + options, + ).getOneToken(); + } + + /** + * Gets the token that follows a given node or token. + * @param {ASTNode|Token|Comment} node The AST node or token. + * @param {number|Function|Object} [options=0] The option object. Same options as getFirstToken() + * @returns {Token|null} An object representing the token. + */ + getTokenAfter(node, options) { + return createCursorWithSkip( + cursors.forward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + node.range[1], + -1, + options, + ).getOneToken(); + } + + /** + * Gets the first token between two non-overlapping nodes. + * @param {ASTNode|Token|Comment} left Node before the desired token range. + * @param {ASTNode|Token|Comment} right Node after the desired token range. + * @param {number|Function|Object} [options=0] The option object. Same options as getFirstToken() + * @returns {Token|null} An object representing the token. + */ + getFirstTokenBetween(left, right, options) { + return createCursorWithSkip( + cursors.forward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + left.range[1], + right.range[0], + options, + ).getOneToken(); + } + + /** + * Gets the last token between two non-overlapping nodes. + * @param {ASTNode|Token|Comment} left Node before the desired token range. + * @param {ASTNode|Token|Comment} right Node after the desired token range. + * @param {number|Function|Object} [options=0] The option object. Same options as getFirstToken() + * @returns {Token|null} An object representing the token. + */ + getLastTokenBetween(left, right, options) { + return createCursorWithSkip( + cursors.backward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + left.range[1], + right.range[0], + options, + ).getOneToken(); + } + + /** + * Gets the token that precedes a given node or token in the token stream. + * This is defined for backward compatibility. Use `includeComments` option instead. + * TODO: We have a plan to remove this in a future major version. + * @param {ASTNode|Token|Comment} node The AST node or token. + * @param {number} [skip=0] A number of tokens to skip. + * @returns {Token|null} An object representing the token. + * @deprecated + */ + getTokenOrCommentBefore(node, skip) { + return this.getTokenBefore(node, { includeComments: true, skip }); + } + + /** + * Gets the token that follows a given node or token in the token stream. + * This is defined for backward compatibility. Use `includeComments` option instead. + * TODO: We have a plan to remove this in a future major version. + * @param {ASTNode|Token|Comment} node The AST node or token. + * @param {number} [skip=0] A number of tokens to skip. + * @returns {Token|null} An object representing the token. + * @deprecated + */ + getTokenOrCommentAfter(node, skip) { + return this.getTokenAfter(node, { includeComments: true, skip }); + } + + //-------------------------------------------------------------------------- + // Gets multiple tokens. + //-------------------------------------------------------------------------- + + /** + * Gets the first `count` tokens of the given node. + * @param {ASTNode} node The AST node. + * @param {number|Function|Object} [options=0] The option object. If this is a number then it's `options.count`. If this is a function then it's `options.filter`. + * @param {boolean} [options.includeComments=false] The flag to iterate comments as well. + * @param {Function|null} [options.filter=null] The predicate function to choose tokens. + * @param {number} [options.count=0] The maximum count of tokens the cursor iterates. + * @returns {Token[]} Tokens. + */ + getFirstTokens(node, options) { + return createCursorWithCount( + cursors.forward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + node.range[0], + node.range[1], + options, + ).getAllTokens(); + } + + /** + * Gets the last `count` tokens of the given node. + * @param {ASTNode} node The AST node. + * @param {number|Function|Object} [options=0] The option object. Same options as getFirstTokens() + * @returns {Token[]} Tokens. + */ + getLastTokens(node, options) { + return createCursorWithCount( + cursors.backward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + node.range[0], + node.range[1], + options, + ) + .getAllTokens() + .reverse(); + } + + /** + * Gets the `count` tokens that precedes a given node or token. + * @param {ASTNode|Token|Comment} node The AST node or token. + * @param {number|Function|Object} [options=0] The option object. Same options as getFirstTokens() + * @returns {Token[]} Tokens. + */ + getTokensBefore(node, options) { + return createCursorWithCount( + cursors.backward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + -1, + node.range[0], + options, + ) + .getAllTokens() + .reverse(); + } + + /** + * Gets the `count` tokens that follows a given node or token. + * @param {ASTNode|Token|Comment} node The AST node or token. + * @param {number|Function|Object} [options=0] The option object. Same options as getFirstTokens() + * @returns {Token[]} Tokens. + */ + getTokensAfter(node, options) { + return createCursorWithCount( + cursors.forward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + node.range[1], + -1, + options, + ).getAllTokens(); + } + + /** + * Gets the first `count` tokens between two non-overlapping nodes. + * @param {ASTNode|Token|Comment} left Node before the desired token range. + * @param {ASTNode|Token|Comment} right Node after the desired token range. + * @param {number|Function|Object} [options=0] The option object. Same options as getFirstTokens() + * @returns {Token[]} Tokens between left and right. + */ + getFirstTokensBetween(left, right, options) { + return createCursorWithCount( + cursors.forward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + left.range[1], + right.range[0], + options, + ).getAllTokens(); + } + + /** + * Gets the last `count` tokens between two non-overlapping nodes. + * @param {ASTNode|Token|Comment} left Node before the desired token range. + * @param {ASTNode|Token|Comment} right Node after the desired token range. + * @param {number|Function|Object} [options=0] The option object. Same options as getFirstTokens() + * @returns {Token[]} Tokens between left and right. + */ + getLastTokensBetween(left, right, options) { + return createCursorWithCount( + cursors.backward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + left.range[1], + right.range[0], + options, + ) + .getAllTokens() + .reverse(); + } + + /** + * Gets all tokens that are related to the given node. + * @param {ASTNode} node The AST node. + * @param {Function|Object} options The option object. If this is a function then it's `options.filter`. + * @param {boolean} [options.includeComments=false] The flag to iterate comments as well. + * @param {Function|null} [options.filter=null] The predicate function to choose tokens. + * @param {number} [options.count=0] The maximum count of tokens the cursor iterates. + * @returns {Token[]} Array of objects representing tokens. + */ + /** + * Gets all tokens that are related to the given node. + * @param {ASTNode} node The AST node. + * @param {number} [beforeCount=0] The number of tokens before the node to retrieve. + * @param {number} [afterCount=0] The number of tokens after the node to retrieve. + * @returns {Token[]} Array of objects representing tokens. + */ + getTokens(node, beforeCount, afterCount) { + return createCursorWithPadding( + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + node.range[0], + node.range[1], + beforeCount, + afterCount, + ).getAllTokens(); + } + + /** + * Gets all of the tokens between two non-overlapping nodes. + * @param {ASTNode|Token|Comment} left Node before the desired token range. + * @param {ASTNode|Token|Comment} right Node after the desired token range. + * @param {Function|Object} options The option object. If this is a function then it's `options.filter`. + * @param {boolean} [options.includeComments=false] The flag to iterate comments as well. + * @param {Function|null} [options.filter=null] The predicate function to choose tokens. + * @param {number} [options.count=0] The maximum count of tokens the cursor iterates. + * @returns {Token[]} Tokens between left and right. + */ + /** + * Gets all of the tokens between two non-overlapping nodes. + * @param {ASTNode|Token|Comment} left Node before the desired token range. + * @param {ASTNode|Token|Comment} right Node after the desired token range. + * @param {number} [padding=0] Number of extra tokens on either side of center. + * @returns {Token[]} Tokens between left and right. + */ + getTokensBetween(left, right, padding) { + return createCursorWithPadding( + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + left.range[1], + right.range[0], + padding, + padding, + ).getAllTokens(); + } + + //-------------------------------------------------------------------------- + // Others. + //-------------------------------------------------------------------------- + + /** + * Checks whether any comments exist or not between the given 2 nodes. + * @param {ASTNode} left The node to check. + * @param {ASTNode} right The node to check. + * @returns {boolean} `true` if one or more comments exist. + */ + commentsExistBetween(left, right) { + const index = utils.search(this[COMMENTS], left.range[1]); + + return ( + index < this[COMMENTS].length && + this[COMMENTS][index].range[1] <= right.range[0] + ); + } + + /** + * Gets all comment tokens directly before the given node or token. + * @param {ASTNode|token} nodeOrToken The AST node or token to check for adjacent comment tokens. + * @returns {Array} An array of comments in occurrence order. + */ + getCommentsBefore(nodeOrToken) { + const cursor = createCursorWithCount( + cursors.backward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + -1, + nodeOrToken.range[0], + { includeComments: true }, + ); + + return getAdjacentCommentTokensFromCursor(cursor).reverse(); + } + + /** + * Gets all comment tokens directly after the given node or token. + * @param {ASTNode|token} nodeOrToken The AST node or token to check for adjacent comment tokens. + * @returns {Array} An array of comments in occurrence order. + */ + getCommentsAfter(nodeOrToken) { + const cursor = createCursorWithCount( + cursors.forward, + this[TOKENS], + this[COMMENTS], + this[INDEX_MAP], + nodeOrToken.range[1], + -1, + { includeComments: true }, + ); + + return getAdjacentCommentTokensFromCursor(cursor); + } + + /** + * Gets all comment tokens inside the given node. + * @param {ASTNode} node The AST node to get the comments for. + * @returns {Array} An array of comments in occurrence order. + */ + getCommentsInside(node) { + return this.getTokens(node, { + includeComments: true, + filter: isCommentToken, + }); + } +}; diff --git a/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/limit-cursor.js b/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/limit-cursor.js new file mode 100644 index 0000000000000000000000000000000000000000..301d7f54c91133bdc322e2497a99be1cdf1a3735 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/limit-cursor.js @@ -0,0 +1,39 @@ +/** + * @fileoverview Define the cursor which limits the number of tokens. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const DecorativeCursor = require("./decorative-cursor"); + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The decorative cursor which limits the number of tokens. + */ +module.exports = class LimitCursor extends DecorativeCursor { + /** + * Initializes this cursor. + * @param {Cursor} cursor The cursor to be decorated. + * @param {number} count The count of tokens this cursor iterates. + */ + constructor(cursor, count) { + super(cursor); + this.count = count; + } + + /** @inheritdoc */ + moveNext() { + if (this.count > 0) { + this.count -= 1; + return super.moveNext(); + } + return false; + } +}; diff --git a/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/padded-token-cursor.js b/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/padded-token-cursor.js new file mode 100644 index 0000000000000000000000000000000000000000..3d3ce04f1ce8eb7a275d5b403736fb11fdf5db5c --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/padded-token-cursor.js @@ -0,0 +1,45 @@ +/** + * @fileoverview Define the cursor which iterates tokens only, with inflated range. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const ForwardTokenCursor = require("./forward-token-cursor"); + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The cursor which iterates tokens only, with inflated range. + * This is for the backward compatibility of padding options. + */ +module.exports = class PaddedTokenCursor extends ForwardTokenCursor { + /** + * Initializes this cursor. + * @param {Token[]} tokens The array of tokens. + * @param {Comment[]} comments The array of comments. + * @param {Object} indexMap The map from locations to indices in `tokens`. + * @param {number} startLoc The start location of the iteration range. + * @param {number} endLoc The end location of the iteration range. + * @param {number} beforeCount The number of tokens this cursor iterates before start. + * @param {number} afterCount The number of tokens this cursor iterates after end. + */ + constructor( + tokens, + comments, + indexMap, + startLoc, + endLoc, + beforeCount, + afterCount, + ) { + super(tokens, comments, indexMap, startLoc, endLoc); + this.index = Math.max(0, this.index - beforeCount); + this.indexEnd = Math.min(tokens.length - 1, this.indexEnd + afterCount); + } +}; diff --git a/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/skip-cursor.js b/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/skip-cursor.js new file mode 100644 index 0000000000000000000000000000000000000000..6bc43d85604f169c056a695c9a72b7d6cd5b8058 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/skip-cursor.js @@ -0,0 +1,41 @@ +/** + * @fileoverview Define the cursor which ignores the first few tokens. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const DecorativeCursor = require("./decorative-cursor"); + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The decorative cursor which ignores the first few tokens. + */ +module.exports = class SkipCursor extends DecorativeCursor { + /** + * Initializes this cursor. + * @param {Cursor} cursor The cursor to be decorated. + * @param {number} count The count of tokens this cursor skips. + */ + constructor(cursor, count) { + super(cursor); + this.count = count; + } + + /** @inheritdoc */ + moveNext() { + while (this.count > 0) { + this.count -= 1; + if (!super.moveNext()) { + return false; + } + } + return super.moveNext(); + } +}; diff --git a/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/utils.js b/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..94e456c9f36d735f130264a29114c92103d9a93d --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/languages/js/source-code/token-store/utils.js @@ -0,0 +1,110 @@ +/** + * @fileoverview Define utility functions for token store. + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * Finds the index of the first token which is after the given location. + * If it was not found, this returns `tokens.length`. + * @param {(Token|Comment)[]} tokens It searches the token in this list. + * @param {number} location The location to search. + * @returns {number} The found index or `tokens.length`. + */ +exports.search = function search(tokens, location) { + for ( + let minIndex = 0, maxIndex = tokens.length - 1; + minIndex <= maxIndex; + + ) { + /* + * Calculate the index in the middle between minIndex and maxIndex. + * `| 0` is used to round a fractional value down to the nearest integer: this is similar to + * using `Math.trunc()` or `Math.floor()`, but performance tests have shown this method to + * be faster. + */ + const index = ((minIndex + maxIndex) / 2) | 0; + const token = tokens[index]; + const tokenStartLocation = token.range[0]; + + if (location <= tokenStartLocation) { + if (index === minIndex) { + return index; + } + maxIndex = index; + } else { + minIndex = index + 1; + } + } + return tokens.length; +}; + +/** + * Gets the index of the `startLoc` in `tokens`. + * `startLoc` can be the value of `node.range[1]`, so this checks about `startLoc - 1` as well. + * @param {(Token|Comment)[]} tokens The tokens to find an index. + * @param {Object} indexMap The map from locations to indices. + * @param {number} startLoc The location to get an index. + * @returns {number} The index. + */ +exports.getFirstIndex = function getFirstIndex(tokens, indexMap, startLoc) { + if (startLoc in indexMap) { + return indexMap[startLoc]; + } + if (startLoc - 1 in indexMap) { + const index = indexMap[startLoc - 1]; + const token = tokens[index]; + + // If the mapped index is out of bounds, the returned cursor index will point after the end of the tokens array. + if (!token) { + return tokens.length; + } + + /* + * For the map of "comment's location -> token's index", it points the next token of a comment. + * In that case, +1 is unnecessary. + */ + if (token.range[0] >= startLoc) { + return index; + } + return index + 1; + } + return 0; +}; + +/** + * Gets the index of the `endLoc` in `tokens`. + * The information of end locations are recorded at `endLoc - 1` in `indexMap`, so this checks about `endLoc - 1` as well. + * @param {(Token|Comment)[]} tokens The tokens to find an index. + * @param {Object} indexMap The map from locations to indices. + * @param {number} endLoc The location to get an index. + * @returns {number} The index. + */ +exports.getLastIndex = function getLastIndex(tokens, indexMap, endLoc) { + if (endLoc in indexMap) { + return indexMap[endLoc] - 1; + } + if (endLoc - 1 in indexMap) { + const index = indexMap[endLoc - 1]; + const token = tokens[index]; + + // If the mapped index is out of bounds, the returned cursor index will point before the end of the tokens array. + if (!token) { + return tokens.length - 1; + } + + /* + * For the map of "comment's location -> token's index", it points the next token of a comment. + * In that case, -1 is necessary. + */ + if (token.range[1] > endLoc) { + return index - 1; + } + return index; + } + return tokens.length - 1; +}; diff --git a/tools/ui/node_modules/eslint/lib/languages/js/validate-language-options.js b/tools/ui/node_modules/eslint/lib/languages/js/validate-language-options.js new file mode 100644 index 0000000000000000000000000000000000000000..23ed266642aee31c64914de237e3f4f87611a1e9 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/languages/js/validate-language-options.js @@ -0,0 +1,196 @@ +/** + * @fileoverview The schema to validate language options + * @author Nicholas C. Zakas + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Data +//----------------------------------------------------------------------------- + +const globalVariablesValues = new Set([ + true, + "true", + "writable", + "writeable", + false, + "false", + "readonly", + "readable", + null, + "off", +]); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Check if a value is a non-null object. + * @param {any} value The value to check. + * @returns {boolean} `true` if the value is a non-null object. + */ +function isNonNullObject(value) { + return typeof value === "object" && value !== null; +} + +/** + * Check if a value is a non-null non-array object. + * @param {any} value The value to check. + * @returns {boolean} `true` if the value is a non-null non-array object. + */ +function isNonArrayObject(value) { + return isNonNullObject(value) && !Array.isArray(value); +} + +/** + * Check if a value is undefined. + * @param {any} value The value to check. + * @returns {boolean} `true` if the value is undefined. + */ +function isUndefined(value) { + return typeof value === "undefined"; +} + +//----------------------------------------------------------------------------- +// Schemas +//----------------------------------------------------------------------------- + +/** + * Validates the ecmaVersion property. + * @param {string|number} ecmaVersion The value to check. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ +function validateEcmaVersion(ecmaVersion) { + if (isUndefined(ecmaVersion)) { + throw new TypeError( + 'Key "ecmaVersion": Expected an "ecmaVersion" property.', + ); + } + + if (typeof ecmaVersion !== "number" && ecmaVersion !== "latest") { + throw new TypeError( + 'Key "ecmaVersion": Expected a number or "latest".', + ); + } +} + +/** + * Validates the sourceType property. + * @param {string} sourceType The value to check. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ +function validateSourceType(sourceType) { + if ( + typeof sourceType !== "string" || + !/^(?:script|module|commonjs)$/u.test(sourceType) + ) { + throw new TypeError( + 'Key "sourceType": Expected "script", "module", or "commonjs".', + ); + } +} + +/** + * Validates the globals property. + * @param {Object} globals The value to check. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ +function validateGlobals(globals) { + if (!isNonArrayObject(globals)) { + throw new TypeError('Key "globals": Expected an object.'); + } + + for (const key of Object.keys(globals)) { + // avoid hairy edge case + if (key === "__proto__") { + continue; + } + + if (key !== key.trim()) { + throw new TypeError( + `Key "globals": Global "${key}" has leading or trailing whitespace.`, + ); + } + + if (!globalVariablesValues.has(globals[key])) { + throw new TypeError( + `Key "globals": Key "${key}": Expected "readonly", "writable", or "off".`, + ); + } + } +} + +/** + * Validates the parser property. + * @param {Object} parser The value to check. + * @returns {void} + * @throws {TypeError} If the value is invalid. + */ +function validateParser(parser) { + if ( + !parser || + typeof parser !== "object" || + (typeof parser.parse !== "function" && + typeof parser.parseForESLint !== "function") + ) { + throw new TypeError( + 'Key "parser": Expected object with parse() or parseForESLint() method.', + ); + } +} + +/** + * Validates the language options. + * @param {Object} languageOptions The language options to validate. + * @returns {void} + * @throws {TypeError} If the language options are invalid. + */ +function validateLanguageOptions(languageOptions) { + if (!isNonArrayObject(languageOptions)) { + throw new TypeError("Expected an object."); + } + + const { + ecmaVersion, + sourceType, + globals, + parser, + parserOptions, + ...otherOptions + } = languageOptions; + + if ("ecmaVersion" in languageOptions) { + validateEcmaVersion(ecmaVersion); + } + + if ("sourceType" in languageOptions) { + validateSourceType(sourceType); + } + + if ("globals" in languageOptions) { + validateGlobals(globals); + } + + if ("parser" in languageOptions) { + validateParser(parser); + } + + if ("parserOptions" in languageOptions) { + if (!isNonArrayObject(parserOptions)) { + throw new TypeError('Key "parserOptions": Expected an object.'); + } + } + + const otherOptionKeys = Object.keys(otherOptions); + + if (otherOptionKeys.length > 0) { + throw new TypeError(`Unexpected key "${otherOptionKeys[0]}" found.`); + } +} + +module.exports = { validateLanguageOptions }; diff --git a/tools/ui/node_modules/eslint/lib/linter/apply-disable-directives.js b/tools/ui/node_modules/eslint/lib/linter/apply-disable-directives.js new file mode 100644 index 0000000000000000000000000000000000000000..529be9e73764241fe17dfd8716f2666a2ca36a0c --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/linter/apply-disable-directives.js @@ -0,0 +1,584 @@ +/** + * @fileoverview A module that filters reported problems based on `eslint-disable` and `eslint-enable` comments + * @author Teddy Katz + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** @typedef {import("../types").Linter.LintMessage} LintMessage */ +/** @typedef {import("@eslint/core").Language} Language */ +/** @typedef {import("@eslint/core").Position} Position */ +/** @typedef {import("@eslint/core").RulesConfig} RulesConfig */ + +//------------------------------------------------------------------------------ +// Module Definition +//------------------------------------------------------------------------------ + +const escapeRegExp = require("escape-string-regexp"); +const { Config } = require("../config/config.js"); + +/** + * Compares the locations of two objects in a source file + * @param {Position} itemA The first object + * @param {Position} itemB The second object + * @returns {number} A value less than 1 if itemA appears before itemB in the source file, greater than 1 if + * itemA appears after itemB in the source file, or 0 if itemA and itemB have the same location. + */ +function compareLocations(itemA, itemB) { + return itemA.line - itemB.line || itemA.column - itemB.column; +} + +/** + * Groups a set of directives into sub-arrays by their parent comment. + * @param {Iterable} directives Unused directives to be removed. + * @returns {Directive[][]} Directives grouped by their parent comment. + */ +function groupByParentDirective(directives) { + const groups = new Map(); + + for (const directive of directives) { + const { + unprocessedDirective: { parentDirective }, + } = directive; + + if (groups.has(parentDirective)) { + groups.get(parentDirective).push(directive); + } else { + groups.set(parentDirective, [directive]); + } + } + + return [...groups.values()]; +} + +/** + * Creates removal details for a set of directives within the same comment. + * @param {Directive[]} directives Unused directives to be removed. + * @param {{node: Token, value: string}} parentDirective Data about the backing directive. + * @param {SourceCode} sourceCode The source code object for the file being linted. + * @returns {{ description, fix, unprocessedDirective }[]} Details for later creation of output Problems. + */ +function createIndividualDirectivesRemoval( + directives, + parentDirective, + sourceCode, +) { + /* + * Get the list of the rules text without any surrounding whitespace. In order to preserve the original + * formatting, we don't want to change that whitespace. + * + * // eslint-disable-line rule-one , rule-two , rule-three -- comment + * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + */ + const listText = parentDirective.value.trim(); + + // Calculate where it starts in the source code text + const listStart = sourceCode.text.indexOf( + listText, + sourceCode.getRange(parentDirective.node)[0], + ); + + /* + * We can assume that `listText` contains multiple elements. + * Otherwise, this function wouldn't be called - if there is + * only one rule in the list, then the whole comment must be removed. + */ + + return directives.map(directive => { + const { ruleId } = directive; + + const regex = new RegExp( + String.raw`(?:^|\s*,\s*)(?['"]?)${escapeRegExp(ruleId)}\k(?:\s*,\s*|$)`, + "u", + ); + const match = regex.exec(listText); + const matchedText = match[0]; + const matchStart = listStart + match.index; + const matchEnd = matchStart + matchedText.length; + + const firstIndexOfComma = matchedText.indexOf(","); + const lastIndexOfComma = matchedText.lastIndexOf(","); + + let removalStart, removalEnd; + + if (firstIndexOfComma !== lastIndexOfComma) { + /* + * Since there are two commas, this must one of the elements in the middle of the list. + * Matched range starts where the previous rule name ends, and ends where the next rule name starts. + * + * // eslint-disable-line rule-one , rule-two , rule-three -- comment + * ^^^^^^^^^^^^^^ + * + * We want to remove only the content between the two commas, and also one of the commas. + * + * // eslint-disable-line rule-one , rule-two , rule-three -- comment + * ^^^^^^^^^^^ + */ + removalStart = matchStart + firstIndexOfComma; + removalEnd = matchStart + lastIndexOfComma; + } else { + /* + * This is either the first element or the last element. + * + * If this is the first element, matched range starts where the first rule name starts + * and ends where the second rule name starts. This is exactly the range we want + * to remove so that the second rule name will start where the first one was starting + * and thus preserve the original formatting. + * + * // eslint-disable-line rule-one , rule-two , rule-three -- comment + * ^^^^^^^^^^^ + * + * Similarly, if this is the last element, we've already matched the range we want to + * remove. The previous rule name will end where the last one was ending, relative + * to the content on the right side. + * + * // eslint-disable-line rule-one , rule-two , rule-three -- comment + * ^^^^^^^^^^^^^ + */ + removalStart = matchStart; + removalEnd = matchEnd; + } + + return { + description: `'${ruleId}'`, + fix: { + range: [removalStart, removalEnd], + text: "", + }, + unprocessedDirective: directive.unprocessedDirective, + }; + }); +} + +/** + * Creates a description of deleting an entire unused disable directive. + * @param {Directive[]} directives Unused directives to be removed. + * @param {Token} node The backing Comment token. + * @param {SourceCode} sourceCode The source code object for the file being linted. + * @returns {{ description, fix, unprocessedDirective }} Details for later creation of an output problem. + */ +function createDirectiveRemoval(directives, node, sourceCode) { + const range = sourceCode.getRange(node); + const ruleIds = directives + .filter(directive => directive.ruleId) + .map(directive => `'${directive.ruleId}'`); + + return { + description: + ruleIds.length <= 2 + ? ruleIds.join(" or ") + : `${ruleIds.slice(0, ruleIds.length - 1).join(", ")}, or ${ruleIds.at(-1)}`, + fix: { + range, + text: " ", + }, + unprocessedDirective: directives[0].unprocessedDirective, + }; +} + +/** + * Parses details from directives to create output Problems. + * @param {Iterable} allDirectives Unused directives to be removed. + * @param {SourceCode} sourceCode The source code object for the file being linted. + * @returns {{ description, fix, unprocessedDirective }[]} Details for later creation of output Problems. + */ +function processUnusedDirectives(allDirectives, sourceCode) { + const directiveGroups = groupByParentDirective(allDirectives); + + return directiveGroups.flatMap(directives => { + const { parentDirective } = directives[0].unprocessedDirective; + const remainingRuleIds = new Set(parentDirective.ruleIds); + + for (const directive of directives) { + remainingRuleIds.delete(directive.ruleId); + } + + return remainingRuleIds.size + ? createIndividualDirectivesRemoval( + directives, + parentDirective, + sourceCode, + ) + : [ + createDirectiveRemoval( + directives, + parentDirective.node, + sourceCode, + ), + ]; + }); +} + +/** + * Collect eslint-enable comments that are removing suppressions by eslint-disable comments. + * @param {Directive[]} directives The directives to check. + * @returns {Set} The used eslint-enable comments + */ +function collectUsedEnableDirectives(directives) { + /** + * A Map of `eslint-enable` keyed by ruleIds that may be marked as used. + * If `eslint-enable` does not have a ruleId, the key will be `null`. + * @type {Map} + */ + const enabledRules = new Map(); + + /** + * A Set of `eslint-enable` marked as used. + * It is also the return value of `collectUsedEnableDirectives` function. + * @type {Set} + */ + const usedEnableDirectives = new Set(); + + /* + * Checks the directives backwards to see if the encountered `eslint-enable` is used by the previous `eslint-disable`, + * and if so, stores the `eslint-enable` in `usedEnableDirectives`. + */ + for (let index = directives.length - 1; index >= 0; index--) { + const directive = directives[index]; + + if (directive.type === "disable") { + if (enabledRules.size === 0) { + continue; + } + if (directive.ruleId === null) { + // If encounter `eslint-disable` without ruleId, + // mark all `eslint-enable` currently held in enabledRules as used. + // e.g. + // /* eslint-disable */ <- current directive + // /* eslint-enable rule-id1 */ <- used + // /* eslint-enable rule-id2 */ <- used + // /* eslint-enable */ <- used + for (const enableDirective of enabledRules.values()) { + usedEnableDirectives.add(enableDirective); + } + enabledRules.clear(); + } else { + const enableDirective = enabledRules.get(directive.ruleId); + + if (enableDirective) { + // If encounter `eslint-disable` with ruleId, and there is an `eslint-enable` with the same ruleId in enabledRules, + // mark `eslint-enable` with ruleId as used. + // e.g. + // /* eslint-disable rule-id */ <- current directive + // /* eslint-enable rule-id */ <- used + usedEnableDirectives.add(enableDirective); + } else { + const enabledDirectiveWithoutRuleId = + enabledRules.get(null); + + if (enabledDirectiveWithoutRuleId) { + // If encounter `eslint-disable` with ruleId, and there is no `eslint-enable` with the same ruleId in enabledRules, + // mark `eslint-enable` without ruleId as used. + // e.g. + // /* eslint-disable rule-id */ <- current directive + // /* eslint-enable */ <- used + usedEnableDirectives.add(enabledDirectiveWithoutRuleId); + } + } + } + } else if (directive.type === "enable") { + if (directive.ruleId === null) { + // If encounter `eslint-enable` without ruleId, the `eslint-enable` that follows it are unused. + // So clear enabledRules. + // e.g. + // /* eslint-enable */ <- current directive + // /* eslint-enable rule-id *// <- unused + // /* eslint-enable */ <- unused + enabledRules.clear(); + enabledRules.set(null, directive); + } else { + enabledRules.set(directive.ruleId, directive); + } + } + } + return usedEnableDirectives; +} + +/** + * This is the same as the exported function, except that it + * doesn't handle disable-line and disable-next-line directives, and it always reports unused + * disable directives. + * @param {Object} options options for applying directives. This is the same as the options + * for the exported function, except that `reportUnusedDisableDirectives` is not supported + * (this function always reports unused disable directives). + * @returns {{problems: LintMessage[], unusedDirectives: LintMessage[]}} An object with a list + * of problems (including suppressed ones) and unused eslint-disable directives + */ +function applyDirectives(options) { + const problems = []; + const usedDisableDirectives = new Set(); + const { sourceCode } = options; + + for (const problem of options.problems) { + let disableDirectivesForProblem = []; + let nextDirectiveIndex = 0; + + while ( + nextDirectiveIndex < options.directives.length && + compareLocations(options.directives[nextDirectiveIndex], problem) <= + 0 + ) { + const directive = options.directives[nextDirectiveIndex++]; + + if ( + directive.ruleId === null || + directive.ruleId === problem.ruleId + ) { + switch (directive.type) { + case "disable": + disableDirectivesForProblem.push(directive); + break; + + case "enable": + disableDirectivesForProblem = []; + break; + + // no default + } + } + } + + if (disableDirectivesForProblem.length > 0) { + const suppressions = disableDirectivesForProblem.map(directive => ({ + kind: "directive", + justification: directive.unprocessedDirective.justification, + })); + + if (problem.suppressions) { + problem.suppressions = + problem.suppressions.concat(suppressions); + } else { + problem.suppressions = suppressions; + usedDisableDirectives.add(disableDirectivesForProblem.at(-1)); + } + } + + problems.push(problem); + } + + const unusedDisableDirectivesToReport = options.directives.filter( + directive => + directive.type === "disable" && + !usedDisableDirectives.has(directive) && + !options.rulesToIgnore.has(directive.ruleId), + ); + + const unusedEnableDirectivesToReport = new Set( + options.directives.filter( + directive => + directive.unprocessedDirective.type === "enable" && + !options.rulesToIgnore.has(directive.ruleId), + ), + ); + + /* + * If directives has the eslint-enable directive, + * check whether the eslint-enable comment is used. + */ + if (unusedEnableDirectivesToReport.size > 0) { + for (const directive of collectUsedEnableDirectives( + options.directives, + )) { + unusedEnableDirectivesToReport.delete(directive); + } + } + + const processed = processUnusedDirectives( + unusedDisableDirectivesToReport, + sourceCode, + ).concat( + processUnusedDirectives(unusedEnableDirectivesToReport, sourceCode), + ); + const columnOffset = options.language.columnStart === 1 ? 0 : 1; + const lineOffset = options.language.lineStart === 1 ? 0 : 1; + + const unusedDirectives = processed.map( + ({ description, fix, unprocessedDirective }) => { + const { parentDirective, type, line, column } = + unprocessedDirective; + + let message; + + if (type === "enable") { + message = description + ? `Unused eslint-enable directive (no matching eslint-disable directives were found for ${description}).` + : "Unused eslint-enable directive (no matching eslint-disable directives were found)."; + } else { + message = description + ? `Unused eslint-disable directive (no problems were reported from ${description}).` + : "Unused eslint-disable directive (no problems were reported)."; + } + + const loc = sourceCode.getLoc(parentDirective.node); + + return { + ruleId: null, + message, + line: + type === "disable-next-line" + ? loc.start.line + lineOffset + : line, + column: + type === "disable-next-line" + ? loc.start.column + columnOffset + : column, + severity: + options.reportUnusedDisableDirectives === "warn" ? 1 : 2, + nodeType: null, + ...(options.disableFixes ? {} : { fix }), + }; + }, + ); + + return { problems, unusedDirectives }; +} + +/** + * Given a list of directive comments (i.e. metadata about eslint-disable and eslint-enable comments) and a list + * of reported problems, adds the suppression information to the problems. + * @param {Object} options Information about directives and problems + * @param {Language} options.language The language being linted. + * @param {SourceCode} options.sourceCode The source code object for the file being linted. + * @param {{ + * type: ("disable"|"enable"|"disable-line"|"disable-next-line"), + * ruleId: (string|null), + * line: number, + * column: number, + * justification: string + * }} options.directives Directive comments found in the file, with one-based columns. + * Two directive comments can only have the same location if they also have the same type (e.g. a single eslint-disable + * comment for two different rules is represented as two directives). + * @param {{ruleId: (string|null), line: number, column: number}[]} options.problems + * A list of problems reported by rules, sorted by increasing location in the file, with one-based columns. + * @param {"off" | "warn" | "error"} options.reportUnusedDisableDirectives If `"warn"` or `"error"`, adds additional problems for unused directives + * @param {RulesConfig} options.configuredRules The rules configuration. + * @param {Function} options.ruleFilter A predicate function to filter which rules should be executed. + * @param {boolean} options.disableFixes If true, it doesn't make `fix` properties. + * @returns {{ruleId: (string|null), line: number, column: number, suppressions?: {kind: string, justification: string}}[]} + * An object with a list of reported problems, the suppressed of which contain the suppression information. + */ +module.exports = ({ + language, + sourceCode, + directives, + disableFixes, + problems, + configuredRules, + ruleFilter, + reportUnusedDisableDirectives = "off", +}) => { + const blockDirectives = directives + .filter( + directive => + directive.type === "disable" || directive.type === "enable", + ) + .map(directive => + Object.assign({}, directive, { unprocessedDirective: directive }), + ) + .sort(compareLocations); + + const lineDirectives = directives + .flatMap(directive => { + switch (directive.type) { + case "disable": + case "enable": + return []; + + case "disable-line": + return [ + { + type: "disable", + line: directive.line, + column: 1, + ruleId: directive.ruleId, + unprocessedDirective: directive, + }, + { + type: "enable", + line: directive.line + 1, + column: 0, + ruleId: directive.ruleId, + unprocessedDirective: directive, + }, + ]; + + case "disable-next-line": + return [ + { + type: "disable", + line: directive.line + 1, + column: 1, + ruleId: directive.ruleId, + unprocessedDirective: directive, + }, + { + type: "enable", + line: directive.line + 2, + column: 0, + ruleId: directive.ruleId, + unprocessedDirective: directive, + }, + ]; + + default: + throw new TypeError( + `Unrecognized directive type '${directive.type}'`, + ); + } + }) + .sort(compareLocations); + + // This determines a list of rules that are not being run by the given ruleFilter, if present. + const rulesToIgnore = + configuredRules && ruleFilter + ? new Set( + Object.keys(configuredRules).filter(ruleId => { + const severity = Config.getRuleNumericSeverity( + configuredRules[ruleId], + ); + + // Ignore for disabled rules. + if (severity === 0) { + return false; + } + + return !ruleFilter({ severity, ruleId }); + }), + ) + : new Set(); + + // If no ruleId is supplied that means this directive is applied to all rules, so we can't determine if it's unused if any rules are filtered out. + if (rulesToIgnore.size > 0) { + rulesToIgnore.add(null); + } + + const blockDirectivesResult = applyDirectives({ + language, + sourceCode, + problems, + directives: blockDirectives, + disableFixes, + reportUnusedDisableDirectives, + rulesToIgnore, + }); + const lineDirectivesResult = applyDirectives({ + language, + sourceCode, + problems: blockDirectivesResult.problems, + directives: lineDirectives, + disableFixes, + reportUnusedDisableDirectives, + rulesToIgnore, + }); + + return reportUnusedDisableDirectives !== "off" + ? lineDirectivesResult.problems + .concat(blockDirectivesResult.unusedDirectives) + .concat(lineDirectivesResult.unusedDirectives) + .sort(compareLocations) + : lineDirectivesResult.problems; +}; diff --git a/tools/ui/node_modules/eslint/lib/linter/code-path-analysis/code-path-analyzer.js b/tools/ui/node_modules/eslint/lib/linter/code-path-analysis/code-path-analyzer.js new file mode 100644 index 0000000000000000000000000000000000000000..fc728d10d9cff588214b2c705f80b47d93dd0d82 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/linter/code-path-analysis/code-path-analyzer.js @@ -0,0 +1,828 @@ +/** + * @fileoverview A class of the code path analyzer. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const assert = require("../../shared/assert"), + { breakableTypePattern } = require("../../shared/ast-utils"), + CodePath = require("./code-path"), + CodePathSegment = require("./code-path-segment"), + IdGenerator = require("./id-generator"), + debug = require("./debug-helpers"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not a given node is a `case` node (not `default` node). + * @param {ASTNode} node A `SwitchCase` node to check. + * @returns {boolean} `true` if the node is a `case` node (not `default` node). + */ +function isCaseNode(node) { + return Boolean(node.test); +} + +/** + * Checks if a given node appears as the value of a PropertyDefinition node. + * @param {ASTNode} node THe node to check. + * @returns {boolean} `true` if the node is a PropertyDefinition value, + * false if not. + */ +function isPropertyDefinitionValue(node) { + const parent = node.parent; + + return ( + parent && parent.type === "PropertyDefinition" && parent.value === node + ); +} + +/** + * Checks whether the given logical operator is taken into account for the code + * path analysis. + * @param {string} operator The operator found in the LogicalExpression node + * @returns {boolean} `true` if the operator is "&&" or "||" or "??" + */ +function isHandledLogicalOperator(operator) { + return operator === "&&" || operator === "||" || operator === "??"; +} + +/** + * Checks whether the given assignment operator is a logical assignment operator. + * Logical assignments are taken into account for the code path analysis + * because of their short-circuiting semantics. + * @param {string} operator The operator found in the AssignmentExpression node + * @returns {boolean} `true` if the operator is "&&=" or "||=" or "??=" + */ +function isLogicalAssignmentOperator(operator) { + return operator === "&&=" || operator === "||=" || operator === "??="; +} + +/** + * Gets the label if the parent node of a given node is a LabeledStatement. + * @param {ASTNode} node A node to get. + * @returns {string|null} The label or `null`. + */ +function getLabel(node) { + if (node.parent.type === "LabeledStatement") { + return node.parent.label.name; + } + return null; +} + +/** + * Checks whether or not a given logical expression node goes different path + * between the `true` case and the `false` case. + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is a test of a choice statement. + */ +function isForkingByTrueOrFalse(node) { + const parent = node.parent; + + switch (parent.type) { + case "ConditionalExpression": + case "IfStatement": + case "WhileStatement": + case "DoWhileStatement": + case "ForStatement": + return parent.test === node; + + case "LogicalExpression": + return isHandledLogicalOperator(parent.operator); + + case "AssignmentExpression": + return isLogicalAssignmentOperator(parent.operator); + + default: + return false; + } +} + +/** + * Gets the boolean value of a given literal node. + * + * This is used to detect infinity loops (e.g. `while (true) {}`). + * Statements preceded by an infinity loop are unreachable if the loop didn't + * have any `break` statement. + * @param {ASTNode} node A node to get. + * @returns {boolean|undefined} a boolean value if the node is a Literal node, + * otherwise `undefined`. + */ +function getBooleanValueIfSimpleConstant(node) { + if (node.type === "Literal") { + return Boolean(node.value); + } + return void 0; +} + +/** + * Checks that a given identifier node is a reference or not. + * + * This is used to detect the first throwable node in a `try` block. + * @param {ASTNode} node An Identifier node to check. + * @returns {boolean} `true` if the node is a reference. + */ +function isIdentifierReference(node) { + const parent = node.parent; + + switch (parent.type) { + case "LabeledStatement": + case "BreakStatement": + case "ContinueStatement": + case "ArrayPattern": + case "RestElement": + case "ImportSpecifier": + case "ImportDefaultSpecifier": + case "ImportNamespaceSpecifier": + case "CatchClause": + return false; + + case "FunctionDeclaration": + case "FunctionExpression": + case "ArrowFunctionExpression": + case "ClassDeclaration": + case "ClassExpression": + case "VariableDeclarator": + return parent.id !== node; + + case "Property": + case "PropertyDefinition": + case "MethodDefinition": + return parent.key !== node || parent.computed || parent.shorthand; + + case "AssignmentPattern": + return parent.key !== node; + + default: + return true; + } +} + +/** + * Updates the current segment with the head segment. + * This is similar to local branches and tracking branches of git. + * + * To separate the current and the head is in order to not make useless segments. + * + * In this process, both "onCodePathSegmentStart" and "onCodePathSegmentEnd" + * events are fired. + * @param {CodePathAnalyzer} analyzer The instance. + * @param {ASTNode} node The current AST node. + * @returns {void} + */ +function forwardCurrentToHead(analyzer, node) { + const codePath = analyzer.codePath; + const state = CodePath.getState(codePath); + const currentSegments = state.currentSegments; + const headSegments = state.headSegments; + const end = Math.max(currentSegments.length, headSegments.length); + let i, currentSegment, headSegment; + + // Fires leaving events. + for (i = 0; i < end; ++i) { + currentSegment = currentSegments[i]; + headSegment = headSegments[i]; + + if (currentSegment !== headSegment && currentSegment) { + const eventName = currentSegment.reachable + ? "onCodePathSegmentEnd" + : "onUnreachableCodePathSegmentEnd"; + + debug.dump(`${eventName} ${currentSegment.id}`); + + analyzer.emit(eventName, [currentSegment, node]); + } + } + + // Update state. + state.currentSegments = headSegments; + + // Fires entering events. + for (i = 0; i < end; ++i) { + currentSegment = currentSegments[i]; + headSegment = headSegments[i]; + + if (currentSegment !== headSegment && headSegment) { + const eventName = headSegment.reachable + ? "onCodePathSegmentStart" + : "onUnreachableCodePathSegmentStart"; + + debug.dump(`${eventName} ${headSegment.id}`); + CodePathSegment.markUsed(headSegment); + analyzer.emit(eventName, [headSegment, node]); + } + } +} + +/** + * Updates the current segment with empty. + * This is called at the last of functions or the program. + * @param {CodePathAnalyzer} analyzer The instance. + * @param {ASTNode} node The current AST node. + * @returns {void} + */ +function leaveFromCurrentSegment(analyzer, node) { + const state = CodePath.getState(analyzer.codePath); + const currentSegments = state.currentSegments; + + for (let i = 0; i < currentSegments.length; ++i) { + const currentSegment = currentSegments[i]; + const eventName = currentSegment.reachable + ? "onCodePathSegmentEnd" + : "onUnreachableCodePathSegmentEnd"; + + debug.dump(`${eventName} ${currentSegment.id}`); + + analyzer.emit(eventName, [currentSegment, node]); + } + + state.currentSegments = []; +} + +/** + * Updates the code path due to the position of a given node in the parent node + * thereof. + * + * For example, if the node is `parent.consequent`, this creates a fork from the + * current path. + * @param {CodePathAnalyzer} analyzer The instance. + * @param {ASTNode} node The current AST node. + * @returns {void} + */ +function preprocess(analyzer, node) { + const codePath = analyzer.codePath; + const state = CodePath.getState(codePath); + const parent = node.parent; + + switch (parent.type) { + // The `arguments.length == 0` case is in `postprocess` function. + case "CallExpression": + if ( + parent.optional === true && + parent.arguments.length >= 1 && + parent.arguments[0] === node + ) { + state.makeOptionalRight(); + } + break; + case "MemberExpression": + if (parent.optional === true && parent.property === node) { + state.makeOptionalRight(); + } + break; + + case "LogicalExpression": + if ( + parent.right === node && + isHandledLogicalOperator(parent.operator) + ) { + state.makeLogicalRight(); + } + break; + + case "AssignmentExpression": + if ( + parent.right === node && + isLogicalAssignmentOperator(parent.operator) + ) { + state.makeLogicalRight(); + } + break; + + case "ConditionalExpression": + case "IfStatement": + /* + * Fork if this node is at `consequent`/`alternate`. + * `popForkContext()` exists at `IfStatement:exit` and + * `ConditionalExpression:exit`. + */ + if (parent.consequent === node) { + state.makeIfConsequent(); + } else if (parent.alternate === node) { + state.makeIfAlternate(); + } + break; + + case "SwitchCase": + if (parent.consequent[0] === node) { + state.makeSwitchCaseBody(false, !parent.test); + } + break; + + case "TryStatement": + if (parent.handler === node) { + state.makeCatchBlock(); + } else if (parent.finalizer === node) { + state.makeFinallyBlock(); + } + break; + + case "WhileStatement": + if (parent.test === node) { + state.makeWhileTest(getBooleanValueIfSimpleConstant(node)); + } else { + assert(parent.body === node); + state.makeWhileBody(); + } + break; + + case "DoWhileStatement": + if (parent.body === node) { + state.makeDoWhileBody(); + } else { + assert(parent.test === node); + state.makeDoWhileTest(getBooleanValueIfSimpleConstant(node)); + } + break; + + case "ForStatement": + if (parent.test === node) { + state.makeForTest(getBooleanValueIfSimpleConstant(node)); + } else if (parent.update === node) { + state.makeForUpdate(); + } else if (parent.body === node) { + state.makeForBody(); + } + break; + + case "ForInStatement": + case "ForOfStatement": + if (parent.left === node) { + state.makeForInOfLeft(); + } else if (parent.right === node) { + state.makeForInOfRight(); + } else { + assert(parent.body === node); + state.makeForInOfBody(); + } + break; + + case "AssignmentPattern": + /* + * Fork if this node is at `right`. + * `left` is executed always, so it uses the current path. + * `popForkContext()` exists at `AssignmentPattern:exit`. + */ + if (parent.right === node) { + state.pushForkContext(); + state.forkBypassPath(); + state.forkPath(); + } + break; + + default: + break; + } +} + +/** + * Updates the code path due to the type of a given node in entering. + * @param {CodePathAnalyzer} analyzer The instance. + * @param {ASTNode} node The current AST node. + * @returns {void} + */ +function processCodePathToEnter(analyzer, node) { + let codePath = analyzer.codePath; + let state = codePath && CodePath.getState(codePath); + const parent = node.parent; + + /** + * Creates a new code path and trigger the onCodePathStart event + * based on the currently selected node. + * @param {string} origin The reason the code path was started. + * @returns {void} + */ + function startCodePath(origin) { + if (codePath) { + // Emits onCodePathSegmentStart events if updated. + forwardCurrentToHead(analyzer, node); + debug.dumpState(node, state, false); + } + + // Create the code path of this scope. + codePath = analyzer.codePath = new CodePath({ + id: analyzer.idGenerator.next(), + origin, + upper: codePath, + onLooped: analyzer.onLooped, + }); + state = CodePath.getState(codePath); + + // Emits onCodePathStart events. + debug.dump(`onCodePathStart ${codePath.id}`); + analyzer.emit("onCodePathStart", [codePath, node]); + } + + /* + * Special case: The right side of class field initializer is considered + * to be its own function, so we need to start a new code path in this + * case. + */ + if (isPropertyDefinitionValue(node)) { + startCodePath("class-field-initializer"); + + /* + * Intentional fall through because `node` needs to also be + * processed by the code below. For example, if we have: + * + * class Foo { + * a = () => {} + * } + * + * In this case, we also need start a second code path. + */ + } + + switch (node.type) { + case "Program": + startCodePath("program"); + break; + + case "FunctionDeclaration": + case "FunctionExpression": + case "ArrowFunctionExpression": + startCodePath("function"); + break; + + case "StaticBlock": + startCodePath("class-static-block"); + break; + + case "ChainExpression": + state.pushChainContext(); + break; + case "CallExpression": + if (node.optional === true) { + state.makeOptionalNode(); + } + break; + case "MemberExpression": + if (node.optional === true) { + state.makeOptionalNode(); + } + break; + + case "LogicalExpression": + if (isHandledLogicalOperator(node.operator)) { + state.pushChoiceContext( + node.operator, + isForkingByTrueOrFalse(node), + ); + } + break; + + case "AssignmentExpression": + if (isLogicalAssignmentOperator(node.operator)) { + state.pushChoiceContext( + node.operator.slice(0, -1), // removes `=` from the end + isForkingByTrueOrFalse(node), + ); + } + break; + + case "ConditionalExpression": + case "IfStatement": + state.pushChoiceContext("test", false); + break; + + case "SwitchStatement": + state.pushSwitchContext( + node.cases.some(isCaseNode), + getLabel(node), + ); + break; + + case "TryStatement": + state.pushTryContext(Boolean(node.finalizer)); + break; + + case "SwitchCase": + /* + * Fork if this node is after the 2st node in `cases`. + * It's similar to `else` blocks. + * The next `test` node is processed in this path. + */ + if (parent.discriminant !== node && parent.cases[0] !== node) { + state.forkPath(); + } + break; + + case "WhileStatement": + case "DoWhileStatement": + case "ForStatement": + case "ForInStatement": + case "ForOfStatement": + state.pushLoopContext(node.type, getLabel(node)); + break; + + case "LabeledStatement": + if (!breakableTypePattern.test(node.body.type)) { + state.pushBreakContext(false, node.label.name); + } + break; + + default: + break; + } + + // Emits onCodePathSegmentStart events if updated. + forwardCurrentToHead(analyzer, node); + debug.dumpState(node, state, false); +} + +/** + * Updates the code path due to the type of a given node in leaving. + * @param {CodePathAnalyzer} analyzer The instance. + * @param {ASTNode} node The current AST node. + * @returns {void} + */ +function processCodePathToExit(analyzer, node) { + const codePath = analyzer.codePath; + const state = CodePath.getState(codePath); + let dontForward = false; + + switch (node.type) { + case "ChainExpression": + state.popChainContext(); + break; + + case "IfStatement": + case "ConditionalExpression": + state.popChoiceContext(); + break; + + case "LogicalExpression": + if (isHandledLogicalOperator(node.operator)) { + state.popChoiceContext(); + } + break; + + case "AssignmentExpression": + if (isLogicalAssignmentOperator(node.operator)) { + state.popChoiceContext(); + } + break; + + case "SwitchStatement": + state.popSwitchContext(); + break; + + case "SwitchCase": + /* + * This is the same as the process at the 1st `consequent` node in + * `preprocess` function. + * Must do if this `consequent` is empty. + */ + if (node.consequent.length === 0) { + state.makeSwitchCaseBody(true, !node.test); + } + if (state.forkContext.reachable) { + dontForward = true; + } + break; + + case "TryStatement": + state.popTryContext(); + break; + + case "BreakStatement": + forwardCurrentToHead(analyzer, node); + state.makeBreak(node.label && node.label.name); + dontForward = true; + break; + + case "ContinueStatement": + forwardCurrentToHead(analyzer, node); + state.makeContinue(node.label && node.label.name); + dontForward = true; + break; + + case "ReturnStatement": + forwardCurrentToHead(analyzer, node); + state.makeReturn(); + dontForward = true; + break; + + case "ThrowStatement": + forwardCurrentToHead(analyzer, node); + state.makeThrow(); + dontForward = true; + break; + + case "Identifier": + if (isIdentifierReference(node)) { + state.makeFirstThrowablePathInTryBlock(); + dontForward = true; + } + break; + + case "CallExpression": + case "ImportExpression": + case "MemberExpression": + case "NewExpression": + case "YieldExpression": + state.makeFirstThrowablePathInTryBlock(); + break; + + case "WhileStatement": + case "DoWhileStatement": + case "ForStatement": + case "ForInStatement": + case "ForOfStatement": + state.popLoopContext(); + break; + + case "AssignmentPattern": + state.popForkContext(); + break; + + case "LabeledStatement": + if (!breakableTypePattern.test(node.body.type)) { + state.popBreakContext(); + } + break; + + default: + break; + } + + // Emits onCodePathSegmentStart events if updated. + if (!dontForward) { + forwardCurrentToHead(analyzer, node); + } + debug.dumpState(node, state, true); +} + +/** + * Updates the code path to finalize the current code path. + * @param {CodePathAnalyzer} analyzer The instance. + * @param {ASTNode} node The current AST node. + * @returns {void} + */ +function postprocess(analyzer, node) { + /** + * Ends the code path for the current node. + * @returns {void} + */ + function endCodePath() { + let codePath = analyzer.codePath; + + // Mark the current path as the final node. + CodePath.getState(codePath).makeFinal(); + + // Emits onCodePathSegmentEnd event of the current segments. + leaveFromCurrentSegment(analyzer, node); + + // Emits onCodePathEnd event of this code path. + debug.dump(`onCodePathEnd ${codePath.id}`); + analyzer.emit("onCodePathEnd", [codePath, node]); + debug.dumpDot(codePath); + + codePath = analyzer.codePath = analyzer.codePath.upper; + if (codePath) { + debug.dumpState(node, CodePath.getState(codePath), true); + } + } + + switch (node.type) { + case "Program": + case "FunctionDeclaration": + case "FunctionExpression": + case "ArrowFunctionExpression": + case "StaticBlock": { + endCodePath(); + break; + } + + // The `arguments.length >= 1` case is in `preprocess` function. + case "CallExpression": + if (node.optional === true && node.arguments.length === 0) { + CodePath.getState(analyzer.codePath).makeOptionalRight(); + } + break; + + default: + break; + } + + /* + * Special case: The right side of class field initializer is considered + * to be its own function, so we need to end a code path in this + * case. + * + * We need to check after the other checks in order to close the + * code paths in the correct order for code like this: + * + * + * class Foo { + * a = () => {} + * } + * + * In this case, The ArrowFunctionExpression code path is closed first + * and then we need to close the code path for the PropertyDefinition + * value. + */ + if (isPropertyDefinitionValue(node)) { + endCodePath(); + } +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * The class to analyze code paths. + * This class implements the EventGenerator interface. + */ +class CodePathAnalyzer { + /** + * @param {EventGenerator} eventGenerator An event generator to wrap. + */ + constructor(eventGenerator) { + this.original = eventGenerator; + this.emit = eventGenerator.emit; + this.codePath = null; + this.idGenerator = new IdGenerator("s"); + this.currentNode = null; + this.onLooped = this.onLooped.bind(this); + } + + /** + * Does the process to enter a given AST node. + * This updates state of analysis and calls `enterNode` of the wrapped. + * @param {ASTNode} node A node which is entering. + * @returns {void} + */ + enterNode(node) { + this.currentNode = node; + + // Updates the code path due to node's position in its parent node. + if (node.parent) { + preprocess(this, node); + } + + /* + * Updates the code path. + * And emits onCodePathStart/onCodePathSegmentStart events. + */ + processCodePathToEnter(this, node); + + // Emits node events. + this.original.enterNode(node); + + this.currentNode = null; + } + + /** + * Does the process to leave a given AST node. + * This updates state of analysis and calls `leaveNode` of the wrapped. + * @param {ASTNode} node A node which is leaving. + * @returns {void} + */ + leaveNode(node) { + this.currentNode = node; + + /* + * Updates the code path. + * And emits onCodePathStart/onCodePathSegmentStart events. + */ + processCodePathToExit(this, node); + + // Emits node events. + this.original.leaveNode(node); + + // Emits the last onCodePathStart/onCodePathSegmentStart events. + postprocess(this, node); + + this.currentNode = null; + } + + /** + * This is called on a code path looped. + * Then this raises a looped event. + * @param {CodePathSegment} fromSegment A segment of prev. + * @param {CodePathSegment} toSegment A segment of next. + * @returns {void} + */ + onLooped(fromSegment, toSegment) { + if (fromSegment.reachable && toSegment.reachable) { + debug.dump( + `onCodePathSegmentLoop ${fromSegment.id} -> ${toSegment.id}`, + ); + this.emit("onCodePathSegmentLoop", [ + fromSegment, + toSegment, + this.currentNode, + ]); + } + } +} + +module.exports = CodePathAnalyzer; diff --git a/tools/ui/node_modules/eslint/lib/linter/code-path-analysis/code-path-segment.js b/tools/ui/node_modules/eslint/lib/linter/code-path-analysis/code-path-segment.js new file mode 100644 index 0000000000000000000000000000000000000000..fa4950185749150c2ba665eb6d69cd82f24db095 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/linter/code-path-analysis/code-path-segment.js @@ -0,0 +1,262 @@ +/** + * @fileoverview The CodePathSegment class. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const debug = require("./debug-helpers"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not a given segment is reachable. + * @param {CodePathSegment} segment A segment to check. + * @returns {boolean} `true` if the segment is reachable. + */ +function isReachable(segment) { + return segment.reachable; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * A code path segment. + * + * Each segment is arranged in a series of linked lists (implemented by arrays) + * that keep track of the previous and next segments in a code path. In this way, + * you can navigate between all segments in any code path so long as you have a + * reference to any segment in that code path. + * + * When first created, the segment is in a detached state, meaning that it knows the + * segments that came before it but those segments don't know that this new segment + * follows it. Only when `CodePathSegment#markUsed()` is called on a segment does it + * officially become part of the code path by updating the previous segments to know + * that this new segment follows. + */ +class CodePathSegment { + /** + * Creates a new instance. + * @param {string} id An identifier. + * @param {CodePathSegment[]} allPrevSegments An array of the previous segments. + * This array includes unreachable segments. + * @param {boolean} reachable A flag which shows this is reachable. + */ + constructor(id, allPrevSegments, reachable) { + /** + * The identifier of this code path. + * Rules use it to store additional information of each rule. + * @type {string} + */ + this.id = id; + + /** + * An array of the next reachable segments. + * @type {CodePathSegment[]} + */ + this.nextSegments = []; + + /** + * An array of the previous reachable segments. + * @type {CodePathSegment[]} + */ + this.prevSegments = allPrevSegments.filter(isReachable); + + /** + * An array of all next segments including reachable and unreachable. + * @type {CodePathSegment[]} + */ + this.allNextSegments = []; + + /** + * An array of all previous segments including reachable and unreachable. + * @type {CodePathSegment[]} + */ + this.allPrevSegments = allPrevSegments; + + /** + * A flag which shows this is reachable. + * @type {boolean} + */ + this.reachable = reachable; + + // Internal data. + Object.defineProperty(this, "internal", { + value: { + // determines if the segment has been attached to the code path + used: false, + + // array of previous segments coming from the end of a loop + loopedPrevSegments: [], + }, + }); + + /* c8 ignore start */ + if (debug.enabled) { + this.internal.nodes = []; + } /* c8 ignore stop */ + } + + /** + * Checks a given previous segment is coming from the end of a loop. + * @param {CodePathSegment} segment A previous segment to check. + * @returns {boolean} `true` if the segment is coming from the end of a loop. + */ + isLoopedPrevSegment(segment) { + return this.internal.loopedPrevSegments.includes(segment); + } + + /** + * Creates the root segment. + * @param {string} id An identifier. + * @returns {CodePathSegment} The created segment. + */ + static newRoot(id) { + return new CodePathSegment(id, [], true); + } + + /** + * Creates a new segment and appends it after the given segments. + * @param {string} id An identifier. + * @param {CodePathSegment[]} allPrevSegments An array of the previous segments + * to append to. + * @returns {CodePathSegment} The created segment. + */ + static newNext(id, allPrevSegments) { + return new CodePathSegment( + id, + CodePathSegment.flattenUnusedSegments(allPrevSegments), + allPrevSegments.some(isReachable), + ); + } + + /** + * Creates an unreachable segment and appends it after the given segments. + * @param {string} id An identifier. + * @param {CodePathSegment[]} allPrevSegments An array of the previous segments. + * @returns {CodePathSegment} The created segment. + */ + static newUnreachable(id, allPrevSegments) { + const segment = new CodePathSegment( + id, + CodePathSegment.flattenUnusedSegments(allPrevSegments), + false, + ); + + /* + * In `if (a) return a; foo();` case, the unreachable segment preceded by + * the return statement is not used but must not be removed. + */ + CodePathSegment.markUsed(segment); + + return segment; + } + + /** + * Creates a segment that follows given segments. + * This factory method does not connect with `allPrevSegments`. + * But this inherits `reachable` flag. + * @param {string} id An identifier. + * @param {CodePathSegment[]} allPrevSegments An array of the previous segments. + * @returns {CodePathSegment} The created segment. + */ + static newDisconnected(id, allPrevSegments) { + return new CodePathSegment(id, [], allPrevSegments.some(isReachable)); + } + + /** + * Marks a given segment as used. + * + * And this function registers the segment into the previous segments as a next. + * @param {CodePathSegment} segment A segment to mark. + * @returns {void} + */ + static markUsed(segment) { + if (segment.internal.used) { + return; + } + segment.internal.used = true; + + let i; + + if (segment.reachable) { + /* + * If the segment is reachable, then it's officially part of the + * code path. This loops through all previous segments to update + * their list of next segments. Because the segment is reachable, + * it's added to both `nextSegments` and `allNextSegments`. + */ + for (i = 0; i < segment.allPrevSegments.length; ++i) { + const prevSegment = segment.allPrevSegments[i]; + + prevSegment.allNextSegments.push(segment); + prevSegment.nextSegments.push(segment); + } + } else { + /* + * If the segment is not reachable, then it's not officially part of the + * code path. This loops through all previous segments to update + * their list of next segments. Because the segment is not reachable, + * it's added only to `allNextSegments`. + */ + for (i = 0; i < segment.allPrevSegments.length; ++i) { + segment.allPrevSegments[i].allNextSegments.push(segment); + } + } + } + + /** + * Marks a previous segment as looped. + * @param {CodePathSegment} segment A segment. + * @param {CodePathSegment} prevSegment A previous segment to mark. + * @returns {void} + */ + static markPrevSegmentAsLooped(segment, prevSegment) { + segment.internal.loopedPrevSegments.push(prevSegment); + } + + /** + * Creates a new array based on an array of segments. If any segment in the + * array is unused, then it is replaced by all of its previous segments. + * All used segments are returned as-is without replacement. + * @param {CodePathSegment[]} segments The array of segments to flatten. + * @returns {CodePathSegment[]} The flattened array. + */ + static flattenUnusedSegments(segments) { + const done = new Set(); + + for (let i = 0; i < segments.length; ++i) { + const segment = segments[i]; + + // Ignores duplicated. + if (done.has(segment)) { + continue; + } + + // Use previous segments if unused. + if (!segment.internal.used) { + for (let j = 0; j < segment.allPrevSegments.length; ++j) { + const prevSegment = segment.allPrevSegments[j]; + + if (!done.has(prevSegment)) { + done.add(prevSegment); + } + } + } else { + done.add(segment); + } + } + + return [...done]; + } +} + +module.exports = CodePathSegment; diff --git a/tools/ui/node_modules/eslint/lib/linter/code-path-analysis/code-path-state.js b/tools/ui/node_modules/eslint/lib/linter/code-path-analysis/code-path-state.js new file mode 100644 index 0000000000000000000000000000000000000000..3ed4a7bc6502e0ba1801f67fe356cd8b29ea43de --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/linter/code-path-analysis/code-path-state.js @@ -0,0 +1,2370 @@ +/** + * @fileoverview A class to manage state of generating a code path. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const CodePathSegment = require("./code-path-segment"), + ForkContext = require("./fork-context"); + +//----------------------------------------------------------------------------- +// Contexts +//----------------------------------------------------------------------------- + +/** + * Represents the context in which a `break` statement can be used. + * + * A `break` statement without a label is only valid in a few places in + * JavaScript: any type of loop or a `switch` statement. Otherwise, `break` + * without a label causes a syntax error. For these contexts, `breakable` is + * set to `true` to indicate that a `break` without a label is valid. + * + * However, a `break` statement with a label is also valid inside of a labeled + * statement. For example, this is valid: + * + * a : { + * break a; + * } + * + * The `breakable` property is set false for labeled statements to indicate + * that `break` without a label is invalid. + */ +class BreakContext { + /** + * Creates a new instance. + * @param {BreakContext} upperContext The previous `BreakContext`. + * @param {boolean} breakable Indicates if we are inside a statement where + * `break` without a label will exit the statement. + * @param {string|null} label The label for the statement. + * @param {ForkContext} forkContext The current fork context. + */ + constructor(upperContext, breakable, label, forkContext) { + /** + * The previous `BreakContext` + * @type {BreakContext} + */ + this.upper = upperContext; + + /** + * Indicates if we are inside a statement where `break` without a label + * will exit the statement. + * @type {boolean} + */ + this.breakable = breakable; + + /** + * The label associated with the statement. + * @type {string|null} + */ + this.label = label; + + /** + * The fork context for the `break`. + * @type {ForkContext} + */ + this.brokenForkContext = ForkContext.newEmpty(forkContext); + } +} + +/** + * Represents the context for `ChainExpression` nodes. + */ +class ChainContext { + /** + * Creates a new instance. + * @param {ChainContext} upperContext The previous `ChainContext`. + */ + constructor(upperContext) { + /** + * The previous `ChainContext` + * @type {ChainContext} + */ + this.upper = upperContext; + + /** + * The number of choice contexts inside of the `ChainContext`. + * @type {number} + */ + this.choiceContextCount = 0; + } +} + +/** + * Represents a choice in the code path. + * + * Choices are created by logical operators such as `&&`, loops, conditionals, + * and `if` statements. This is the point at which the code path has a choice of + * which direction to go. + * + * The result of a choice might be in the left (test) expression of another choice, + * and in that case, may create a new fork. For example, `a || b` is a choice + * but does not create a new fork because the result of the expression is + * not used as the test expression in another expression. In this case, + * `isForkingAsResult` is false. In the expression `a || b || c`, the `a || b` + * expression appears as the test expression for `|| c`, so the + * result of `a || b` creates a fork because execution may or may not + * continue to `|| c`. `isForkingAsResult` for `a || b` in this case is true + * while `isForkingAsResult` for `|| c` is false. (`isForkingAsResult` is always + * false for `if` statements, conditional expressions, and loops.) + * + * All of the choices except one (`??`) operate on a true/false fork, meaning if + * true go one way and if false go the other (tracked by `trueForkContext` and + * `falseForkContext`). The `??` operator doesn't operate on true/false because + * the left expression is evaluated to be nullish or not, so only if nullish do + * we fork to the right expression (tracked by `nullishForkContext`). + */ +class ChoiceContext { + /** + * Creates a new instance. + * @param {ChoiceContext} upperContext The previous `ChoiceContext`. + * @param {string} kind The kind of choice. If it's a logical or assignment expression, this + * is `"&&"` or `"||"` or `"??"`; if it's an `if` statement or + * conditional expression, this is `"test"`; otherwise, this is `"loop"`. + * @param {boolean} isForkingAsResult Indicates if the result of the choice + * creates a fork. + * @param {ForkContext} forkContext The containing `ForkContext`. + */ + constructor(upperContext, kind, isForkingAsResult, forkContext) { + /** + * The previous `ChoiceContext` + * @type {ChoiceContext} + */ + this.upper = upperContext; + + /** + * The kind of choice. If it's a logical or assignment expression, this + * is `"&&"` or `"||"` or `"??"`; if it's an `if` statement or + * conditional expression, this is `"test"`; otherwise, this is `"loop"`. + * @type {string} + */ + this.kind = kind; + + /** + * Indicates if the result of the choice forks the code path. + * @type {boolean} + */ + this.isForkingAsResult = isForkingAsResult; + + /** + * The fork context for the `true` path of the choice. + * @type {ForkContext} + */ + this.trueForkContext = ForkContext.newEmpty(forkContext); + + /** + * The fork context for the `false` path of the choice. + * @type {ForkContext} + */ + this.falseForkContext = ForkContext.newEmpty(forkContext); + + /** + * The fork context for when the choice result is `null` or `undefined`. + * @type {ForkContext} + */ + this.nullishForkContext = ForkContext.newEmpty(forkContext); + + /** + * Indicates if any of `trueForkContext`, `falseForkContext`, or + * `nullishForkContext` have been updated with segments from a child context. + * @type {boolean} + */ + this.processed = false; + } +} + +/** + * Base class for all loop contexts. + */ +class LoopContextBase { + /** + * Creates a new instance. + * @param {LoopContext|null} upperContext The previous `LoopContext`. + * @param {string} type The AST node's `type` for the loop. + * @param {string|null} label The label for the loop from an enclosing `LabeledStatement`. + * @param {BreakContext} breakContext The context for breaking the loop. + */ + constructor(upperContext, type, label, breakContext) { + /** + * The previous `LoopContext`. + * @type {LoopContext} + */ + this.upper = upperContext; + + /** + * The AST node's `type` for the loop. + * @type {string} + */ + this.type = type; + + /** + * The label for the loop from an enclosing `LabeledStatement`. + * @type {string|null} + */ + this.label = label; + + /** + * The fork context for when `break` is encountered. + * @type {ForkContext} + */ + this.brokenForkContext = breakContext.brokenForkContext; + } +} + +/** + * Represents the context for a `while` loop. + */ +class WhileLoopContext extends LoopContextBase { + /** + * Creates a new instance. + * @param {LoopContext|null} upperContext The previous `LoopContext`. + * @param {string|null} label The label for the loop from an enclosing `LabeledStatement`. + * @param {BreakContext} breakContext The context for breaking the loop. + */ + constructor(upperContext, label, breakContext) { + super(upperContext, "WhileStatement", label, breakContext); + + /** + * The hardcoded literal boolean test condition for + * the loop. Used to catch infinite or skipped loops. + * @type {boolean|undefined} + */ + this.test = void 0; + + /** + * The segments representing the test condition where `continue` will + * jump to. The test condition will typically have just one segment but + * it's possible for there to be more than one. + * @type {Array|null} + */ + this.continueDestSegments = null; + } +} + +/** + * Represents the context for a `do-while` loop. + */ +class DoWhileLoopContext extends LoopContextBase { + /** + * Creates a new instance. + * @param {LoopContext|null} upperContext The previous `LoopContext`. + * @param {string|null} label The label for the loop from an enclosing `LabeledStatement`. + * @param {BreakContext} breakContext The context for breaking the loop. + * @param {ForkContext} forkContext The enclosing fork context. + */ + constructor(upperContext, label, breakContext, forkContext) { + super(upperContext, "DoWhileStatement", label, breakContext); + + /** + * The hardcoded literal boolean test condition for + * the loop. Used to catch infinite or skipped loops. + * @type {boolean|undefined} + */ + this.test = void 0; + + /** + * The segments at the start of the loop body. This is the only loop + * where the test comes at the end, so the first iteration always + * happens and we need a reference to the first statements. + * @type {Array|null} + */ + this.entrySegments = null; + + /** + * The fork context to follow when a `continue` is found. + * @type {ForkContext} + */ + this.continueForkContext = ForkContext.newEmpty(forkContext); + } +} + +/** + * Represents the context for a `for` loop. + */ +class ForLoopContext extends LoopContextBase { + /** + * Creates a new instance. + * @param {LoopContext|null} upperContext The previous `LoopContext`. + * @param {string|null} label The label for the loop from an enclosing `LabeledStatement`. + * @param {BreakContext} breakContext The context for breaking the loop. + */ + constructor(upperContext, label, breakContext) { + super(upperContext, "ForStatement", label, breakContext); + + /** + * The hardcoded literal boolean test condition for + * the loop. Used to catch infinite or skipped loops. + * @type {boolean|undefined} + */ + this.test = void 0; + + /** + * The end of the init expression. This may change during the lifetime + * of the instance as we traverse the loop because some loops don't have + * an init expression. + * @type {Array|null} + */ + this.endOfInitSegments = null; + + /** + * The start of the test expression. This may change during the lifetime + * of the instance as we traverse the loop because some loops don't have + * a test expression. + * @type {Array|null} + */ + this.testSegments = null; + + /** + * The end of the test expression. This may change during the lifetime + * of the instance as we traverse the loop because some loops don't have + * a test expression. + * @type {Array|null} + */ + this.endOfTestSegments = null; + + /** + * The start of the update expression. This may change during the lifetime + * of the instance as we traverse the loop because some loops don't have + * an update expression. + * @type {Array|null} + */ + this.updateSegments = null; + + /** + * The end of the update expression. This may change during the lifetime + * of the instance as we traverse the loop because some loops don't have + * an update expression. + * @type {Array|null} + */ + this.endOfUpdateSegments = null; + + /** + * The segments representing the test condition where `continue` will + * jump to. The test condition will typically have just one segment but + * it's possible for there to be more than one. This may change during the + * lifetime of the instance as we traverse the loop because some loops + * don't have an update expression. When there is an update expression, this + * will end up pointing to that expression; otherwise it will end up pointing + * to the test expression. + * @type {Array|null} + */ + this.continueDestSegments = null; + } +} + +/** + * Represents the context for a `for-in` loop. + * + * Terminology: + * - "left" means the part of the loop to the left of the `in` keyword. For + * example, in `for (var x in y)`, the left is `var x`. + * - "right" means the part of the loop to the right of the `in` keyword. For + * example, in `for (var x in y)`, the right is `y`. + */ +class ForInLoopContext extends LoopContextBase { + /** + * Creates a new instance. + * @param {LoopContext|null} upperContext The previous `LoopContext`. + * @param {string|null} label The label for the loop from an enclosing `LabeledStatement`. + * @param {BreakContext} breakContext The context for breaking the loop. + */ + constructor(upperContext, label, breakContext) { + super(upperContext, "ForInStatement", label, breakContext); + + /** + * The segments that came immediately before the start of the loop. + * This allows you to traverse backwards out of the loop into the + * surrounding code. This is necessary to evaluate the right expression + * correctly, as it must be evaluated in the same way as the left + * expression, but the pointer to these segments would otherwise be + * lost if not stored on the instance. Once the right expression has + * been evaluated, this property is no longer used. + * @type {Array|null} + */ + this.prevSegments = null; + + /** + * Segments representing the start of everything to the left of the + * `in` keyword. This can be used to move forward towards + * `endOfLeftSegments`. `leftSegments` and `endOfLeftSegments` are + * effectively the head and tail of a doubly-linked list. + * @type {Array|null} + */ + this.leftSegments = null; + + /** + * Segments representing the end of everything to the left of the + * `in` keyword. This can be used to move backward towards `leftSegments`. + * `leftSegments` and `endOfLeftSegments` are effectively the head + * and tail of a doubly-linked list. + * @type {Array|null} + */ + this.endOfLeftSegments = null; + + /** + * The segments representing the left expression where `continue` will + * jump to. In `for-in` loops, `continue` must always re-execute the + * left expression each time through the loop. This contains the same + * segments as `leftSegments`, but is duplicated here so each loop + * context has the same property pointing to where `continue` should + * end up. + * @type {Array|null} + */ + this.continueDestSegments = null; + } +} + +/** + * Represents the context for a `for-of` loop. + */ +class ForOfLoopContext extends LoopContextBase { + /** + * Creates a new instance. + * @param {LoopContext|null} upperContext The previous `LoopContext`. + * @param {string|null} label The label for the loop from an enclosing `LabeledStatement`. + * @param {BreakContext} breakContext The context for breaking the loop. + */ + constructor(upperContext, label, breakContext) { + super(upperContext, "ForOfStatement", label, breakContext); + + /** + * The segments that came immediately before the start of the loop. + * This allows you to traverse backwards out of the loop into the + * surrounding code. This is necessary to evaluate the right expression + * correctly, as it must be evaluated in the same way as the left + * expression, but the pointer to these segments would otherwise be + * lost if not stored on the instance. Once the right expression has + * been evaluated, this property is no longer used. + * @type {Array|null} + */ + this.prevSegments = null; + + /** + * Segments representing the start of everything to the left of the + * `of` keyword. This can be used to move forward towards + * `endOfLeftSegments`. `leftSegments` and `endOfLeftSegments` are + * effectively the head and tail of a doubly-linked list. + * @type {Array|null} + */ + this.leftSegments = null; + + /** + * Segments representing the end of everything to the left of the + * `of` keyword. This can be used to move backward towards `leftSegments`. + * `leftSegments` and `endOfLeftSegments` are effectively the head + * and tail of a doubly-linked list. + * @type {Array|null} + */ + this.endOfLeftSegments = null; + + /** + * The segments representing the left expression where `continue` will + * jump to. In `for-in` loops, `continue` must always re-execute the + * left expression each time through the loop. This contains the same + * segments as `leftSegments`, but is duplicated here so each loop + * context has the same property pointing to where `continue` should + * end up. + * @type {Array|null} + */ + this.continueDestSegments = null; + } +} + +/** + * Represents the context for any loop. + * @typedef {WhileLoopContext|DoWhileLoopContext|ForLoopContext|ForInLoopContext|ForOfLoopContext} LoopContext + */ + +/** + * Represents the context for a `switch` statement. + */ +class SwitchContext { + /** + * Creates a new instance. + * @param {SwitchContext} upperContext The previous context. + * @param {boolean} hasCase Indicates if there is at least one `case` statement. + * `default` doesn't count. + */ + constructor(upperContext, hasCase) { + /** + * The previous context. + * @type {SwitchContext} + */ + this.upper = upperContext; + + /** + * Indicates if there is at least one `case` statement. `default` doesn't count. + * @type {boolean} + */ + this.hasCase = hasCase; + + /** + * The `default` keyword. + * @type {Array|null} + */ + this.defaultSegments = null; + + /** + * The default case body starting segments. + * @type {Array|null} + */ + this.defaultBodySegments = null; + + /** + * Indicates if a `default` case and is empty exists. + * @type {boolean} + */ + this.foundEmptyDefault = false; + + /** + * Indicates that a `default` exists and is the last case. + * @type {boolean} + */ + this.lastIsDefault = false; + + /** + * The number of fork contexts created. This is equivalent to the + * number of `case` statements plus a `default` statement (if present). + * @type {number} + */ + this.forkCount = 0; + } +} + +/** + * Represents the context for a `try` statement. + */ +class TryContext { + /** + * Creates a new instance. + * @param {TryContext} upperContext The previous context. + * @param {boolean} hasFinalizer Indicates if the `try` statement has a + * `finally` block. + * @param {ForkContext} forkContext The enclosing fork context. + */ + constructor(upperContext, hasFinalizer, forkContext) { + /** + * The previous context. + * @type {TryContext} + */ + this.upper = upperContext; + + /** + * Indicates if the `try` statement has a `finally` block. + * @type {boolean} + */ + this.hasFinalizer = hasFinalizer; + + /** + * Tracks the traversal position inside of the `try` statement. This is + * used to help determine the context necessary to create paths because + * a `try` statement may or may not have `catch` or `finally` blocks, + * and code paths behave differently in those blocks. + * @type {"try"|"catch"|"finally"} + */ + this.position = "try"; + + /** + * If the `try` statement has a `finally` block, this affects how a + * `return` statement behaves in the `try` block. Without `finally`, + * `return` behaves as usual and doesn't require a fork; with `finally`, + * `return` forks into the `finally` block, so we need a fork context + * to track it. + * @type {ForkContext|null} + */ + this.returnedForkContext = hasFinalizer + ? ForkContext.newEmpty(forkContext) + : null; + + /** + * When a `throw` occurs inside of a `try` block, the code path forks + * into the `catch` or `finally` blocks, and this fork context tracks + * that path. + * @type {ForkContext} + */ + this.thrownForkContext = ForkContext.newEmpty(forkContext); + + /** + * Indicates if the last segment in the `try` block is reachable. + * @type {boolean} + */ + this.lastOfTryIsReachable = false; + + /** + * Indicates if the last segment in the `catch` block is reachable. + * @type {boolean} + */ + this.lastOfCatchIsReachable = false; + } +} + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Adds given segments into the `dest` array. + * If the `others` array does not include the given segments, adds to the `all` + * array as well. + * + * This adds only reachable and used segments. + * @param {CodePathSegment[]} dest A destination array (`returnedSegments` or `thrownSegments`). + * @param {CodePathSegment[]} others Another destination array (`returnedSegments` or `thrownSegments`). + * @param {CodePathSegment[]} all The unified destination array (`finalSegments`). + * @param {CodePathSegment[]} segments Segments to add. + * @returns {void} + */ +function addToReturnedOrThrown(dest, others, all, segments) { + for (let i = 0; i < segments.length; ++i) { + const segment = segments[i]; + + dest.push(segment); + if (!others.includes(segment)) { + all.push(segment); + } + } +} + +/** + * Gets a loop context for a `continue` statement based on a given label. + * @param {CodePathState} state The state to search within. + * @param {string|null} label The label of a `continue` statement. + * @returns {LoopContext} A loop-context for a `continue` statement. + */ +function getContinueContext(state, label) { + if (!label) { + return state.loopContext; + } + + let context = state.loopContext; + + while (context) { + if (context.label === label) { + return context; + } + context = context.upper; + } + + /* c8 ignore next */ + return null; +} + +/** + * Gets a context for a `break` statement. + * @param {CodePathState} state The state to search within. + * @param {string|null} label The label of a `break` statement. + * @returns {BreakContext} A context for a `break` statement. + */ +function getBreakContext(state, label) { + let context = state.breakContext; + + while (context) { + if (label ? context.label === label : context.breakable) { + return context; + } + context = context.upper; + } + + /* c8 ignore next */ + return null; +} + +/** + * Gets a context for a `return` statement. There is just one special case: + * if there is a `try` statement with a `finally` block, because that alters + * how `return` behaves; otherwise, this just passes through the given state. + * @param {CodePathState} state The state to search within + * @returns {TryContext|CodePathState} A context for a `return` statement. + */ +function getReturnContext(state) { + let context = state.tryContext; + + while (context) { + if (context.hasFinalizer && context.position !== "finally") { + return context; + } + context = context.upper; + } + + return state; +} + +/** + * Gets a context for a `throw` statement. There is just one special case: + * if there is a `try` statement with a `finally` block and we are inside of + * a `catch` because that changes how `throw` behaves; otherwise, this just + * passes through the given state. + * @param {CodePathState} state The state to search within. + * @returns {TryContext|CodePathState} A context for a `throw` statement. + */ +function getThrowContext(state) { + let context = state.tryContext; + + while (context) { + if ( + context.position === "try" || + (context.hasFinalizer && context.position === "catch") + ) { + return context; + } + context = context.upper; + } + + return state; +} + +/** + * Removes a given value from a given array. + * @param {any[]} elements An array to remove the specific element. + * @param {any} value The value to be removed. + * @returns {void} + */ +function removeFromArray(elements, value) { + elements.splice(elements.indexOf(value), 1); +} + +/** + * Disconnect given segments. + * + * This is used in a process for switch statements. + * If there is the "default" chunk before other cases, the order is different + * between node's and running's. + * @param {CodePathSegment[]} prevSegments Forward segments to disconnect. + * @param {CodePathSegment[]} nextSegments Backward segments to disconnect. + * @returns {void} + */ +function disconnectSegments(prevSegments, nextSegments) { + for (let i = 0; i < prevSegments.length; ++i) { + const prevSegment = prevSegments[i]; + const nextSegment = nextSegments[i]; + + removeFromArray(prevSegment.nextSegments, nextSegment); + removeFromArray(prevSegment.allNextSegments, nextSegment); + removeFromArray(nextSegment.prevSegments, prevSegment); + removeFromArray(nextSegment.allPrevSegments, prevSegment); + } +} + +/** + * Creates looping path between two arrays of segments, ensuring that there are + * paths going between matching segments in the arrays. + * @param {CodePathState} state The state to operate on. + * @param {CodePathSegment[]} unflattenedFromSegments Segments which are source. + * @param {CodePathSegment[]} unflattenedToSegments Segments which are destination. + * @returns {void} + */ +function makeLooped(state, unflattenedFromSegments, unflattenedToSegments) { + const fromSegments = CodePathSegment.flattenUnusedSegments( + unflattenedFromSegments, + ); + const toSegments = CodePathSegment.flattenUnusedSegments( + unflattenedToSegments, + ); + const end = Math.min(fromSegments.length, toSegments.length); + + /* + * This loop effectively updates a doubly-linked list between two collections + * of segments making sure that segments in the same array indices are + * combined to create a path. + */ + for (let i = 0; i < end; ++i) { + // get the segments in matching array indices + const fromSegment = fromSegments[i]; + const toSegment = toSegments[i]; + + /* + * If the destination segment is reachable, then create a path from the + * source segment to the destination segment. + */ + if (toSegment.reachable) { + fromSegment.nextSegments.push(toSegment); + } + + /* + * If the source segment is reachable, then create a path from the + * destination segment back to the source segment. + */ + if (fromSegment.reachable) { + toSegment.prevSegments.push(fromSegment); + } + + /* + * Also update the arrays that don't care if the segments are reachable + * or not. This should always happen regardless of anything else. + */ + fromSegment.allNextSegments.push(toSegment); + toSegment.allPrevSegments.push(fromSegment); + + /* + * If the destination segment has at least two previous segments in its + * path then that means there was one previous segment before this iteration + * of the loop was executed. So, we need to mark the source segment as + * looped. + */ + if (toSegment.allPrevSegments.length >= 2) { + CodePathSegment.markPrevSegmentAsLooped(toSegment, fromSegment); + } + + // let the code path analyzer know that there's been a loop created + state.notifyLooped(fromSegment, toSegment); + } +} + +/** + * Finalizes segments of `test` chunk of a ForStatement. + * + * - Adds `false` paths to paths which are leaving from the loop. + * - Sets `true` paths to paths which go to the body. + * @param {LoopContext} context A loop context to modify. + * @param {ChoiceContext} choiceContext A choice context of this loop. + * @param {CodePathSegment[]} head The current head paths. + * @returns {void} + */ +function finalizeTestSegmentsOfFor(context, choiceContext, head) { + /* + * If this choice context doesn't already contain paths from a + * child context, then add the current head to each potential path. + */ + if (!choiceContext.processed) { + choiceContext.trueForkContext.add(head); + choiceContext.falseForkContext.add(head); + choiceContext.nullishForkContext.add(head); + } + + /* + * If the test condition isn't a hardcoded truthy value, then `break` + * must follow the same path as if the test condition is false. To represent + * that, we append the path for when the loop test is false (represented by + * `falseForkContext`) to the `brokenForkContext`. + */ + if (context.test !== true) { + context.brokenForkContext.addAll(choiceContext.falseForkContext); + } + + context.endOfTestSegments = choiceContext.trueForkContext.makeNext(0, -1); +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * A class which manages state to analyze code paths. + */ +class CodePathState { + /** + * Creates a new instance. + * @param {IdGenerator} idGenerator An id generator to generate id for code + * path segments. + * @param {Function} onLooped A callback function to notify looping. + */ + constructor(idGenerator, onLooped) { + /** + * The ID generator to use when creating new segments. + * @type {IdGenerator} + */ + this.idGenerator = idGenerator; + + /** + * A callback function to call when there is a loop. + * @type {Function} + */ + this.notifyLooped = onLooped; + + /** + * The root fork context for this state. + * @type {ForkContext} + */ + this.forkContext = ForkContext.newRoot(idGenerator); + + /** + * Context for logical expressions, conditional expressions, `if` statements, + * and loops. + * @type {ChoiceContext} + */ + this.choiceContext = null; + + /** + * Context for `switch` statements. + * @type {SwitchContext} + */ + this.switchContext = null; + + /** + * Context for `try` statements. + * @type {TryContext} + */ + this.tryContext = null; + + /** + * Context for loop statements. + * @type {LoopContext} + */ + this.loopContext = null; + + /** + * Context for `break` statements. + * @type {BreakContext} + */ + this.breakContext = null; + + /** + * Context for `ChainExpression` nodes. + * @type {ChainContext} + */ + this.chainContext = null; + + /** + * An array that tracks the current segments in the state. The array + * starts empty and segments are added with each `onCodePathSegmentStart` + * event and removed with each `onCodePathSegmentEnd` event. Effectively, + * this is tracking the code path segment traversal as the state is + * modified. + * @type {Array} + */ + this.currentSegments = []; + + /** + * Tracks the starting segment for this path. This value never changes. + * @type {CodePathSegment} + */ + this.initialSegment = this.forkContext.head[0]; + + /** + * The final segments of the code path which are either `return` or `throw`. + * This is a union of the segments in `returnedForkContext` and `thrownForkContext`. + * @type {Array} + */ + this.finalSegments = []; + + /** + * The final segments of the code path which are `return`. These + * segments are also contained in `finalSegments`. + * @type {Array} + */ + this.returnedForkContext = []; + + /** + * The final segments of the code path which are `throw`. These + * segments are also contained in `finalSegments`. + * @type {Array} + */ + this.thrownForkContext = []; + + /* + * We add an `add` method so that these look more like fork contexts and + * can be used interchangeably when a fork context is needed to add more + * segments to a path. + * + * Ultimately, we want anything added to `returned` or `thrown` to also + * be added to `final`. We only add reachable and used segments to these + * arrays. + */ + const final = this.finalSegments; + const returned = this.returnedForkContext; + const thrown = this.thrownForkContext; + + returned.add = addToReturnedOrThrown.bind( + null, + returned, + thrown, + final, + ); + thrown.add = addToReturnedOrThrown.bind(null, thrown, returned, final); + } + + /** + * A passthrough property exposing the current pointer as part of the API. + * @type {CodePathSegment[]} + */ + get headSegments() { + return this.forkContext.head; + } + + /** + * The parent forking context. + * This is used for the root of new forks. + * @type {ForkContext} + */ + get parentForkContext() { + const current = this.forkContext; + + return current && current.upper; + } + + /** + * Creates and stacks new forking context. + * @param {boolean} forkLeavingPath A flag which shows being in a + * "finally" block. + * @returns {ForkContext} The created context. + */ + pushForkContext(forkLeavingPath) { + this.forkContext = ForkContext.newEmpty( + this.forkContext, + forkLeavingPath, + ); + + return this.forkContext; + } + + /** + * Pops and merges the last forking context. + * @returns {ForkContext} The last context. + */ + popForkContext() { + const lastContext = this.forkContext; + + this.forkContext = lastContext.upper; + this.forkContext.replaceHead(lastContext.makeNext(0, -1)); + + return lastContext; + } + + /** + * Creates a new path. + * @returns {void} + */ + forkPath() { + this.forkContext.add(this.parentForkContext.makeNext(-1, -1)); + } + + /** + * Creates a bypass path. + * This is used for such as IfStatement which does not have "else" chunk. + * @returns {void} + */ + forkBypassPath() { + this.forkContext.add(this.parentForkContext.head); + } + + //-------------------------------------------------------------------------- + // ConditionalExpression, LogicalExpression, IfStatement + //-------------------------------------------------------------------------- + + /** + * Creates a context for ConditionalExpression, LogicalExpression, AssignmentExpression (logical assignments only), + * IfStatement, WhileStatement, DoWhileStatement, or ForStatement. + * + * LogicalExpressions have cases that it goes different paths between the + * `true` case and the `false` case. + * + * For Example: + * + * if (a || b) { + * foo(); + * } else { + * bar(); + * } + * + * In this case, `b` is evaluated always in the code path of the `else` + * block, but it's not so in the code path of the `if` block. + * So there are 3 paths. + * + * a -> foo(); + * a -> b -> foo(); + * a -> b -> bar(); + * @param {string} kind A kind string. + * If the new context is LogicalExpression's or AssignmentExpression's, this is `"&&"` or `"||"` or `"??"`. + * If it's IfStatement's or ConditionalExpression's, this is `"test"`. + * Otherwise, this is `"loop"`. + * @param {boolean} isForkingAsResult Indicates if the result of the choice + * creates a fork. + * @returns {void} + */ + pushChoiceContext(kind, isForkingAsResult) { + this.choiceContext = new ChoiceContext( + this.choiceContext, + kind, + isForkingAsResult, + this.forkContext, + ); + } + + /** + * Pops the last choice context and finalizes it. + * This is called upon leaving a node that represents a choice. + * @throws {Error} (Unreachable.) + * @returns {ChoiceContext} The popped context. + */ + popChoiceContext() { + const poppedChoiceContext = this.choiceContext; + const forkContext = this.forkContext; + const head = forkContext.head; + + this.choiceContext = poppedChoiceContext.upper; + + switch (poppedChoiceContext.kind) { + case "&&": + case "||": + case "??": + /* + * The `head` are the path of the right-hand operand. + * If we haven't previously added segments from child contexts, + * then we add these segments to all possible forks. + */ + if (!poppedChoiceContext.processed) { + poppedChoiceContext.trueForkContext.add(head); + poppedChoiceContext.falseForkContext.add(head); + poppedChoiceContext.nullishForkContext.add(head); + } + + /* + * If this context is the left (test) expression for another choice + * context, such as `a || b` in the expression `a || b || c`, + * then we take the segments for this context and move them up + * to the parent context. + */ + if (poppedChoiceContext.isForkingAsResult) { + const parentContext = this.choiceContext; + + parentContext.trueForkContext.addAll( + poppedChoiceContext.trueForkContext, + ); + parentContext.falseForkContext.addAll( + poppedChoiceContext.falseForkContext, + ); + parentContext.nullishForkContext.addAll( + poppedChoiceContext.nullishForkContext, + ); + parentContext.processed = true; + + // Exit early so we don't collapse all paths into one. + return poppedChoiceContext; + } + + break; + + case "test": + if (!poppedChoiceContext.processed) { + /* + * The head segments are the path of the `if` block here. + * Updates the `true` path with the end of the `if` block. + */ + poppedChoiceContext.trueForkContext.clear(); + poppedChoiceContext.trueForkContext.add(head); + } else { + /* + * The head segments are the path of the `else` block here. + * Updates the `false` path with the end of the `else` + * block. + */ + poppedChoiceContext.falseForkContext.clear(); + poppedChoiceContext.falseForkContext.add(head); + } + + break; + + case "loop": + /* + * Loops are addressed in `popLoopContext()` so just return + * the context without modification. + */ + return poppedChoiceContext; + + /* c8 ignore next */ + default: + throw new Error("unreachable"); + } + + /* + * Merge the true path with the false path to create a single path. + */ + const combinedForkContext = poppedChoiceContext.trueForkContext; + + combinedForkContext.addAll(poppedChoiceContext.falseForkContext); + forkContext.replaceHead(combinedForkContext.makeNext(0, -1)); + + return poppedChoiceContext; + } + + /** + * Creates a code path segment to represent right-hand operand of a logical + * expression. + * This is called in the preprocessing phase when entering a node. + * @throws {Error} (Unreachable.) + * @returns {void} + */ + makeLogicalRight() { + const currentChoiceContext = this.choiceContext; + const forkContext = this.forkContext; + + if (currentChoiceContext.processed) { + /* + * This context was already assigned segments from a child + * choice context. In this case, we are concerned only about + * the path that does not short-circuit and so ends up on the + * right-hand operand of the logical expression. + */ + let prevForkContext; + + switch (currentChoiceContext.kind) { + case "&&": // if true then go to the right-hand side. + prevForkContext = currentChoiceContext.trueForkContext; + break; + case "||": // if false then go to the right-hand side. + prevForkContext = currentChoiceContext.falseForkContext; + break; + case "??": // Both true/false can short-circuit, so needs the third path to go to the right-hand side. That's nullishForkContext. + prevForkContext = currentChoiceContext.nullishForkContext; + break; + default: + throw new Error("unreachable"); + } + + /* + * Create the segment for the right-hand operand of the logical expression + * and adjust the fork context pointer to point there. The right-hand segment + * is added at the end of all segments in `prevForkContext`. + */ + forkContext.replaceHead(prevForkContext.makeNext(0, -1)); + + /* + * We no longer need this list of segments. + * + * Reset `processed` because we've removed the segments from the child + * choice context. This allows `popChoiceContext()` to continue adding + * segments later. + */ + prevForkContext.clear(); + currentChoiceContext.processed = false; + } else { + /* + * This choice context was not assigned segments from a child + * choice context, which means that it's a terminal logical + * expression. + * + * `head` is the segments for the left-hand operand of the + * logical expression. + * + * Each of the fork contexts below are empty at this point. We choose + * the path(s) that will short-circuit and add the segment for the + * left-hand operand to it. Ultimately, this will be the only segment + * in that path due to the short-circuting, so we are just seeding + * these paths to start. + */ + switch (currentChoiceContext.kind) { + case "&&": + /* + * In most contexts, when a && expression evaluates to false, + * it short circuits, so we need to account for that by setting + * the `falseForkContext` to the left operand. + * + * When a && expression is the left-hand operand for a ?? + * expression, such as `(a && b) ?? c`, a nullish value will + * also short-circuit in a different way than a false value, + * so we also set the `nullishForkContext` to the left operand. + * This path is only used with a ?? expression and is thrown + * away for any other type of logical expression, so it's safe + * to always add. + */ + currentChoiceContext.falseForkContext.add(forkContext.head); + currentChoiceContext.nullishForkContext.add( + forkContext.head, + ); + break; + case "||": // the true path can short-circuit. + currentChoiceContext.trueForkContext.add(forkContext.head); + break; + case "??": // both can short-circuit. + currentChoiceContext.trueForkContext.add(forkContext.head); + currentChoiceContext.falseForkContext.add(forkContext.head); + break; + default: + throw new Error("unreachable"); + } + + /* + * Create the segment for the right-hand operand of the logical expression + * and adjust the fork context pointer to point there. + */ + forkContext.replaceHead(forkContext.makeNext(-1, -1)); + } + } + + /** + * Makes a code path segment of the `if` block. + * @returns {void} + */ + makeIfConsequent() { + const context = this.choiceContext; + const forkContext = this.forkContext; + + /* + * If any result were not transferred from child contexts, + * this sets the head segments to both cases. + * The head segments are the path of the test expression. + */ + if (!context.processed) { + context.trueForkContext.add(forkContext.head); + context.falseForkContext.add(forkContext.head); + context.nullishForkContext.add(forkContext.head); + } + + context.processed = false; + + // Creates new path from the `true` case. + forkContext.replaceHead(context.trueForkContext.makeNext(0, -1)); + } + + /** + * Makes a code path segment of the `else` block. + * @returns {void} + */ + makeIfAlternate() { + const context = this.choiceContext; + const forkContext = this.forkContext; + + /* + * The head segments are the path of the `if` block. + * Updates the `true` path with the end of the `if` block. + */ + context.trueForkContext.clear(); + context.trueForkContext.add(forkContext.head); + context.processed = true; + + // Creates new path from the `false` case. + forkContext.replaceHead(context.falseForkContext.makeNext(0, -1)); + } + + //-------------------------------------------------------------------------- + // ChainExpression + //-------------------------------------------------------------------------- + + /** + * Pushes a new `ChainExpression` context to the stack. This method is + * called when entering a `ChainExpression` node. A chain context is used to + * count forking in the optional chain then merge them on the exiting from the + * `ChainExpression` node. + * @returns {void} + */ + pushChainContext() { + this.chainContext = new ChainContext(this.chainContext); + } + + /** + * Pop a `ChainExpression` context from the stack. This method is called on + * exiting from each `ChainExpression` node. This merges all forks of the + * last optional chaining. + * @returns {void} + */ + popChainContext() { + const context = this.chainContext; + + this.chainContext = context.upper; + + // pop all choice contexts of this. + for (let i = context.choiceContextCount; i > 0; --i) { + this.popChoiceContext(); + } + } + + /** + * Create a choice context for optional access. + * This method is called on entering to each `(Call|Member)Expression[optional=true]` node. + * This creates a choice context as similar to `LogicalExpression[operator="??"]` node. + * @returns {void} + */ + makeOptionalNode() { + if (this.chainContext) { + this.chainContext.choiceContextCount += 1; + this.pushChoiceContext("??", false); + } + } + + /** + * Create a fork. + * This method is called on entering to the `arguments|property` property of each `(Call|Member)Expression` node. + * @returns {void} + */ + makeOptionalRight() { + if (this.chainContext) { + this.makeLogicalRight(); + } + } + + //-------------------------------------------------------------------------- + // SwitchStatement + //-------------------------------------------------------------------------- + + /** + * Creates a context object of SwitchStatement and stacks it. + * @param {boolean} hasCase `true` if the switch statement has one or more + * case parts. + * @param {string|null} label The label text. + * @returns {void} + */ + pushSwitchContext(hasCase, label) { + this.switchContext = new SwitchContext(this.switchContext, hasCase); + this.pushBreakContext(true, label); + } + + /** + * Pops the last context of SwitchStatement and finalizes it. + * + * - Disposes all forking stack for `case` and `default`. + * - Creates the next code path segment from `context.brokenForkContext`. + * - If the last `SwitchCase` node is not a `default` part, creates a path + * to the `default` body. + * @returns {void} + */ + popSwitchContext() { + const context = this.switchContext; + + this.switchContext = context.upper; + + const forkContext = this.forkContext; + const brokenForkContext = this.popBreakContext().brokenForkContext; + + if (context.forkCount === 0) { + /* + * When there is only one `default` chunk and there is one or more + * `break` statements, even if forks are nothing, it needs to merge + * those. + */ + if (!brokenForkContext.empty) { + brokenForkContext.add(forkContext.makeNext(-1, -1)); + forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); + } + + return; + } + + const lastSegments = forkContext.head; + + this.forkBypassPath(); + const lastCaseSegments = forkContext.head; + + /* + * `brokenForkContext` is used to make the next segment. + * It must add the last segment into `brokenForkContext`. + */ + brokenForkContext.add(lastSegments); + + /* + * Any value that doesn't match a `case` test should flow to the default + * case. That happens normally when the default case is last in the `switch`, + * but if it's not, we need to rewire some of the paths to be correct. + */ + if (!context.lastIsDefault) { + if (context.defaultBodySegments) { + /* + * There is a non-empty default case, so remove the path from the `default` + * label to its body for an accurate representation. + */ + disconnectSegments( + context.defaultSegments, + context.defaultBodySegments, + ); + + /* + * Connect the path from the last non-default case to the body of the + * default case. + */ + makeLooped(this, lastCaseSegments, context.defaultBodySegments); + } else { + /* + * There is no default case, so we treat this as if the last case + * had a `break` in it. + */ + brokenForkContext.add(lastCaseSegments); + } + } + + // Traverse up to the original fork context for the `switch` statement + for (let i = 0; i < context.forkCount; ++i) { + this.forkContext = this.forkContext.upper; + } + + /* + * Creates a path from all `brokenForkContext` paths. + * This is a path after `switch` statement. + */ + this.forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); + } + + /** + * Makes a code path segment for a `SwitchCase` node. + * @param {boolean} isCaseBodyEmpty `true` if the body is empty. + * @param {boolean} isDefaultCase `true` if the body is the default case. + * @returns {void} + */ + makeSwitchCaseBody(isCaseBodyEmpty, isDefaultCase) { + const context = this.switchContext; + + if (!context.hasCase) { + return; + } + + /* + * Merge forks. + * The parent fork context has two segments. + * Those are from the current `case` and the body of the previous case. + */ + const parentForkContext = this.forkContext; + const forkContext = this.pushForkContext(); + + forkContext.add(parentForkContext.makeNext(0, -1)); + + /* + * Add information about the default case. + * + * The purpose of this is to identify the starting segments for the + * default case to make sure there is a path there. + */ + if (isDefaultCase) { + /* + * This is the default case in the `switch`. + * + * We first save the current pointer as `defaultSegments` to point + * to the `default` keyword. + */ + context.defaultSegments = parentForkContext.head; + + /* + * If the body of the case is empty then we just set + * `foundEmptyDefault` to true; otherwise, we save a reference + * to the current pointer as `defaultBodySegments`. + */ + if (isCaseBodyEmpty) { + context.foundEmptyDefault = true; + } else { + context.defaultBodySegments = forkContext.head; + } + } else { + /* + * This is not the default case in the `switch`. + * + * If it's not empty and there is already an empty default case found, + * that means the default case actually comes before this case, + * and that it will fall through to this case. So, we can now + * ignore the previous default case (reset `foundEmptyDefault` to false) + * and set `defaultBodySegments` to the current segments because this is + * effectively the new default case. + */ + if (!isCaseBodyEmpty && context.foundEmptyDefault) { + context.foundEmptyDefault = false; + context.defaultBodySegments = forkContext.head; + } + } + + // keep track if the default case ends up last + context.lastIsDefault = isDefaultCase; + context.forkCount += 1; + } + + //-------------------------------------------------------------------------- + // TryStatement + //-------------------------------------------------------------------------- + + /** + * Creates a context object of TryStatement and stacks it. + * @param {boolean} hasFinalizer `true` if the try statement has a + * `finally` block. + * @returns {void} + */ + pushTryContext(hasFinalizer) { + this.tryContext = new TryContext( + this.tryContext, + hasFinalizer, + this.forkContext, + ); + } + + /** + * Pops the last context of TryStatement and finalizes it. + * @returns {void} + */ + popTryContext() { + const context = this.tryContext; + + this.tryContext = context.upper; + + /* + * If we're inside the `catch` block, that means there is no `finally`, + * so we can process the `try` and `catch` blocks the simple way and + * merge their two paths. + */ + if (context.position === "catch") { + this.popForkContext(); + return; + } + + /* + * The following process is executed only when there is a `finally` + * block. + */ + + const originalReturnedForkContext = context.returnedForkContext; + const originalThrownForkContext = context.thrownForkContext; + + // no `return` or `throw` in `try` or `catch` so there's nothing left to do + if ( + originalReturnedForkContext.empty && + originalThrownForkContext.empty + ) { + return; + } + + /* + * The following process is executed only when there is a `finally` + * block and there was a `return` or `throw` in the `try` or `catch` + * blocks. + */ + + // Separate head to normal paths and leaving paths. + const headSegments = this.forkContext.head; + + this.forkContext = this.forkContext.upper; + const normalSegments = headSegments.slice( + 0, + (headSegments.length / 2) | 0, + ); + const leavingSegments = headSegments.slice( + (headSegments.length / 2) | 0, + ); + + // Forwards the leaving path to upper contexts. + if (!originalReturnedForkContext.empty) { + getReturnContext(this).returnedForkContext.add(leavingSegments); + } + if (!originalThrownForkContext.empty) { + getThrowContext(this).thrownForkContext.add(leavingSegments); + } + + // Sets the normal path as the next. + this.forkContext.replaceHead(normalSegments); + + /* + * If both paths of the `try` block and the `catch` block are + * unreachable, the next path becomes unreachable as well. + */ + if (!context.lastOfTryIsReachable && !context.lastOfCatchIsReachable) { + this.forkContext.makeUnreachable(); + } + } + + /** + * Makes a code path segment for a `catch` block. + * @returns {void} + */ + makeCatchBlock() { + const context = this.tryContext; + const forkContext = this.forkContext; + const originalThrownForkContext = context.thrownForkContext; + + /* + * We are now in a catch block so we need to update the context + * with that information. This includes creating a new fork + * context in case we encounter any `throw` statements here. + */ + context.position = "catch"; + context.thrownForkContext = ForkContext.newEmpty(forkContext); + context.lastOfTryIsReachable = forkContext.reachable; + + // Merge the thrown paths from the `try` and `catch` blocks + originalThrownForkContext.add(forkContext.head); + const thrownSegments = originalThrownForkContext.makeNext(0, -1); + + // Fork to a bypass and the merged thrown path. + this.pushForkContext(); + this.forkBypassPath(); + this.forkContext.add(thrownSegments); + } + + /** + * Makes a code path segment for a `finally` block. + * + * In the `finally` block, parallel paths are created. The parallel paths + * are used as leaving-paths. The leaving-paths are paths from `return` + * statements and `throw` statements in a `try` block or a `catch` block. + * @returns {void} + */ + makeFinallyBlock() { + const context = this.tryContext; + let forkContext = this.forkContext; + const originalReturnedForkContext = context.returnedForkContext; + const originalThrownForContext = context.thrownForkContext; + const headOfLeavingSegments = forkContext.head; + + // Update state. + if (context.position === "catch") { + // Merges two paths from the `try` block and `catch` block. + this.popForkContext(); + forkContext = this.forkContext; + + context.lastOfCatchIsReachable = forkContext.reachable; + } else { + context.lastOfTryIsReachable = forkContext.reachable; + } + + context.position = "finally"; + + /* + * If there was no `return` or `throw` in either the `try` or `catch` + * blocks, then there's no further code paths to create for `finally`. + */ + if ( + originalReturnedForkContext.empty && + originalThrownForContext.empty + ) { + // This path does not leave. + return; + } + + /* + * Create a parallel segment from merging returned and thrown. + * This segment will leave at the end of this `finally` block. + */ + const segments = forkContext.makeNext(-1, -1); + + for (let i = 0; i < forkContext.count; ++i) { + const prevSegsOfLeavingSegment = [headOfLeavingSegments[i]]; + + for ( + let j = 0; + j < originalReturnedForkContext.segmentsList.length; + ++j + ) { + prevSegsOfLeavingSegment.push( + originalReturnedForkContext.segmentsList[j][i], + ); + } + for ( + let j = 0; + j < originalThrownForContext.segmentsList.length; + ++j + ) { + prevSegsOfLeavingSegment.push( + originalThrownForContext.segmentsList[j][i], + ); + } + + segments.push( + CodePathSegment.newNext( + this.idGenerator.next(), + prevSegsOfLeavingSegment, + ), + ); + } + + this.pushForkContext(true); + this.forkContext.add(segments); + } + + /** + * Makes a code path segment from the first throwable node to the `catch` + * block or the `finally` block. + * @returns {void} + */ + makeFirstThrowablePathInTryBlock() { + const forkContext = this.forkContext; + + if (!forkContext.reachable) { + return; + } + + const context = getThrowContext(this); + + if ( + context === this || + context.position !== "try" || + !context.thrownForkContext.empty + ) { + return; + } + + context.thrownForkContext.add(forkContext.head); + forkContext.replaceHead(forkContext.makeNext(-1, -1)); + } + + //-------------------------------------------------------------------------- + // Loop Statements + //-------------------------------------------------------------------------- + + /** + * Creates a context object of a loop statement and stacks it. + * @param {string} type The type of the node which was triggered. One of + * `WhileStatement`, `DoWhileStatement`, `ForStatement`, `ForInStatement`, + * and `ForStatement`. + * @param {string|null} label A label of the node which was triggered. + * @throws {Error} (Unreachable - unknown type.) + * @returns {void} + */ + pushLoopContext(type, label) { + const forkContext = this.forkContext; + + // All loops need a path to account for `break` statements + const breakContext = this.pushBreakContext(true, label); + + switch (type) { + case "WhileStatement": + this.pushChoiceContext("loop", false); + this.loopContext = new WhileLoopContext( + this.loopContext, + label, + breakContext, + ); + break; + + case "DoWhileStatement": + this.pushChoiceContext("loop", false); + this.loopContext = new DoWhileLoopContext( + this.loopContext, + label, + breakContext, + forkContext, + ); + break; + + case "ForStatement": + this.pushChoiceContext("loop", false); + this.loopContext = new ForLoopContext( + this.loopContext, + label, + breakContext, + ); + break; + + case "ForInStatement": + this.loopContext = new ForInLoopContext( + this.loopContext, + label, + breakContext, + ); + break; + + case "ForOfStatement": + this.loopContext = new ForOfLoopContext( + this.loopContext, + label, + breakContext, + ); + break; + + /* c8 ignore next */ + default: + throw new Error(`unknown type: "${type}"`); + } + } + + /** + * Pops the last context of a loop statement and finalizes it. + * @throws {Error} (Unreachable - unknown type.) + * @returns {void} + */ + popLoopContext() { + const context = this.loopContext; + + this.loopContext = context.upper; + + const forkContext = this.forkContext; + const brokenForkContext = this.popBreakContext().brokenForkContext; + + // Creates a looped path. + switch (context.type) { + case "WhileStatement": + case "ForStatement": + this.popChoiceContext(); + + /* + * Creates the path from the end of the loop body up to the + * location where `continue` would jump to. + */ + makeLooped( + this, + forkContext.head, + context.continueDestSegments, + ); + break; + + case "DoWhileStatement": { + const choiceContext = this.popChoiceContext(); + + if (!choiceContext.processed) { + choiceContext.trueForkContext.add(forkContext.head); + choiceContext.falseForkContext.add(forkContext.head); + } + + /* + * If this isn't a hardcoded `true` condition, then `break` + * should continue down the path as if the condition evaluated + * to false. + */ + if (context.test !== true) { + brokenForkContext.addAll(choiceContext.falseForkContext); + } + + /* + * When the condition is true, the loop continues back to the top, + * so create a path from each possible true condition back to the + * top of the loop. + */ + const segmentsList = choiceContext.trueForkContext.segmentsList; + + for (let i = 0; i < segmentsList.length; ++i) { + makeLooped(this, segmentsList[i], context.entrySegments); + } + break; + } + + case "ForInStatement": + case "ForOfStatement": + brokenForkContext.add(forkContext.head); + + /* + * Creates the path from the end of the loop body up to the + * left expression (left of `in` or `of`) of the loop. + */ + makeLooped(this, forkContext.head, context.leftSegments); + break; + + /* c8 ignore next */ + default: + throw new Error("unreachable"); + } + + /* + * If there wasn't a `break` statement in the loop, then we're at + * the end of the loop's path, so we make an unreachable segment + * to mark that. + * + * If there was a `break` statement, then we continue on into the + * `brokenForkContext`. + */ + if (brokenForkContext.empty) { + forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); + } else { + forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); + } + } + + /** + * Makes a code path segment for the test part of a WhileStatement. + * @param {boolean|undefined} test The test value (only when constant). + * @returns {void} + */ + makeWhileTest(test) { + const context = this.loopContext; + const forkContext = this.forkContext; + const testSegments = forkContext.makeNext(0, -1); + + // Update state. + context.test = test; + context.continueDestSegments = testSegments; + forkContext.replaceHead(testSegments); + } + + /** + * Makes a code path segment for the body part of a WhileStatement. + * @returns {void} + */ + makeWhileBody() { + const context = this.loopContext; + const choiceContext = this.choiceContext; + const forkContext = this.forkContext; + + if (!choiceContext.processed) { + choiceContext.trueForkContext.add(forkContext.head); + choiceContext.falseForkContext.add(forkContext.head); + } + + /* + * If this isn't a hardcoded `true` condition, then `break` + * should continue down the path as if the condition evaluated + * to false. + */ + if (context.test !== true) { + context.brokenForkContext.addAll(choiceContext.falseForkContext); + } + forkContext.replaceHead(choiceContext.trueForkContext.makeNext(0, -1)); + } + + /** + * Makes a code path segment for the body part of a DoWhileStatement. + * @returns {void} + */ + makeDoWhileBody() { + const context = this.loopContext; + const forkContext = this.forkContext; + const bodySegments = forkContext.makeNext(-1, -1); + + // Update state. + context.entrySegments = bodySegments; + forkContext.replaceHead(bodySegments); + } + + /** + * Makes a code path segment for the test part of a DoWhileStatement. + * @param {boolean|undefined} test The test value (only when constant). + * @returns {void} + */ + makeDoWhileTest(test) { + const context = this.loopContext; + const forkContext = this.forkContext; + + context.test = test; + + /* + * If there is a `continue` statement in the loop then `continueForkContext` + * won't be empty. We wire up the path from `continue` to the loop + * test condition and then continue the traversal in the root fork context. + */ + if (!context.continueForkContext.empty) { + context.continueForkContext.add(forkContext.head); + const testSegments = context.continueForkContext.makeNext(0, -1); + + forkContext.replaceHead(testSegments); + } + } + + /** + * Makes a code path segment for the test part of a ForStatement. + * @param {boolean|undefined} test The test value (only when constant). + * @returns {void} + */ + makeForTest(test) { + const context = this.loopContext; + const forkContext = this.forkContext; + const endOfInitSegments = forkContext.head; + const testSegments = forkContext.makeNext(-1, -1); + + /* + * Update the state. + * + * The `continueDestSegments` are set to `testSegments` because we + * don't yet know if there is an update expression in this loop. So, + * from what we already know at this point, a `continue` statement + * will jump back to the test expression. + */ + context.test = test; + context.endOfInitSegments = endOfInitSegments; + context.continueDestSegments = context.testSegments = testSegments; + forkContext.replaceHead(testSegments); + } + + /** + * Makes a code path segment for the update part of a ForStatement. + * @returns {void} + */ + makeForUpdate() { + const context = this.loopContext; + const choiceContext = this.choiceContext; + const forkContext = this.forkContext; + + // Make the next paths of the test. + if (context.testSegments) { + finalizeTestSegmentsOfFor(context, choiceContext, forkContext.head); + } else { + context.endOfInitSegments = forkContext.head; + } + + /* + * Update the state. + * + * The `continueDestSegments` are now set to `updateSegments` because we + * know there is an update expression in this loop. So, a `continue` statement + * in the loop will jump to the update expression first, and then to any + * test expression the loop might have. + */ + const updateSegments = forkContext.makeDisconnected(-1, -1); + + context.continueDestSegments = context.updateSegments = updateSegments; + forkContext.replaceHead(updateSegments); + } + + /** + * Makes a code path segment for the body part of a ForStatement. + * @returns {void} + */ + makeForBody() { + const context = this.loopContext; + const choiceContext = this.choiceContext; + const forkContext = this.forkContext; + + /* + * Determine what to do based on which part of the `for` loop are present. + * 1. If there is an update expression, then `updateSegments` is not null and + * we need to assign `endOfUpdateSegments`, and if there is a test + * expression, we then need to create the looped path to get back to + * the test condition. + * 2. If there is no update expression but there is a test expression, + * then we only need to update the test segment information. + * 3. If there is no update expression and no test expression, then we + * just save `endOfInitSegments`. + */ + if (context.updateSegments) { + context.endOfUpdateSegments = forkContext.head; + + /* + * In a `for` loop that has both an update expression and a test + * condition, execution flows from the test expression into the + * loop body, to the update expression, and then back to the test + * expression to determine if the loop should continue. + * + * To account for that, we need to make a path from the end of the + * update expression to the start of the test expression. This is + * effectively what creates the loop in the code path. + */ + if (context.testSegments) { + makeLooped( + this, + context.endOfUpdateSegments, + context.testSegments, + ); + } + } else if (context.testSegments) { + finalizeTestSegmentsOfFor(context, choiceContext, forkContext.head); + } else { + context.endOfInitSegments = forkContext.head; + } + + let bodySegments = context.endOfTestSegments; + + /* + * If there is a test condition, then there `endOfTestSegments` is also + * the start of the loop body. If there isn't a test condition then + * `bodySegments` will be null and we need to look elsewhere to find + * the start of the body. + * + * The body starts at the end of the init expression and ends at the end + * of the update expression, so we use those locations to determine the + * body segments. + */ + if (!bodySegments) { + const prevForkContext = ForkContext.newEmpty(forkContext); + + prevForkContext.add(context.endOfInitSegments); + if (context.endOfUpdateSegments) { + prevForkContext.add(context.endOfUpdateSegments); + } + + bodySegments = prevForkContext.makeNext(0, -1); + } + + /* + * If there was no test condition and no update expression, then + * `continueDestSegments` will be null. In that case, a + * `continue` should skip directly to the body of the loop. + * Otherwise, we want to keep the current `continueDestSegments`. + */ + context.continueDestSegments = + context.continueDestSegments || bodySegments; + + // move pointer to the body + forkContext.replaceHead(bodySegments); + } + + /** + * Makes a code path segment for the left part of a ForInStatement and a + * ForOfStatement. + * @returns {void} + */ + makeForInOfLeft() { + const context = this.loopContext; + const forkContext = this.forkContext; + const leftSegments = forkContext.makeDisconnected(-1, -1); + + // Update state. + context.prevSegments = forkContext.head; + context.leftSegments = context.continueDestSegments = leftSegments; + forkContext.replaceHead(leftSegments); + } + + /** + * Makes a code path segment for the right part of a ForInStatement and a + * ForOfStatement. + * @returns {void} + */ + makeForInOfRight() { + const context = this.loopContext; + const forkContext = this.forkContext; + const temp = ForkContext.newEmpty(forkContext); + + temp.add(context.prevSegments); + const rightSegments = temp.makeNext(-1, -1); + + // Update state. + context.endOfLeftSegments = forkContext.head; + forkContext.replaceHead(rightSegments); + } + + /** + * Makes a code path segment for the body part of a ForInStatement and a + * ForOfStatement. + * @returns {void} + */ + makeForInOfBody() { + const context = this.loopContext; + const forkContext = this.forkContext; + const temp = ForkContext.newEmpty(forkContext); + + temp.add(context.endOfLeftSegments); + const bodySegments = temp.makeNext(-1, -1); + + // Make a path: `right` -> `left`. + makeLooped(this, forkContext.head, context.leftSegments); + + // Update state. + context.brokenForkContext.add(forkContext.head); + forkContext.replaceHead(bodySegments); + } + + //-------------------------------------------------------------------------- + // Control Statements + //-------------------------------------------------------------------------- + + /** + * Creates new context in which a `break` statement can be used. This occurs inside of a loop, + * labeled statement, or switch statement. + * @param {boolean} breakable Indicates if we are inside a statement where + * `break` without a label will exit the statement. + * @param {string|null} label The label associated with the statement. + * @returns {BreakContext} The new context. + */ + pushBreakContext(breakable, label) { + this.breakContext = new BreakContext( + this.breakContext, + breakable, + label, + this.forkContext, + ); + return this.breakContext; + } + + /** + * Removes the top item of the break context stack. + * @returns {Object} The removed context. + */ + popBreakContext() { + const context = this.breakContext; + const forkContext = this.forkContext; + + this.breakContext = context.upper; + + // Process this context here for other than switches and loops. + if (!context.breakable) { + const brokenForkContext = context.brokenForkContext; + + if (!brokenForkContext.empty) { + brokenForkContext.add(forkContext.head); + forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); + } + } + + return context; + } + + /** + * Makes a path for a `break` statement. + * + * It registers the head segment to a context of `break`. + * It makes new unreachable segment, then it set the head with the segment. + * @param {string|null} label A label of the break statement. + * @returns {void} + */ + makeBreak(label) { + const forkContext = this.forkContext; + + if (!forkContext.reachable) { + return; + } + + const context = getBreakContext(this, label); + + if (context) { + context.brokenForkContext.add(forkContext.head); + } + + /* c8 ignore next */ + forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); + } + + /** + * Makes a path for a `continue` statement. + * + * It makes a looping path. + * It makes new unreachable segment, then it set the head with the segment. + * @param {string|null} label A label of the continue statement. + * @returns {void} + */ + makeContinue(label) { + const forkContext = this.forkContext; + + if (!forkContext.reachable) { + return; + } + + const context = getContinueContext(this, label); + + if (context) { + if (context.continueDestSegments) { + makeLooped( + this, + forkContext.head, + context.continueDestSegments, + ); + + // If the context is a for-in/of loop, this affects a break also. + if ( + context.type === "ForInStatement" || + context.type === "ForOfStatement" + ) { + context.brokenForkContext.add(forkContext.head); + } + } else { + context.continueForkContext.add(forkContext.head); + } + } + forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); + } + + /** + * Makes a path for a `return` statement. + * + * It registers the head segment to a context of `return`. + * It makes new unreachable segment, then it set the head with the segment. + * @returns {void} + */ + makeReturn() { + const forkContext = this.forkContext; + + if (forkContext.reachable) { + getReturnContext(this).returnedForkContext.add(forkContext.head); + forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); + } + } + + /** + * Makes a path for a `throw` statement. + * + * It registers the head segment to a context of `throw`. + * It makes new unreachable segment, then it set the head with the segment. + * @returns {void} + */ + makeThrow() { + const forkContext = this.forkContext; + + if (forkContext.reachable) { + getThrowContext(this).thrownForkContext.add(forkContext.head); + forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); + } + } + + /** + * Makes the final path. + * @returns {void} + */ + makeFinal() { + const segments = this.currentSegments; + + if (segments.length > 0 && segments[0].reachable) { + this.returnedForkContext.add(segments); + } + } +} + +module.exports = CodePathState; diff --git a/tools/ui/node_modules/eslint/lib/linter/code-path-analysis/code-path.js b/tools/ui/node_modules/eslint/lib/linter/code-path-analysis/code-path.js new file mode 100644 index 0000000000000000000000000000000000000000..36ff8c53ee05e0c6958fc4ea70d7b46485a91f01 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/linter/code-path-analysis/code-path.js @@ -0,0 +1,332 @@ +/** + * @fileoverview A class of the code path. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const CodePathState = require("./code-path-state"); +const IdGenerator = require("./id-generator"); + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * A code path. + */ +class CodePath { + /** + * Creates a new instance. + * @param {Object} options Options for the function (see below). + * @param {string} options.id An identifier. + * @param {string} options.origin The type of code path origin. + * @param {CodePath|null} options.upper The code path of the upper function scope. + * @param {Function} options.onLooped A callback function to notify looping. + */ + constructor({ id, origin, upper, onLooped }) { + /** + * The identifier of this code path. + * Rules use it to store additional information of each rule. + * @type {string} + */ + this.id = id; + + /** + * The reason that this code path was started. May be "program", + * "function", "class-field-initializer", or "class-static-block". + * @type {string} + */ + this.origin = origin; + + /** + * The code path of the upper function scope. + * @type {CodePath|null} + */ + this.upper = upper; + + /** + * The code paths of nested function scopes. + * @type {CodePath[]} + */ + this.childCodePaths = []; + + // Initializes internal state. + Object.defineProperty(this, "internal", { + value: new CodePathState(new IdGenerator(`${id}_`), onLooped), + }); + + // Adds this into `childCodePaths` of `upper`. + if (upper) { + upper.childCodePaths.push(this); + } + } + + /** + * Gets the state of a given code path. + * @param {CodePath} codePath A code path to get. + * @returns {CodePathState} The state of the code path. + */ + static getState(codePath) { + return codePath.internal; + } + + /** + * The initial code path segment. This is the segment that is at the head + * of the code path. + * This is a passthrough to the underlying `CodePathState`. + * @type {CodePathSegment} + */ + get initialSegment() { + return this.internal.initialSegment; + } + + /** + * Final code path segments. These are the terminal (tail) segments in the + * code path, which is the combination of `returnedSegments` and `thrownSegments`. + * All segments in this array are reachable. + * This is a passthrough to the underlying `CodePathState`. + * @type {CodePathSegment[]} + */ + get finalSegments() { + return this.internal.finalSegments; + } + + /** + * Final code path segments that represent normal completion of the code path. + * For functions, this means both explicit `return` statements and implicit returns, + * such as the last reachable segment in a function that does not have an + * explicit `return` as this implicitly returns `undefined`. For scripts, + * modules, class field initializers, and class static blocks, this means + * all lines of code have been executed. + * These segments are also present in `finalSegments`. + * This is a passthrough to the underlying `CodePathState`. + * @type {CodePathSegment[]} + */ + get returnedSegments() { + return this.internal.returnedForkContext; + } + + /** + * Final code path segments that represent `throw` statements. + * This is a passthrough to the underlying `CodePathState`. + * These segments are also present in `finalSegments`. + * @type {CodePathSegment[]} + */ + get thrownSegments() { + return this.internal.thrownForkContext; + } + + /** + * Traverses all segments in this code path. + * + * codePath.traverseSegments((segment, controller) => { + * // do something. + * }); + * + * This method enumerates segments in order from the head. + * + * The `controller` argument has two methods: + * + * - `skip()` - skips the following segments in this branch + * - `break()` - skips all following segments in the traversal + * + * A note on the parameters: the `options` argument is optional. This means + * the first argument might be an options object or the callback function. + * @param {Object} [optionsOrCallback] Optional first and last segments to traverse. + * @param {CodePathSegment} [optionsOrCallback.first] The first segment to traverse. + * @param {CodePathSegment} [optionsOrCallback.last] The last segment to traverse. + * @param {Function} callback A callback function. + * @returns {void} + */ + traverseSegments(optionsOrCallback, callback) { + // normalize the arguments into a callback and options + let resolvedOptions; + let resolvedCallback; + + if (typeof optionsOrCallback === "function") { + resolvedCallback = optionsOrCallback; + resolvedOptions = {}; + } else { + resolvedOptions = optionsOrCallback || {}; + resolvedCallback = callback; + } + + // determine where to start traversing from based on the options + const startSegment = + resolvedOptions.first || this.internal.initialSegment; + const lastSegment = resolvedOptions.last; + + // set up initial location information + let record; + let index; + let end; + let segment = null; + + // segments that have already been visited during traversal + const visited = new Set(); + + // tracks the traversal steps + const stack = [[startSegment, 0]]; + + // segments that have been skipped during traversal + const skipped = new Set(); + + // indicates if we exited early from the traversal + let broken = false; + + /** + * Maintains traversal state. + */ + const controller = { + /** + * Skip the following segments in this branch. + * @returns {void} + */ + skip() { + skipped.add(segment); + }, + + /** + * Stop traversal completely - do not traverse to any + * other segments. + * @returns {void} + */ + break() { + broken = true; + }, + }; + + /** + * Checks if a given previous segment has been visited. + * @param {CodePathSegment} prevSegment A previous segment to check. + * @returns {boolean} `true` if the segment has been visited. + */ + function isVisited(prevSegment) { + return ( + visited.has(prevSegment) || + segment.isLoopedPrevSegment(prevSegment) + ); + } + + /** + * Checks if a given previous segment has been skipped. + * @param {CodePathSegment} prevSegment A previous segment to check. + * @returns {boolean} `true` if the segment has been skipped. + */ + function isSkipped(prevSegment) { + return ( + skipped.has(prevSegment) || + segment.isLoopedPrevSegment(prevSegment) + ); + } + + // the traversal + while (stack.length > 0) { + /* + * This isn't a pure stack. We use the top record all the time + * but don't always pop it off. The record is popped only if + * one of the following is true: + * + * 1) We have already visited the segment. + * 2) We have not visited *all* of the previous segments. + * 3) We have traversed past the available next segments. + * + * Otherwise, we just read the value and sometimes modify the + * record as we traverse. + */ + record = stack.at(-1); + segment = record[0]; + index = record[1]; + + if (index === 0) { + // Skip if this segment has been visited already. + if (visited.has(segment)) { + stack.pop(); + continue; + } + + // Skip if all previous segments have not been visited. + if ( + segment !== startSegment && + segment.prevSegments.length > 0 && + !segment.prevSegments.every(isVisited) + ) { + stack.pop(); + continue; + } + + visited.add(segment); + + // Skips the segment if all previous segments have been skipped. + const shouldSkip = + skipped.size > 0 && + segment.prevSegments.length > 0 && + segment.prevSegments.every(isSkipped); + + /* + * If the most recent segment hasn't been skipped, then we call + * the callback, passing in the segment and the controller. + */ + if (!shouldSkip) { + resolvedCallback.call(this, segment, controller); + + // exit if we're at the last segment + if (segment === lastSegment) { + controller.skip(); + } + + /* + * If the previous statement was executed, or if the callback + * called a method on the controller, we might need to exit the + * loop, so check for that and break accordingly. + */ + if (broken) { + break; + } + } else { + // If the most recent segment has been skipped, then mark it as skipped. + skipped.add(segment); + } + } + + // Update the stack. + end = segment.nextSegments.length - 1; + if (index < end) { + /* + * If we haven't yet visited all of the next segments, update + * the current top record on the stack to the next index to visit + * and then push a record for the current segment on top. + * + * Setting the current top record's index lets us know how many + * times we've been here and ensures that the segment won't be + * reprocessed (because we only process segments with an index + * of 0). + */ + record[1] += 1; + stack.push([segment.nextSegments[index], 0]); + } else if (index === end) { + /* + * If we are at the last next segment, then reset the top record + * in the stack to next segment and set its index to 0 so it will + * be processed next. + */ + record[0] = segment.nextSegments[index]; + record[1] = 0; + } else { + /* + * If index > end, that means we have no more segments that need + * processing. So, we pop that record off of the stack in order to + * continue traversing at the next level up. + */ + stack.pop(); + } + } + } +} + +module.exports = CodePath; diff --git a/tools/ui/node_modules/eslint/lib/linter/code-path-analysis/debug-helpers.js b/tools/ui/node_modules/eslint/lib/linter/code-path-analysis/debug-helpers.js new file mode 100644 index 0000000000000000000000000000000000000000..6a65ca7b50d3f1a1a4ac79c5f6f59d2d9e412bbe --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/linter/code-path-analysis/debug-helpers.js @@ -0,0 +1,223 @@ +/** + * @fileoverview Helpers to debug for code path analysis. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const debug = require("debug")("eslint:code-path"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Gets id of a given segment. + * @param {CodePathSegment} segment A segment to get. + * @returns {string} Id of the segment. + */ +/* c8 ignore next */ +// eslint-disable-next-line jsdoc/require-jsdoc -- Ignoring +function getId(segment) { + return segment.id + (segment.reachable ? "" : "!"); +} + +/** + * Get string for the given node and operation. + * @param {ASTNode} node The node to convert. + * @param {"enter" | "exit" | undefined} label The operation label. + * @returns {string} The string representation. + */ +function nodeToString(node, label) { + const suffix = label ? `:${label}` : ""; + + switch (node.type) { + case "Identifier": + return `${node.type}${suffix} (${node.name})`; + case "Literal": + return `${node.type}${suffix} (${node.value})`; + default: + return `${node.type}${suffix}`; + } +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = { + /** + * A flag that debug dumping is enabled or not. + * @type {boolean} + */ + enabled: debug.enabled, + + /** + * Dumps given objects. + * @param {...any} args objects to dump. + * @returns {void} + */ + dump: debug, + + /** + * Dumps the current analyzing state. + * @param {ASTNode} node A node to dump. + * @param {CodePathState} state A state to dump. + * @param {boolean} leaving A flag whether or not it's leaving + * @returns {void} + */ + dumpState: !debug.enabled + ? debug + : /* c8 ignore next */ function (node, state, leaving) { + for (let i = 0; i < state.currentSegments.length; ++i) { + const segInternal = state.currentSegments[i].internal; + + if (leaving) { + const last = segInternal.nodes.length - 1; + + if ( + last >= 0 && + segInternal.nodes[last] === + nodeToString(node, "enter") + ) { + segInternal.nodes[last] = nodeToString( + node, + void 0, + ); + } else { + segInternal.nodes.push(nodeToString(node, "exit")); + } + } else { + segInternal.nodes.push(nodeToString(node, "enter")); + } + } + + debug( + [ + `${state.currentSegments.map(getId).join(",")})`, + `${node.type}${leaving ? ":exit" : ""}`, + ].join(" "), + ); + }, + + /** + * Dumps a DOT code of a given code path. + * The DOT code can be visualized with Graphvis. + * @param {CodePath} codePath A code path to dump. + * @returns {void} + * @see http://www.graphviz.org + * @see http://www.webgraphviz.com + */ + dumpDot: !debug.enabled + ? debug + : /* c8 ignore next */ function (codePath) { + let text = + "\n" + + "digraph {\n" + + 'node[shape=box,style="rounded,filled",fillcolor=white];\n' + + 'initial[label="",shape=circle,style=filled,fillcolor=black,width=0.25,height=0.25];\n'; + + if (codePath.returnedSegments.length > 0) { + text += + 'final[label="",shape=doublecircle,style=filled,fillcolor=black,width=0.25,height=0.25];\n'; + } + if (codePath.thrownSegments.length > 0) { + text += + 'thrown[label="✘",shape=circle,width=0.3,height=0.3,fixedsize=true];\n'; + } + + const traceMap = Object.create(null); + const arrows = this.makeDotArrows(codePath, traceMap); + + // eslint-disable-next-line guard-for-in -- Want ability to traverse prototype + for (const id in traceMap) { + const segment = traceMap[id]; + + text += `${id}[`; + + if (segment.reachable) { + text += 'label="'; + } else { + text += + 'style="rounded,dashed,filled",fillcolor="#FF9800",label="<>\\n'; + } + + if (segment.internal.nodes.length > 0) { + text += segment.internal.nodes.join("\\n"); + } else { + text += "????"; + } + + text += '"];\n'; + } + + text += `${arrows}\n`; + text += "}"; + debug("DOT", text); + }, + + /** + * Makes a DOT code of a given code path. + * The DOT code can be visualized with Graphvis. + * @param {CodePath} codePath A code path to make DOT. + * @param {Object} traceMap Optional. A map to check whether or not segments had been done. + * @returns {string} A DOT code of the code path. + */ + makeDotArrows(codePath, traceMap) { + const stack = [[codePath.initialSegment, 0]]; + const done = traceMap || Object.create(null); + let lastId = codePath.initialSegment.id; + let text = `initial->${codePath.initialSegment.id}`; + + while (stack.length > 0) { + const item = stack.pop(); + const segment = item[0]; + const index = item[1]; + + if (done[segment.id] && index === 0) { + continue; + } + done[segment.id] = segment; + + const nextSegment = segment.allNextSegments[index]; + + if (!nextSegment) { + continue; + } + + if (lastId === segment.id) { + text += `->${nextSegment.id}`; + } else { + text += `;\n${segment.id}->${nextSegment.id}`; + } + lastId = nextSegment.id; + + stack.unshift([segment, 1 + index]); + stack.push([nextSegment, 0]); + } + + codePath.returnedSegments.forEach(finalSegment => { + if (lastId === finalSegment.id) { + text += "->final"; + } else { + text += `;\n${finalSegment.id}->final`; + } + lastId = null; + }); + + codePath.thrownSegments.forEach(finalSegment => { + if (lastId === finalSegment.id) { + text += "->thrown"; + } else { + text += `;\n${finalSegment.id}->thrown`; + } + lastId = null; + }); + + return `${text};`; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/linter/code-path-analysis/fork-context.js b/tools/ui/node_modules/eslint/lib/linter/code-path-analysis/fork-context.js new file mode 100644 index 0000000000000000000000000000000000000000..93d33162542820a900736387da7a297f80fcab1e --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/linter/code-path-analysis/fork-context.js @@ -0,0 +1,374 @@ +/** + * @fileoverview A class to operate forking. + * + * This is state of forking. + * This has a fork list and manages it. + * + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const assert = require("../../shared/assert"), + CodePathSegment = require("./code-path-segment"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Determines whether or not a given segment is reachable. + * @param {CodePathSegment} segment The segment to check. + * @returns {boolean} `true` if the segment is reachable. + */ +function isReachable(segment) { + return segment.reachable; +} + +/** + * Creates a new segment for each fork in the given context and appends it + * to the end of the specified range of segments. Ultimately, this ends up calling + * `new CodePathSegment()` for each of the forks using the `create` argument + * as a wrapper around special behavior. + * + * The `startIndex` and `endIndex` arguments specify a range of segments in + * `context` that should become `allPrevSegments` for the newly created + * `CodePathSegment` objects. + * + * When `context.segmentsList` is `[[a, b], [c, d], [e, f]]`, `begin` is `0`, and + * `end` is `-1`, this creates two new segments, `[g, h]`. This `g` is appended to + * the end of the path from `a`, `c`, and `e`. This `h` is appended to the end of + * `b`, `d`, and `f`. + * @param {ForkContext} context An instance from which the previous segments + * will be obtained. + * @param {number} startIndex The index of the first segment in the context + * that should be specified as previous segments for the newly created segments. + * @param {number} endIndex The index of the last segment in the context + * that should be specified as previous segments for the newly created segments. + * @param {Function} create A function that creates new `CodePathSegment` + * instances in a particular way. See the `CodePathSegment.new*` methods. + * @returns {Array} An array of the newly-created segments. + */ +function createSegments(context, startIndex, endIndex, create) { + /** @type {Array>} */ + const list = context.segmentsList; + + /* + * Both `startIndex` and `endIndex` work the same way: if the number is zero + * or more, then the number is used as-is. If the number is negative, + * then that number is added to the length of the segments list to + * determine the index to use. That means -1 for either argument + * is the last element, -2 is the second to last, and so on. + * + * So if `startIndex` is 0, `endIndex` is -1, and `list.length` is 3, the + * effective `startIndex` is 0 and the effective `endIndex` is 2, so this function + * will include items at indices 0, 1, and 2. + * + * Therefore, if `startIndex` is -1 and `endIndex` is -1, that means we'll only + * be using the last segment in `list`. + */ + const normalizedBegin = + startIndex >= 0 ? startIndex : list.length + startIndex; + const normalizedEnd = endIndex >= 0 ? endIndex : list.length + endIndex; + + /** @type {Array} */ + const segments = []; + + for (let i = 0; i < context.count; ++i) { + // this is passed into `new CodePathSegment` to add to code path. + const allPrevSegments = []; + + for (let j = normalizedBegin; j <= normalizedEnd; ++j) { + allPrevSegments.push(list[j][i]); + } + + // note: `create` is just a wrapper that augments `new CodePathSegment`. + segments.push(create(context.idGenerator.next(), allPrevSegments)); + } + + return segments; +} + +/** + * Inside of a `finally` block we end up with two parallel paths. If the code path + * exits by a control statement (such as `break` or `continue`) from the `finally` + * block, then we need to merge the remaining parallel paths back into one. + * @param {ForkContext} context The fork context to work on. + * @param {Array} segments Segments to merge. + * @returns {Array} The merged segments. + */ +function mergeExtraSegments(context, segments) { + let currentSegments = segments; + + /* + * We need to ensure that the array returned from this function contains no more + * than the number of segments that the context allows. `context.count` indicates + * how many items should be in the returned array to ensure that the new segment + * entries will line up with the already existing segment entries. + */ + while (currentSegments.length > context.count) { + const merged = []; + + /* + * Because `context.count` is a factor of 2 inside of a `finally` block, + * we can divide the segment count by 2 to merge the paths together. + * This loops through each segment in the list and creates a new `CodePathSegment` + * that has the segment and the segment two slots away as previous segments. + * + * If `currentSegments` is [a,b,c,d], this will create new segments e and f, such + * that: + * + * When `i` is 0: + * a->e + * c->e + * + * When `i` is 1: + * b->f + * d->f + */ + for ( + let i = 0, length = Math.floor(currentSegments.length / 2); + i < length; + ++i + ) { + merged.push( + CodePathSegment.newNext(context.idGenerator.next(), [ + currentSegments[i], + currentSegments[i + length], + ]), + ); + } + + /* + * Go through the loop condition one more time to see if we have the + * number of segments for the context. If not, we'll keep merging paths + * of the merged segments until we get there. + */ + currentSegments = merged; + } + + return currentSegments; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Manages the forking of code paths. + */ +class ForkContext { + /** + * Creates a new instance. + * @param {IdGenerator} idGenerator An identifier generator for segments. + * @param {ForkContext|null} upper The preceding fork context. + * @param {number} count The number of parallel segments in each element + * of `segmentsList`. + */ + constructor(idGenerator, upper, count) { + /** + * The ID generator that will generate segment IDs for any new + * segments that are created. + * @type {IdGenerator} + */ + this.idGenerator = idGenerator; + + /** + * The preceding fork context. + * @type {ForkContext|null} + */ + this.upper = upper; + + /** + * The number of elements in each element of `segmentsList`. In most + * cases, this is 1 but can be 2 when there is a `finally` present, + * which forks the code path outside of normal flow. In the case of nested + * `finally` blocks, this can be a multiple of 2. + * @type {number} + */ + this.count = count; + + /** + * The segments within this context. Each element in this array has + * `count` elements that represent one step in each fork. For example, + * when `segmentsList` is `[[a, b], [c, d], [e, f]]`, there is one path + * a->c->e and one path b->d->f, and `count` is 2 because each element + * is an array with two elements. + * @type {Array>} + */ + this.segmentsList = []; + } + + /** + * The segments that begin this fork context. + * @type {Array} + */ + get head() { + const list = this.segmentsList; + + return list.length === 0 ? [] : list.at(-1); + } + + /** + * Indicates if the context contains no segments. + * @type {boolean} + */ + get empty() { + return this.segmentsList.length === 0; + } + + /** + * Indicates if there are any segments that are reachable. + * @type {boolean} + */ + get reachable() { + const segments = this.head; + + return segments.length > 0 && segments.some(isReachable); + } + + /** + * Creates new segments in this context and appends them to the end of the + * already existing `CodePathSegment`s specified by `startIndex` and + * `endIndex`. + * @param {number} startIndex The index of the first segment in the context + * that should be specified as previous segments for the newly created segments. + * @param {number} endIndex The index of the last segment in the context + * that should be specified as previous segments for the newly created segments. + * @returns {Array} An array of the newly created segments. + */ + makeNext(startIndex, endIndex) { + return createSegments( + this, + startIndex, + endIndex, + CodePathSegment.newNext, + ); + } + + /** + * Creates new unreachable segments in this context and appends them to the end of the + * already existing `CodePathSegment`s specified by `startIndex` and + * `endIndex`. + * @param {number} startIndex The index of the first segment in the context + * that should be specified as previous segments for the newly created segments. + * @param {number} endIndex The index of the last segment in the context + * that should be specified as previous segments for the newly created segments. + * @returns {Array} An array of the newly created segments. + */ + makeUnreachable(startIndex, endIndex) { + return createSegments( + this, + startIndex, + endIndex, + CodePathSegment.newUnreachable, + ); + } + + /** + * Creates new segments in this context and does not append them to the end + * of the already existing `CodePathSegment`s specified by `startIndex` and + * `endIndex`. The `startIndex` and `endIndex` are only used to determine if + * the new segments should be reachable. If any of the segments in this range + * are reachable then the new segments are also reachable; otherwise, the new + * segments are unreachable. + * @param {number} startIndex The index of the first segment in the context + * that should be considered for reachability. + * @param {number} endIndex The index of the last segment in the context + * that should be considered for reachability. + * @returns {Array} An array of the newly created segments. + */ + makeDisconnected(startIndex, endIndex) { + return createSegments( + this, + startIndex, + endIndex, + CodePathSegment.newDisconnected, + ); + } + + /** + * Adds segments to the head of this context. + * @param {Array} segments The segments to add. + * @returns {void} + */ + add(segments) { + assert( + segments.length >= this.count, + `${segments.length} >= ${this.count}`, + ); + this.segmentsList.push(mergeExtraSegments(this, segments)); + } + + /** + * Replaces the head segments with the given segments. + * The current head segments are removed. + * @param {Array} replacementHeadSegments The new head segments. + * @returns {void} + */ + replaceHead(replacementHeadSegments) { + assert( + replacementHeadSegments.length >= this.count, + `${replacementHeadSegments.length} >= ${this.count}`, + ); + this.segmentsList.splice( + -1, + 1, + mergeExtraSegments(this, replacementHeadSegments), + ); + } + + /** + * Adds all segments of a given fork context into this context. + * @param {ForkContext} otherForkContext The fork context to add from. + * @returns {void} + */ + addAll(otherForkContext) { + assert(otherForkContext.count === this.count); + this.segmentsList.push(...otherForkContext.segmentsList); + } + + /** + * Clears all segments in this context. + * @returns {void} + */ + clear() { + this.segmentsList = []; + } + + /** + * Creates a new root context, meaning that there are no parent + * fork contexts. + * @param {IdGenerator} idGenerator An identifier generator for segments. + * @returns {ForkContext} New fork context. + */ + static newRoot(idGenerator) { + const context = new ForkContext(idGenerator, null, 1); + + context.add([CodePathSegment.newRoot(idGenerator.next())]); + + return context; + } + + /** + * Creates an empty fork context preceded by a given context. + * @param {ForkContext} parentContext The parent fork context. + * @param {boolean} shouldForkLeavingPath Indicates that we are inside of + * a `finally` block and should therefore fork the path that leaves + * `finally`. + * @returns {ForkContext} New fork context. + */ + static newEmpty(parentContext, shouldForkLeavingPath) { + return new ForkContext( + parentContext.idGenerator, + parentContext, + (shouldForkLeavingPath ? 2 : 1) * parentContext.count, + ); + } +} + +module.exports = ForkContext; diff --git a/tools/ui/node_modules/eslint/lib/linter/code-path-analysis/id-generator.js b/tools/ui/node_modules/eslint/lib/linter/code-path-analysis/id-generator.js new file mode 100644 index 0000000000000000000000000000000000000000..9cb4d33b29a92237a80d8901c8b0e62431086288 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/linter/code-path-analysis/id-generator.js @@ -0,0 +1,44 @@ +/** + * @fileoverview A class of identifiers generator for code path segments. + * + * Each rule uses the identifier of code path segments to store additional + * information of the code path. + * + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * A generator for unique ids. + */ +class IdGenerator { + /** + * @param {string} prefix Optional. A prefix of generated ids. + */ + constructor(prefix) { + this.prefix = String(prefix); + this.n = 0; + } + + /** + * Generates id. + * @returns {string} A generated id. + */ + next() { + this.n = (1 + this.n) | 0; + + /* c8 ignore start */ + if (this.n < 0) { + this.n = 1; + } /* c8 ignore stop */ + + return this.prefix + this.n; + } +} + +module.exports = IdGenerator; diff --git a/tools/ui/node_modules/eslint/lib/linter/esquery.js b/tools/ui/node_modules/eslint/lib/linter/esquery.js new file mode 100644 index 0000000000000000000000000000000000000000..31d302bc6b7df66d3d3bda43b08394e278c9cb58 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/linter/esquery.js @@ -0,0 +1,332 @@ +/** + * @fileoverview ESQuery wrapper for ESLint. + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const esquery = require("esquery"); + +//----------------------------------------------------------------------------- +// Typedefs +//----------------------------------------------------------------------------- + +/** + * @typedef {import("esquery").Selector} ESQuerySelector + * @typedef {import("esquery").ESQueryOptions} ESQueryOptions + */ + +//------------------------------------------------------------------------------ +// Classes +//------------------------------------------------------------------------------ + +/** + * The result of parsing and analyzing an ESQuery selector. + */ +class ESQueryParsedSelector { + /** + * The raw selector string that was parsed + * @type {string} + */ + source; + + /** + * Whether this selector is an exit selector + * @type {boolean} + */ + isExit; + + /** + * An object (from esquery) describing the matching behavior of the selector + * @type {ESQuerySelector} + */ + root; + + /** + * The node types that could possibly trigger this selector, or `null` if all node types could trigger it + * @type {string[]|null} + */ + nodeTypes; + + /** + * The number of class, pseudo-class, and attribute queries in this selector + * @type {number} + */ + attributeCount; + + /** + * The number of identifier queries in this selector + * @type {number} + */ + identifierCount; + + /** + * Creates a new parsed selector. + * @param {string} source The raw selector string that was parsed + * @param {boolean} isExit Whether this selector is an exit selector + * @param {ESQuerySelector} root An object (from esquery) describing the matching behavior of the selector + * @param {string[]|null} nodeTypes The node types that could possibly trigger this selector, or `null` if all node types could trigger it + * @param {number} attributeCount The number of class, pseudo-class, and attribute queries in this selector + * @param {number} identifierCount The number of identifier queries in this selector + */ + constructor( + source, + isExit, + root, + nodeTypes, + attributeCount, + identifierCount, + ) { + this.source = source; + this.isExit = isExit; + this.root = root; + this.nodeTypes = nodeTypes; + this.attributeCount = attributeCount; + this.identifierCount = identifierCount; + } + + /** + * Compares this selector's specificity to another selector for sorting purposes. + * @param {ESQueryParsedSelector} otherSelector The selector to compare against + * @returns {number} + * a value less than 0 if this selector is less specific than otherSelector + * a value greater than 0 if this selector is more specific than otherSelector + * a value less than 0 if this selector and otherSelector have the same specificity, and this selector <= otherSelector alphabetically + * a value greater than 0 if this selector and otherSelector have the same specificity, and this selector > otherSelector alphabetically + */ + compare(otherSelector) { + return ( + this.attributeCount - otherSelector.attributeCount || + this.identifierCount - otherSelector.identifierCount || + (this.source <= otherSelector.source ? -1 : 1) + ); + } +} + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const selectorCache = new Map(); + +/** + * Computes the union of one or more arrays + * @param {...any[]} arrays One or more arrays to union + * @returns {any[]} The union of the input arrays + */ +function union(...arrays) { + return [...new Set(arrays.flat())]; +} + +/** + * Computes the intersection of one or more arrays + * @param {...any[]} arrays One or more arrays to intersect + * @returns {any[]} The intersection of the input arrays + */ +function intersection(...arrays) { + if (arrays.length === 0) { + return []; + } + + let result = [...new Set(arrays[0])]; + + for (const array of arrays.slice(1)) { + result = result.filter(x => array.includes(x)); + } + return result; +} + +/** + * Analyzes a parsed selector and returns combined data about it + * @param {ESQuerySelector} parsedSelector An object (from esquery) describing the matching behavior of the selector + * @returns {{nodeTypes:string[]|null, attributeCount:number, identifierCount:number}} Object containing selector data. + */ +function analyzeParsedSelector(parsedSelector) { + let attributeCount = 0; + let identifierCount = 0; + + /** + * Analyzes a selector and returns the node types that could possibly trigger it. + * @param {ESQuerySelector} selector The selector to analyze. + * @returns {string[]|null} The node types that could possibly trigger this selector, or `null` if all node types could trigger it + */ + function analyzeSelector(selector) { + switch (selector.type) { + case "identifier": + identifierCount++; + return [selector.value]; + + case "not": + selector.selectors.map(analyzeSelector); + return null; + + case "matches": { + const typesForComponents = + selector.selectors.map(analyzeSelector); + + if (typesForComponents.every(Boolean)) { + return union(...typesForComponents); + } + return null; + } + + case "compound": { + const typesForComponents = selector.selectors + .map(analyzeSelector) + .filter(typesForComponent => typesForComponent); + + // If all of the components could match any type, then the compound could also match any type. + if (!typesForComponents.length) { + return null; + } + + /* + * If at least one of the components could only match a particular type, the compound could only match + * the intersection of those types. + */ + return intersection(...typesForComponents); + } + + case "attribute": + case "field": + case "nth-child": + case "nth-last-child": + attributeCount++; + return null; + + case "child": + case "descendant": + case "sibling": + case "adjacent": + analyzeSelector(selector.left); + return analyzeSelector(selector.right); + + case "class": + // TODO: abstract into JSLanguage somehow + if (selector.name === "function") { + return [ + "FunctionDeclaration", + "FunctionExpression", + "ArrowFunctionExpression", + ]; + } + return null; + + default: + return null; + } + } + + const nodeTypes = analyzeSelector(parsedSelector); + + return { + nodeTypes, + attributeCount, + identifierCount, + }; +} + +/** + * Tries to parse a simple selector string, such as a single identifier or wildcard. + * This saves time by avoiding the overhead of esquery parsing for simple cases. + * @param {string} selector The selector string to parse. + * @returns {Object|null} An object describing the selector if it is simple, or `null` if it is not. + */ +function trySimpleParseSelector(selector) { + if (selector === "*") { + return { + type: "wildcard", + value: "*", + }; + } + + if (/^[a-z]+$/iu.test(selector)) { + return { + type: "identifier", + value: selector, + }; + } + + return null; +} + +/** + * Parses a raw selector string, and throws a useful error if parsing fails. + * @param {string} selector The selector string to parse. + * @returns {Object} An object (from esquery) describing the matching behavior of this selector + * @throws {Error} An error if the selector is invalid + */ +function tryParseSelector(selector) { + try { + return esquery.parse(selector); + } catch (err) { + if ( + err.location && + err.location.start && + typeof err.location.start.offset === "number" + ) { + throw new SyntaxError( + `Syntax error in selector "${selector}" at position ${err.location.start.offset}: ${err.message}`, + { + cause: err, + }, + ); + } + throw err; + } +} + +/** + * Parses a raw selector string, and returns the parsed selector along with specificity and type information. + * @param {string} source A raw AST selector + * @returns {ESQueryParsedSelector} A selector descriptor + */ +function parse(source) { + if (selectorCache.has(source)) { + return selectorCache.get(source); + } + + const cleanSource = source.replace(/:exit$/u, ""); + const parsedSelector = + trySimpleParseSelector(cleanSource) ?? tryParseSelector(cleanSource); + const { nodeTypes, attributeCount, identifierCount } = + analyzeParsedSelector(parsedSelector); + + const result = new ESQueryParsedSelector( + source, + source.endsWith(":exit"), + parsedSelector, + nodeTypes, + attributeCount, + identifierCount, + ); + + selectorCache.set(source, result); + return result; +} + +/** + * Checks if a node matches a given selector. + * @param {Object} node The node to check against the selector. + * @param {ESQuerySelector} root The root of the selector to match against. + * @param {Object[]} ancestry The ancestry of the node being checked, which is an array of nodes from the current node to the root. + * @param {ESQueryOptions} options The options to use for matching. + * @returns {boolean} `true` if the node matches the selector, `false` otherwise. + */ +function matches(node, root, ancestry, options) { + return esquery.matches(node, root, ancestry, options); +} + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +module.exports = { + parse, + matches, + ESQueryParsedSelector, +}; diff --git a/tools/ui/node_modules/eslint/lib/linter/file-context.js b/tools/ui/node_modules/eslint/lib/linter/file-context.js new file mode 100644 index 0000000000000000000000000000000000000000..40acdd63cd26da643430e2d869577db94943b677 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/linter/file-context.js @@ -0,0 +1,144 @@ +/** + * @fileoverview The FileContext class. + * @author Nicholas C. Zakas + */ + +"use strict"; + +/** + * Represents a file context that the linter can use to lint a file. + */ +class FileContext { + /** + * The current working directory. + * @type {string} + */ + cwd; + + /** + * The filename of the file being linted. + * @type {string} + */ + filename; + + /** + * The physical filename of the file being linted. + * @type {string} + */ + physicalFilename; + + /** + * The source code of the file being linted. + * @type {SourceCode} + */ + sourceCode; + + /** + * The parser options for the file being linted. + * @type {Record} + * @deprecated Use `languageOptions` instead. + */ + parserOptions; + + /** + * The path to the parser used to parse this file. + * @type {string} + * @deprecated No longer supported. + */ + parserPath; + + /** + * The language options used when parsing this file. + * @type {Record} + */ + languageOptions; + + /** + * The settings for the file being linted. + * @type {Record} + */ + settings; + + /** + * Creates a new instance. + * @param {Object} config The configuration object for the file context. + * @param {string} config.cwd The current working directory. + * @param {string} config.filename The filename of the file being linted. + * @param {string} config.physicalFilename The physical filename of the file being linted. + * @param {SourceCode} config.sourceCode The source code of the file being linted. + * @param {Record} config.parserOptions The parser options for the file being linted. + * @param {string} config.parserPath The path to the parser used to parse this file. + * @param {Record} config.languageOptions The language options used when parsing this file. + * @param {Record} config.settings The settings for the file being linted. + */ + constructor({ + cwd, + filename, + physicalFilename, + sourceCode, + parserOptions, + parserPath, + languageOptions, + settings, + }) { + this.cwd = cwd; + this.filename = filename; + this.physicalFilename = physicalFilename; + this.sourceCode = sourceCode; + this.parserOptions = parserOptions; + this.parserPath = parserPath; + this.languageOptions = languageOptions; + this.settings = settings; + + Object.freeze(this); + } + + /** + * Gets the current working directory. + * @returns {string} The current working directory. + * @deprecated Use `cwd` instead. + */ + getCwd() { + return this.cwd; + } + + /** + * Gets the filename of the file being linted. + * @returns {string} The filename of the file being linted. + * @deprecated Use `filename` instead. + */ + getFilename() { + return this.filename; + } + + /** + * Gets the physical filename of the file being linted. + * @returns {string} The physical filename of the file being linted. + * @deprecated Use `physicalFilename` instead. + */ + getPhysicalFilename() { + return this.physicalFilename; + } + + /** + * Gets the source code of the file being linted. + * @returns {SourceCode} The source code of the file being linted. + * @deprecated Use `sourceCode` instead. + */ + getSourceCode() { + return this.sourceCode; + } + + /** + * Creates a new object with the current object as the prototype and + * the specified properties as its own properties. + * @param {Object} extension The properties to add to the new object. + * @returns {FileContext} A new object with the current object as the prototype + * and the specified properties as its own properties. + */ + extend(extension) { + return Object.freeze(Object.assign(Object.create(this), extension)); + } +} + +exports.FileContext = FileContext; diff --git a/tools/ui/node_modules/eslint/lib/linter/file-report.js b/tools/ui/node_modules/eslint/lib/linter/file-report.js new file mode 100644 index 0000000000000000000000000000000000000000..29cea0a5da94a15849f3af437eaa6d87a5a6034e --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/linter/file-report.js @@ -0,0 +1,608 @@ +/** + * @fileoverview A class to track messages reported by the linter for a file. + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const assert = require("../shared/assert"); +const { RuleFixer } = require("./rule-fixer"); +const { interpolate } = require("./interpolate"); +const ruleReplacements = require("../../conf/replacements.json"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** @typedef {import("../types").Linter.LintMessage} LintMessage */ +/** @typedef {import("../types").Linter.LintSuggestion} SuggestionResult */ +/** @typedef {import("@eslint/core").Language} Language */ +/** @typedef {import("@eslint/core").SourceLocation} SourceLocation */ + +/** + * An error message description + * @typedef {Object} MessageDescriptor + * @property {ASTNode} [node] The reported node + * @property {Location} loc The location of the problem. + * @property {string} message The problem message. + * @property {Object} [data] Optional data to use to fill in placeholders in the + * message. + * @property {Function} [fix] The function to call that creates a fix command. + * @property {Array<{desc?: string, messageId?: string, fix: Function}>} suggest Suggestion descriptions and functions to create a the associated fixes. + */ + +/** + * @typedef {Object} LintProblem + * @property {string} ruleId The rule ID that reported the problem. + * @property {string} message The problem message. + * @property {SourceLocation} loc The location of the problem. + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const DEFAULT_ERROR_LOC = { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 }, +}; + +/** + * Updates a given location based on the language offsets. This allows us to + * change 0-based locations to 1-based locations. We always want ESLint + * reporting lines and columns starting from 1. + * @todo Potentially this should be moved into a shared utility file. + * @param {Object} location The location to update. + * @param {number} location.line The starting line number. + * @param {number} location.column The starting column number. + * @param {number} [location.endLine] The ending line number. + * @param {number} [location.endColumn] The ending column number. + * @param {Language} language The language to use to adjust the location information. + * @returns {Object} The updated location. + */ +function updateLocationInformation( + { line, column, endLine, endColumn }, + language, +) { + const columnOffset = language.columnStart === 1 ? 0 : 1; + const lineOffset = language.lineStart === 1 ? 0 : 1; + + // calculate separately to account for undefined + const finalEndLine = endLine === void 0 ? endLine : endLine + lineOffset; + const finalEndColumn = + endColumn === void 0 ? endColumn : endColumn + columnOffset; + + return { + line: line + lineOffset, + column: column + columnOffset, + endLine: finalEndLine, + endColumn: finalEndColumn, + }; +} + +/** + * creates a missing-rule message. + * @param {string} ruleId the ruleId to create + * @returns {string} created error message + * @private + */ +function createMissingRuleMessage(ruleId) { + return Object.hasOwn(ruleReplacements.rules, ruleId) + ? `Rule '${ruleId}' was removed and replaced by: ${ruleReplacements.rules[ruleId].join(", ")}` + : `Definition for rule '${ruleId}' was not found.`; +} + +/** + * creates a linting problem + * @param {LintProblem} options to create linting error + * @param {RuleSeverity} severity the error message to report + * @param {Language} language the language to use to adjust the location information. + * @returns {LintMessage} created problem, returns a missing-rule problem if only provided ruleId. + * @private + */ +function createLintingProblem(options, severity, language) { + const { + ruleId = null, + loc = DEFAULT_ERROR_LOC, + message = createMissingRuleMessage(options.ruleId), + } = options; + + return { + ruleId, + message, + ...updateLocationInformation( + { + line: loc.start.line, + column: loc.start.column, + endLine: loc.end.line, + endColumn: loc.end.column, + }, + language, + ), + severity, + nodeType: null, + }; +} + +/** + * Translates a multi-argument context.report() call into a single object argument call + * @param {...*} args A list of arguments passed to `context.report` + * @returns {MessageDescriptor} A normalized object containing report information + */ +function normalizeMultiArgReportCall(...args) { + // If there is one argument, it is considered to be a new-style call already. + if (args.length === 1) { + // Shallow clone the object to avoid surprises if reusing the descriptor + return Object.assign({}, args[0]); + } + + // If the second argument is a string, the arguments are interpreted as [node, message, data, fix]. + if (typeof args[1] === "string") { + return { + node: args[0], + message: args[1], + data: args[2], + fix: args[3], + }; + } + + // Otherwise, the arguments are interpreted as [node, loc, message, data, fix]. + return { + node: args[0], + loc: args[1], + message: args[2], + data: args[3], + fix: args[4], + }; +} + +/** + * Asserts that either a loc or a node was provided, and the node is valid if it was provided. + * @param {MessageDescriptor} descriptor A descriptor to validate + * @returns {void} + * @throws AssertionError if neither a node nor a loc was provided, or if the node is not an object + */ +function assertValidNodeInfo(descriptor) { + if (descriptor.node) { + assert(typeof descriptor.node === "object", "Node must be an object"); + } else { + assert( + descriptor.loc, + "Node must be provided when reporting error if location is not provided", + ); + } +} + +/** + * Normalizes a MessageDescriptor to always have a `loc` with `start` and `end` properties + * @param {MessageDescriptor} descriptor A descriptor for the report from a rule. + * @returns {{start: Location, end: (Location|null)}} An updated location that infers the `start` and `end` properties + * from the `node` of the original descriptor, or infers the `start` from the `loc` of the original descriptor. + */ +function normalizeReportLoc(descriptor) { + if (descriptor.loc.start) { + return descriptor.loc; + } + return { start: descriptor.loc, end: null }; +} + +/** + * Clones the given fix object. + * @param {Fix|null} fix The fix to clone. + * @returns {Fix|null} Deep cloned fix object or `null` if `null` or `undefined` was passed in. + */ +function cloneFix(fix) { + if (!fix) { + return null; + } + + return { + range: [fix.range[0], fix.range[1]], + text: fix.text, + }; +} + +/** + * Check that a fix has a valid range. + * @param {Fix|null} fix The fix to validate. + * @returns {void} + */ +function assertValidFix(fix) { + if (fix) { + assert( + fix.range && + typeof fix.range[0] === "number" && + typeof fix.range[1] === "number", + `Fix has invalid range: ${JSON.stringify(fix, null, 2)}`, + ); + } +} + +/** + * Compares items in a fixes array by range. + * @param {Fix} a The first message. + * @param {Fix} b The second message. + * @returns {number} -1 if a comes before b, 1 if a comes after b, 0 if equal. + * @private + */ +function compareFixesByRange(a, b) { + return a.range[0] - b.range[0] || a.range[1] - b.range[1]; +} + +/** + * Merges the given fixes array into one. + * @param {Fix[]} fixes The fixes to merge. + * @param {SourceCode} sourceCode The source code object to get the text between fixes. + * @returns {{text: string, range: number[]}} The merged fixes + */ +function mergeFixes(fixes, sourceCode) { + for (const fix of fixes) { + assertValidFix(fix); + } + + if (fixes.length === 0) { + return null; + } + if (fixes.length === 1) { + return cloneFix(fixes[0]); + } + + fixes.sort(compareFixesByRange); + + const originalText = sourceCode.text; + const start = fixes[0].range[0]; + const end = fixes.at(-1).range[1]; + let text = ""; + let lastPos = Number.MIN_SAFE_INTEGER; + + for (const fix of fixes) { + assert( + fix.range[0] >= lastPos, + "Fix objects must not be overlapped in a report.", + ); + + if (fix.range[0] >= 0) { + text += originalText.slice( + Math.max(0, start, lastPos), + fix.range[0], + ); + } + text += fix.text; + lastPos = fix.range[1]; + } + text += originalText.slice(Math.max(0, start, lastPos), end); + + return { range: [start, end], text }; +} + +/** + * Gets one fix object from the given descriptor. + * If the descriptor retrieves multiple fixes, this merges those to one. + * @param {MessageDescriptor} descriptor The report descriptor. + * @param {SourceCode} sourceCode The source code object to get text between fixes. + * @returns {({text: string, range: number[]}|null)} The fix for the descriptor + */ +function normalizeFixes(descriptor, sourceCode) { + if (typeof descriptor.fix !== "function") { + return null; + } + + const ruleFixer = new RuleFixer({ sourceCode }); + + // @type {null | Fix | Fix[] | IterableIterator} + const fix = descriptor.fix(ruleFixer); + + // Merge to one. + if (fix && Symbol.iterator in fix) { + return mergeFixes(Array.from(fix), sourceCode); + } + + assertValidFix(fix); + return cloneFix(fix); +} + +/** + * Gets an array of suggestion objects from the given descriptor. + * @param {MessageDescriptor} descriptor The report descriptor. + * @param {SourceCode} sourceCode The source code object to get text between fixes. + * @param {Object} messages Object of meta messages for the rule. + * @returns {Array} The suggestions for the descriptor + */ +function mapSuggestions(descriptor, sourceCode, messages) { + if (!descriptor.suggest || !Array.isArray(descriptor.suggest)) { + return []; + } + + return ( + descriptor.suggest + .map(suggestInfo => { + const computedDesc = + suggestInfo.desc || messages[suggestInfo.messageId]; + + return { + ...suggestInfo, + desc: interpolate(computedDesc, suggestInfo.data), + fix: normalizeFixes(suggestInfo, sourceCode), + }; + }) + + // Remove suggestions that didn't provide a fix + .filter(({ fix }) => fix) + ); +} + +/** + * Creates information about the report from a descriptor + * @param {Object} options Information about the problem + * @param {string} options.ruleId Rule ID + * @param {(0|1|2)} options.severity Rule severity + * @param {(ASTNode|null)} options.node Node + * @param {string} options.message Error message + * @param {string} [options.messageId] The error message ID. + * @param {{start: SourceLocation, end: (SourceLocation|null)}} options.loc Start and end location + * @param {{text: string, range: (number[]|null)}} options.fix The fix object + * @param {Array<{text: string, range: (number[]|null)}>} options.suggestions The array of suggestions objects + * @param {Language} [options.language] The language to use to adjust line and column offsets. + * @returns {LintMessage} Information about the report + */ +function createProblem(options) { + const { language } = options; + + // calculate offsets based on the language in use + const columnOffset = language.columnStart === 1 ? 0 : 1; + const lineOffset = language.lineStart === 1 ? 0 : 1; + + const problem = { + ruleId: options.ruleId, + severity: options.severity, + message: options.message, + line: options.loc.start.line + lineOffset, + column: options.loc.start.column + columnOffset, + nodeType: (options.node && options.node.type) || null, + }; + + /* + * If this isn’t in the conditional, some of the tests fail + * because `messageId` is present in the problem object + */ + if (options.messageId) { + problem.messageId = options.messageId; + } + + if (options.loc.end) { + problem.endLine = options.loc.end.line + lineOffset; + problem.endColumn = options.loc.end.column + columnOffset; + } + + if (options.fix) { + problem.fix = options.fix; + } + + if (options.suggestions && options.suggestions.length > 0) { + problem.suggestions = options.suggestions; + } + + return problem; +} + +/** + * Validates that suggestions are properly defined. Throws if an error is detected. + * @param {Array<{ desc?: string, messageId?: string }>} suggest The incoming suggest data. + * @param {Object} messages Object of meta messages for the rule. + * @returns {void} + */ +function validateSuggestions(suggest, messages) { + if (suggest && Array.isArray(suggest)) { + suggest.forEach(suggestion => { + if (suggestion.messageId) { + const { messageId } = suggestion; + + if (!messages) { + throw new TypeError( + `context.report() called with a suggest option with a messageId '${messageId}', but no messages were present in the rule metadata.`, + ); + } + + if (!messages[messageId]) { + throw new TypeError( + `context.report() called with a suggest option with a messageId '${messageId}' which is not present in the 'messages' config: ${JSON.stringify(messages, null, 2)}`, + ); + } + + if (suggestion.desc) { + throw new TypeError( + "context.report() called with a suggest option that defines both a 'messageId' and an 'desc'. Please only pass one.", + ); + } + } else if (!suggestion.desc) { + throw new TypeError( + "context.report() called with a suggest option that doesn't have either a `desc` or `messageId`", + ); + } + + if (typeof suggestion.fix !== "function") { + throw new TypeError( + `context.report() called with a suggest option without a fix function. See: ${JSON.stringify(suggestion, null, 2)}`, + ); + } + }); + } +} + +/** + * Computes the message from a report descriptor. + * @param {MessageDescriptor} descriptor The report descriptor. + * @param {Object} messages Object of meta messages for the rule. + * @returns {string} The computed message. + * @throws {TypeError} If messageId is not found or both message and messageId are provided. + */ +function computeMessageFromDescriptor(descriptor, messages) { + if (descriptor.messageId) { + if (!messages) { + throw new TypeError( + "context.report() called with a messageId, but no messages were present in the rule metadata.", + ); + } + const id = descriptor.messageId; + + if (descriptor.message) { + throw new TypeError( + "context.report() called with a message and a messageId. Please only pass one.", + ); + } + if (!messages || !Object.hasOwn(messages, id)) { + throw new TypeError( + `context.report() called with a messageId of '${id}' which is not present in the 'messages' config: ${JSON.stringify(messages, null, 2)}`, + ); + } + return messages[id]; + } + + if (descriptor.message) { + return descriptor.message; + } + + throw new TypeError( + "Missing `message` property in report() call; add a message that describes the linting problem.", + ); +} + +/** + * A report object that contains the messages reported the linter + * for a file. + */ +class FileReport { + /** + * The messages reported by the linter for this file. + * @type {LintMessage[]} + */ + messages = []; + + /** + * A rule mapper that maps rule IDs to their metadata. + * @type {(string) => RuleDefinition} + */ + #ruleMapper; + + /** + * The source code object for the file. + * @type {SourceCode} + */ + #sourceCode; + + /** + * The language to use to adjust line and column offsets. + * @type {Language} + */ + #language; + + /** + * Whether to disable fixes for this report. + * @type {boolean} + */ + #disableFixes; + + /** + * Creates a new FileReport instance. + * @param {Object} options The options for the file report + * @param {(string) => RuleDefinition} options.ruleMapper A rule mapper that maps rule IDs to their metadata. + * @param {SourceCode} options.sourceCode The source code object for the file. + * @param {Language} options.language The language to use to adjust line and column offsets. + * @param {boolean} [options.disableFixes=false] Whether to disable fixes for this report. + */ + constructor({ ruleMapper, sourceCode, language, disableFixes = false }) { + this.#ruleMapper = ruleMapper; + this.#sourceCode = sourceCode; + this.#language = language; + this.#disableFixes = disableFixes; + } + + /** + * Adds a rule-generated message to the report. + * @param {string} ruleId The rule ID that reported the problem. + * @param {0|1|2} severity The severity of the problem (0 = off, 1 = warning, 2 = error). + * @param {...*} args The arguments passed to `context.report()`. + * @returns {LintMessage} The created message object. + * @throws {TypeError} If the messageId is not found or both message and messageId are provided. + * @throws {AssertionError} If the node is not an object or neither a node nor a loc is provided. + */ + addRuleMessage(ruleId, severity, ...args) { + const descriptor = normalizeMultiArgReportCall(...args); + const ruleDefinition = this.#ruleMapper(ruleId); + const messages = ruleDefinition?.meta?.messages; + + assertValidNodeInfo(descriptor); + + const computedMessage = computeMessageFromDescriptor( + descriptor, + messages, + ); + + validateSuggestions(descriptor.suggest, messages); + + this.messages.push( + createProblem({ + ruleId, + severity, + node: descriptor.node, + message: interpolate(computedMessage, descriptor.data), + messageId: descriptor.messageId, + loc: descriptor.loc + ? normalizeReportLoc(descriptor) + : this.#sourceCode.getLoc(descriptor.node), + fix: this.#disableFixes + ? null + : normalizeFixes(descriptor, this.#sourceCode), + suggestions: this.#disableFixes + ? [] + : mapSuggestions(descriptor, this.#sourceCode, messages), + language: this.#language, + }), + ); + + return this.messages.at(-1); + } + + /** + * Adds an error message to the report. Meant to be called outside of rules. + * @param {LintProblem} descriptor The descriptor for the error message. + * @returns {LintMessage} The created message object. + */ + addError(descriptor) { + const message = createLintingProblem(descriptor, 2, this.#language); + this.messages.push(message); + return message; + } + + /** + * Adds a fatal error message to the report. Meant to be called outside of rules. + * @param {LintProblem} descriptor The descriptor for the fatal error message. + * @returns {LintMessage} The created message object. + */ + addFatal(descriptor) { + const message = createLintingProblem(descriptor, 2, this.#language); + message.fatal = true; + this.messages.push(message); + return message; + } + + /** + * Adds a warning message to the report. Meant to be called outside of rules. + * @param {LintProblem} descriptor The descriptor for the warning message. + * @returns {LintMessage} The created message object. + */ + addWarning(descriptor) { + const message = createLintingProblem(descriptor, 1, this.#language); + this.messages.push(message); + return message; + } +} + +module.exports = { + FileReport, + updateLocationInformation, +}; diff --git a/tools/ui/node_modules/eslint/lib/linter/index.js b/tools/ui/node_modules/eslint/lib/linter/index.js new file mode 100644 index 0000000000000000000000000000000000000000..5a86f71cd13b36fe44c30f401334ca0d4f5ea41e --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/linter/index.js @@ -0,0 +1,11 @@ +"use strict"; + +const { Linter } = require("./linter"); +const SourceCodeFixer = require("./source-code-fixer"); + +module.exports = { + Linter, + + // For testers. + SourceCodeFixer, +}; diff --git a/tools/ui/node_modules/eslint/lib/linter/interpolate.js b/tools/ui/node_modules/eslint/lib/linter/interpolate.js new file mode 100644 index 0000000000000000000000000000000000000000..6327f76e7f1e69bc66d0c3727fa26f7465982fe3 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/linter/interpolate.js @@ -0,0 +1,50 @@ +/** + * @fileoverview Interpolate keys from an object into a string with {{ }} markers. + * @author Jed Fox + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Returns a global expression matching placeholders in messages. + * @returns {RegExp} Global regular expression matching placeholders + */ +function getPlaceholderMatcher() { + return /\{\{([^{}]+)\}\}/gu; +} + +/** + * Replaces {{ placeholders }} in the message with the provided data. + * Does not replace placeholders not available in the data. + * @param {string} text Original message with potential placeholders + * @param {Record} data Map of placeholder name to its value + * @returns {string} Message with replaced placeholders + */ +function interpolate(text, data) { + if (!data) { + return text; + } + + const matcher = getPlaceholderMatcher(); + + // Substitution content for any {{ }} markers. + return text.replace(matcher, (fullMatch, termWithWhitespace) => { + const term = termWithWhitespace.trim(); + + if (term in data) { + return data[term]; + } + + // Preserve old behavior: If parameter name not provided, don't replace it. + return fullMatch; + }); +} + +module.exports = { + getPlaceholderMatcher, + interpolate, +}; diff --git a/tools/ui/node_modules/eslint/lib/linter/linter.js b/tools/ui/node_modules/eslint/lib/linter/linter.js new file mode 100644 index 0000000000000000000000000000000000000000..59d8fab593ddcb1b1ab12163d71e8d3e5a2112a3 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/linter/linter.js @@ -0,0 +1,2676 @@ +/** + * @fileoverview Main Linter Class + * @author Gyandeep Singh + * @author aladdin-add + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const path = require("node:path"), + eslintScope = require("eslint-scope"), + evk = require("eslint-visitor-keys"), + espree = require("espree"), + merge = require("lodash.merge"), + pkg = require("../../package.json"), + { + Legacy: { + ConfigOps, + ConfigValidator, + environments: BuiltInEnvironments, + }, + } = require("@eslint/eslintrc/universal"), + Traverser = require("../shared/traverser"), + { SourceCode } = require("../languages/js/source-code"), + applyDisableDirectives = require("./apply-disable-directives"), + { ConfigCommentParser } = require("@eslint/plugin-kit"), + Rules = require("./rules"), + SourceCodeFixer = require("./source-code-fixer"), + { SourceCodeVisitor } = require("./source-code-visitor"), + timing = require("./timing"); +const { FlatConfigArray } = require("../config/flat-config-array"); +const { startTime, endTime } = require("../shared/stats"); +const { assertIsRuleSeverity } = require("../config/flat-config-schema"); +const { + normalizeSeverityToString, + normalizeSeverityToNumber, +} = require("../shared/severity"); +const { deepMergeArrays } = require("../shared/deep-merge-arrays"); +const jslang = require("../languages/js"); +const { + activeFlags, + inactiveFlags, + getInactivityReasonMessage, +} = require("../shared/flags"); +const debug = require("debug")("eslint:linter"); +const MAX_AUTOFIX_PASSES = 10; +const DEFAULT_PARSER_NAME = "espree"; +const DEFAULT_ECMA_VERSION = 5; +const commentParser = new ConfigCommentParser(); +const parserSymbol = Symbol.for("eslint.RuleTester.parser"); +const { LATEST_ECMA_VERSION } = require("../../conf/ecma-version"); +const { VFile } = require("./vfile"); +const { ParserService } = require("../services/parser-service"); +const { FileContext } = require("./file-context"); +const { ProcessorService } = require("../services/processor-service"); +const { containsDifferentProperty } = require("../shared/option-utils"); +const { Config } = require("../config/config"); +const { WarningService } = require("../services/warning-service"); +const { SourceCodeTraverser } = require("./source-code-traverser"); +const { FileReport, updateLocationInformation } = require("./file-report"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** @import { Language, LanguageOptions, RuleConfig, RuleDefinition, RuleSeverity } from "@eslint/core" */ + +/** @typedef {import("../types").Linter.Config} Config */ +/** @typedef {import("../types").ESLint.ConfigData} ConfigData */ +/** @typedef {import("../types").ESLint.Environment} Environment */ +/** @typedef {import("../types").Linter.GlobalConf} GlobalConf */ +/** @typedef {import("../types").Linter.LanguageOptions} JSLanguageOptions */ +/** @typedef {import("../types").Linter.LintMessage} LintMessage */ +/** @typedef {import("../types").Linter.Parser} Parser */ +/** @typedef {import("../types").Linter.ParserOptions} ParserOptions */ +/** @typedef {import("../types").Linter.Processor} Processor */ +/** @typedef {import("../types").Rule.RuleModule} Rule */ +/** @typedef {import("../types").Linter.StringSeverity} StringSeverity */ +/** @typedef {import("../types").Linter.SuppressedLintMessage} SuppressedLintMessage */ +/** @typedef {import("../types").Linter.TimePass} TimePass */ + +/* eslint-disable jsdoc/valid-types -- https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/4#issuecomment-778805577 */ +/** + * @template T + * @typedef {{ [P in keyof T]-?: T[P] }} Required + */ +/* eslint-enable jsdoc/valid-types -- https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/4#issuecomment-778805577 */ + +/** + * @typedef {Object} DisableDirective + * @property {("disable"|"enable"|"disable-line"|"disable-next-line")} type Type of directive + * @property {number} line The line number + * @property {number} column The column number + * @property {(string|null)} ruleId The rule ID + * @property {string} justification The justification of directive + */ + +/** + * The private data for `Linter` instance. + * @typedef {Object} LinterInternalSlots + * @property {ConfigArray|null} lastConfigArray The `ConfigArray` instance that the last `verify()` call used. + * @property {SourceCode|null} lastSourceCode The `SourceCode` instance that the last `verify()` call used. + * @property {SuppressedLintMessage[]} lastSuppressedMessages The `SuppressedLintMessage[]` instance that the last `verify()` call produced. + * @property {Map} parserMap The loaded parsers. + * @property {{ passes: TimePass[]; }} times The times spent on applying a rule to a file (see `stats` option). + * @property {Rules} ruleMap The loaded rules. + * @property {WarningService} warningService The warning service. + */ + +/** + * @typedef {Object} VerifyOptions + * @property {boolean} [allowInlineConfig] Allow/disallow inline comments' ability + * to change config once it is set. Defaults to true if not supplied. + * Useful if you want to validate JS without comments overriding rules. + * @property {boolean} [disableFixes] if `true` then the linter doesn't make `fix` + * properties into the lint result. + * @property {string} [filename] the filename of the source code. + * @property {boolean | "off" | "warn" | "error"} [reportUnusedDisableDirectives] Adds reported errors for + * unused `eslint-disable` directives. + * @property {Function} [ruleFilter] A predicate function that determines whether a given rule should run. + */ + +/** + * @typedef {Object} ProcessorOptions + * @property {(filename:string, text:string) => boolean} [filterCodeBlock] the + * predicate function that selects adopt code blocks. + * @property {Processor.postprocess} [postprocess] postprocessor for report + * messages. If provided, this should accept an array of the message lists + * for each code block returned from the preprocessor, apply a mapping to + * the messages as appropriate, and return a one-dimensional array of + * messages. + * @property {Processor.preprocess} [preprocess] preprocessor for source text. + * If provided, this should accept a string of source text, and return an + * array of code blocks to lint. + */ + +/** + * @typedef {Object} FixOptions + * @property {boolean | ((message: LintMessage) => boolean)} [fix] Determines + * whether fixes should be applied. + */ + +/** + * @typedef {Object} InternalOptions + * @property {string | null} warnInlineConfig The config name what `noInlineConfig` setting came from. If `noInlineConfig` setting didn't exist, this is null. If this is a config name, then the linter warns directive comments. + * @property {StringSeverity} reportUnusedDisableDirectives Severity to report unused disable directives, if not "off" (boolean values were normalized). + * @property {StringSeverity} reportUnusedInlineConfigs Severity to report unused inline configs, if not "off". + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Determines if a given object is Espree. + * @param {Object} parser The parser to check. + * @returns {boolean} True if the parser is Espree or false if not. + */ +function isEspree(parser) { + return !!(parser === espree || parser[parserSymbol] === espree); +} + +/** + * Ensures that variables representing built-in properties of the Global Object, + * and any globals declared by special block comments, are present in the global + * scope. + * @param {Scope} globalScope The global scope. + * @param {Object} configGlobals The globals declared in configuration + * @param {{exportedVariables: Object, enabledGlobals: Object}} commentDirectives Directives from comment configuration + * @returns {void} + */ +function addDeclaredGlobals( + globalScope, + configGlobals, + { exportedVariables, enabledGlobals }, +) { + // Define configured global variables. + for (const id of new Set([ + ...Object.keys(configGlobals), + ...Object.keys(enabledGlobals), + ])) { + /* + * `ConfigOps.normalizeConfigGlobal` will throw an error if a configured global value is invalid. However, these errors would + * typically be caught when validating a config anyway (validity for inline global comments is checked separately). + */ + const configValue = + configGlobals[id] === void 0 + ? void 0 + : ConfigOps.normalizeConfigGlobal(configGlobals[id]); + const commentValue = enabledGlobals[id] && enabledGlobals[id].value; + const value = commentValue || configValue; + const sourceComments = + enabledGlobals[id] && enabledGlobals[id].comments; + + if (value === "off") { + continue; + } + + let variable = globalScope.set.get(id); + + if (!variable) { + variable = new eslintScope.Variable(id, globalScope); + + globalScope.variables.push(variable); + globalScope.set.set(id, variable); + } + + variable.eslintImplicitGlobalSetting = configValue; + variable.eslintExplicitGlobal = sourceComments !== void 0; + variable.eslintExplicitGlobalComments = sourceComments; + variable.writeable = value === "writable"; + } + + // mark all exported variables as such + Object.keys(exportedVariables).forEach(name => { + const variable = globalScope.set.get(name); + + if (variable) { + variable.eslintUsed = true; + variable.eslintExported = true; + } + }); + + /* + * "through" contains all references which definitions cannot be found. + * Since we augment the global scope using configuration, we need to update + * references and remove the ones that were added by configuration. + */ + globalScope.through = globalScope.through.filter(reference => { + const name = reference.identifier.name; + const variable = globalScope.set.get(name); + + if (variable) { + /* + * Links the variable and the reference. + * And this reference is removed from `Scope#through`. + */ + reference.resolved = variable; + variable.references.push(reference); + + return false; + } + + return true; + }); +} + +/** + * Wraps the value in an Array if it isn't already one. + * @template T + * @param {T|T[]} value Value to be wrapped. + * @returns {Array} The value as an array. + */ +function asArray(value) { + return Array.isArray(value) ? value : [value]; +} + +/** + * Pushes a problem to inlineConfigProblems if ruleOptions are redundant. + * @param {Config} config Provided config. + * @param {Object} loc A line/column location + * @param {FileReport} report Report that may be added to. + * @param {string} ruleId The rule ID. + * @param {Array} ruleOptions The rule options, merged with the config's. + * @param {Array} ruleOptionsInline The rule options from the comment. + * @param {"error"|"warn"} severity The severity to report. + * @returns {void} + */ +function addProblemIfSameSeverityAndOptions( + config, + loc, + report, + ruleId, + ruleOptions, + ruleOptionsInline, + severity, +) { + const existingConfigRaw = config.rules?.[ruleId]; + const existingConfig = existingConfigRaw + ? asArray(existingConfigRaw) + : ["off"]; + const existingSeverity = normalizeSeverityToString(existingConfig[0]); + const inlineSeverity = normalizeSeverityToString(ruleOptions[0]); + const sameSeverity = existingSeverity === inlineSeverity; + + if (!sameSeverity) { + return; + } + + const alreadyConfigured = existingConfigRaw + ? `is already configured to '${existingSeverity}'` + : "is not enabled so can't be turned off"; + let message; + + if ( + (existingConfig.length === 1 && ruleOptions.length === 1) || + existingSeverity === "off" + ) { + message = `Unused inline config ('${ruleId}' ${alreadyConfigured}).`; + } else if ( + !containsDifferentProperty( + ruleOptions.slice(1), + existingConfig.slice(1), + ) + ) { + message = + ruleOptionsInline.length === 1 + ? `Unused inline config ('${ruleId}' ${alreadyConfigured}).` + : `Unused inline config ('${ruleId}' ${alreadyConfigured} with the same options).`; + } + + if (message) { + const numericSeverity = normalizeSeverityToNumber(severity); + const descriptor = { + message, + loc, + }; + + if (numericSeverity === 1) { + report.addWarning(descriptor); + } else if (numericSeverity === 2) { + report.addError(descriptor); + } + } +} + +/** + * Creates a collection of disable directives from a comment + * @param {Object} options to create disable directives + * @param {("disable"|"enable"|"disable-line"|"disable-next-line")} options.type The type of directive comment + * @param {string} options.value The value after the directive in the comment + * comment specified no specific rules, so it applies to all rules (e.g. `eslint-disable`) + * @param {string} options.justification The justification of the directive + * @param {ASTNode|token} options.node The Comment node/token. + * @param {function(string): {create: Function}} ruleMapper A map from rule IDs to defined rules + * @param {Language} language The language to use to adjust the location information. + * @param {SourceCode} sourceCode The SourceCode object to get comments from. + * @param {FileReport} report The report to add problems to. + * @returns {Object[]} Directives from the comment + */ +function createDisableDirectives( + { type, value, justification, node }, + ruleMapper, + language, + sourceCode, + report, +) { + const ruleIds = Object.keys(commentParser.parseListConfig(value)); + const directiveRules = ruleIds.length ? ruleIds : [null]; + const directives = []; // valid disable directives + const parentDirective = { node, value, ruleIds }; + + for (const ruleId of directiveRules) { + const loc = sourceCode.getLoc(node); + + // push to directives, if the rule is defined(including null, e.g. /*eslint enable*/) + if (ruleId === null || !!ruleMapper(ruleId)) { + if (type === "disable-next-line") { + const { line, column } = updateLocationInformation( + loc.end, + language, + ); + + directives.push({ + parentDirective, + type, + line, + column, + ruleId, + justification, + }); + } else { + const { line, column } = updateLocationInformation( + loc.start, + language, + ); + + directives.push({ + parentDirective, + type, + line, + column, + ruleId, + justification, + }); + } + } else { + report.addError({ ruleId, loc }); + } + } + + return directives; +} + +/** + * Parses comments in file to extract file-specific config of rules, globals + * and environments and merges them with global config; also code blocks + * where reporting is disabled or enabled and merges them with reporting config. + * @param {SourceCode} sourceCode The SourceCode object to get comments from. + * @param {function(string): {create: Function}} ruleMapper A map from rule IDs to defined rules + * @param {string|null} warnInlineConfig If a string then it should warn directive comments as disabled. The string value is the config name what the setting came from. + * @param {ConfigData} config Provided config. + * @param {FileReport} report The report to add problems to. + * @returns {{configuredRules: Object, enabledGlobals: {value:string,comment:Token}[], exportedVariables: Object, disableDirectives: DisableDirective[]}} + * A collection of the directive comments that were found, along with any problems that occurred when parsing + */ +function getDirectiveComments( + sourceCode, + ruleMapper, + warnInlineConfig, + config, + report, +) { + const configuredRules = {}; + const enabledGlobals = Object.create(null); + const exportedVariables = {}; + const disableDirectives = []; + const validator = new ConfigValidator({ + builtInRules: Rules, + }); + + sourceCode + .getInlineConfigNodes() + .filter(token => token.type !== "Shebang") + .forEach(comment => { + const directive = commentParser.parseDirective(comment.value); + + if (!directive) { + return; + } + + const { + label, + value, + justification: justificationPart, + } = directive; + + const lineCommentSupported = + /^eslint-disable-(?:next-)?line$/u.test(label); + + if (comment.type === "Line" && !lineCommentSupported) { + return; + } + + const loc = sourceCode.getLoc(comment); + + if (warnInlineConfig) { + const kind = + comment.type === "Block" ? `/*${label}*/` : `//${label}`; + + report.addWarning({ + ruleId: null, + message: `'${kind}' has no effect because you have 'noInlineConfig' setting in ${warnInlineConfig}.`, + loc, + }); + return; + } + + if ( + label === "eslint-disable-line" && + loc.start.line !== loc.end.line + ) { + const message = `${label} comment should not span multiple lines.`; + + report.addError({ + message, + loc, + }); + return; + } + + switch (label) { + case "eslint-disable": + case "eslint-enable": + case "eslint-disable-next-line": + case "eslint-disable-line": { + const directiveType = label.slice("eslint-".length); + const directives = createDisableDirectives( + { + type: directiveType, + value, + justification: justificationPart, + node: comment, + }, + ruleMapper, + jslang, + sourceCode, + report, + ); + + disableDirectives.push(...directives); + break; + } + + case "exported": + Object.assign( + exportedVariables, + commentParser.parseListConfig(value), + ); + break; + + case "globals": + case "global": + for (const [id, idSetting] of Object.entries( + commentParser.parseStringConfig(value), + )) { + let normalizedValue; + + try { + normalizedValue = + ConfigOps.normalizeConfigGlobal(idSetting); + } catch (err) { + report.addError({ + loc, + message: err.message, + }); + continue; + } + + if (enabledGlobals[id]) { + enabledGlobals[id].comments.push(comment); + enabledGlobals[id].value = normalizedValue; + } else { + enabledGlobals[id] = { + comments: [comment], + value: normalizedValue, + }; + } + } + break; + + case "eslint": { + const parseResult = + commentParser.parseJSONLikeConfig(value); + + if (parseResult.ok) { + Object.keys(parseResult.config).forEach(name => { + const rule = ruleMapper(name); + const ruleValue = parseResult.config[name]; + + if (!rule) { + report.addError({ ruleId: name, loc }); + return; + } + + if (Object.hasOwn(configuredRules, name)) { + report.addError({ + message: `Rule "${name}" is already configured by another configuration comment in the preceding code. This configuration is ignored.`, + loc, + }); + return; + } + + let ruleOptions = asArray(ruleValue); + + /* + * If the rule was already configured, inline rule configuration that + * only has severity should retain options from the config and just override the severity. + * + * Example: + * + * { + * rules: { + * curly: ["error", "multi"] + * } + * } + * + * /* eslint curly: ["warn"] * / + * + * Results in: + * + * curly: ["warn", "multi"] + */ + if ( + /* + * If inline config for the rule has only severity + */ + ruleOptions.length === 1 && + /* + * And the rule was already configured + */ + config.rules && + Object.hasOwn(config.rules, name) + ) { + /* + * Then use severity from the inline config and options from the provided config + */ + ruleOptions = [ + ruleOptions[0], // severity from the inline config + ...asArray(config.rules[name]).slice(1), // options from the provided config + ]; + } + + try { + validator.validateRuleOptions( + rule, + name, + ruleOptions, + ); + } catch (err) { + /* + * If the rule has invalid `meta.schema`, throw the error because + * this is not an invalid inline configuration but an invalid rule. + */ + if ( + err.code === + "ESLINT_INVALID_RULE_OPTIONS_SCHEMA" + ) { + throw err; + } + + report.addError({ + ruleId: name, + message: err.message, + loc, + }); + + // do not apply the config, if found invalid options. + return; + } + + configuredRules[name] = ruleOptions; + }); + } else { + report.addFatal({ + loc, + message: parseResult.error.message, + }); + } + + break; + } + + // no default + } + }); + + return { + configuredRules, + enabledGlobals, + exportedVariables, + disableDirectives, + }; +} + +/** + * Parses comments in file to extract disable directives. + * @param {SourceCode} sourceCode The SourceCode object to get comments from. + * @param {function(string): {create: Function}} ruleMapper A map from rule IDs to defined rules + * @param {Language} language The language to use to adjust the location information + * @param {FileReport} report The report to add problems to. + * @returns {DisableDirective[]} + * A collection of the directive comments that were found, along with any problems that occurred when parsing + */ +function getDirectiveCommentsForFlatConfig( + sourceCode, + ruleMapper, + language, + report, +) { + const disableDirectives = []; + + if (sourceCode.getDisableDirectives) { + const { directives: directivesSources, problems: directivesProblems } = + sourceCode.getDisableDirectives(); + + if (Array.isArray(directivesProblems)) { + directivesProblems.forEach(problem => report.addError(problem)); + } + + directivesSources.forEach(directive => { + const directives = createDisableDirectives( + directive, + ruleMapper, + language, + sourceCode, + report, + ); + + disableDirectives.push(...directives); + }); + } + + return disableDirectives; +} + +/** + * Normalize ECMAScript version from the initial config + * @param {Parser} parser The parser which uses this options. + * @param {number} ecmaVersion ECMAScript version from the initial config + * @returns {number} normalized ECMAScript version + */ +function normalizeEcmaVersion(parser, ecmaVersion) { + if (isEspree(parser)) { + if (ecmaVersion === "latest") { + return espree.latestEcmaVersion; + } + } + + /* + * Calculate ECMAScript edition number from official year version starting with + * ES2015, which corresponds with ES6 (or a difference of 2009). + */ + return ecmaVersion >= 2015 ? ecmaVersion - 2009 : ecmaVersion; +} + +/** + * Normalize ECMAScript version from the initial config into languageOptions (year) + * format. + * @param {any} [ecmaVersion] ECMAScript version from the initial config + * @returns {number} normalized ECMAScript version + */ +function normalizeEcmaVersionForLanguageOptions(ecmaVersion) { + switch (ecmaVersion) { + case 3: + return 3; + + // void 0 = no ecmaVersion specified so use the default + case 5: + case void 0: + return 5; + + default: + if (typeof ecmaVersion === "number") { + return ecmaVersion >= 2015 ? ecmaVersion : ecmaVersion + 2009; + } + } + + /* + * We default to the latest supported ecmaVersion for everything else. + * Remember, this is for languageOptions.ecmaVersion, which sets the version + * that is used for a number of processes inside of ESLint. It's normally + * safe to assume people want the latest unless otherwise specified. + */ + return LATEST_ECMA_VERSION; +} + +const eslintEnvPattern = /\/\*\s*eslint-env\s.+?(?:\*\/|$)/gsu; + +/** + * Checks whether or not there is a comment which has "eslint-env *" in a given text. + * @param {string} text A source code text to check. + * @returns {Object|null} A result of parseListConfig() with "eslint-env *" comment. + */ +function findEslintEnv(text) { + let match, retv; + + eslintEnvPattern.lastIndex = 0; + + while ((match = eslintEnvPattern.exec(text)) !== null) { + if (match[0].endsWith("*/")) { + retv = Object.assign( + retv || {}, + commentParser.parseListConfig( + commentParser.parseDirective(match[0].slice(2, -2)).value, + ), + ); + } + } + + return retv; +} + +/** + * Convert "/path/to/" to "". + * `CLIEngine#executeOnText()` method gives "/path/to/" if the filename + * was omitted because `configArray.extractConfig()` requires an absolute path. + * But the linter should pass `` to `RuleContext#filename` in that + * case. + * Also, code blocks can have their virtual filename. If the parent filename was + * ``, the virtual filename is `/0_foo.js` or something like (i.e., + * it's not an absolute path). + * @param {string} filename The filename to normalize. + * @returns {string} The normalized filename. + */ +function normalizeFilename(filename) { + const parts = filename.split(path.sep); + const index = parts.lastIndexOf(""); + + return index === -1 ? filename : parts.slice(index).join(path.sep); +} + +/** + * Normalizes the possible options for `linter.verify` and `linter.verifyAndFix` to a + * consistent shape. + * @param {VerifyOptions} providedOptions Options + * @param {Config|ConfigData} config Config. + * @returns {Required & InternalOptions} Normalized options + */ +function normalizeVerifyOptions(providedOptions, config) { + const linterOptions = config.linterOptions || config; + + // .noInlineConfig for eslintrc, .linterOptions.noInlineConfig for flat + const disableInlineConfig = linterOptions.noInlineConfig === true; + const ignoreInlineConfig = providedOptions.allowInlineConfig === false; + const configNameOfNoInlineConfig = config.configNameOfNoInlineConfig + ? ` (${config.configNameOfNoInlineConfig})` + : ""; + + let reportUnusedDisableDirectives = + providedOptions.reportUnusedDisableDirectives; + + if (typeof reportUnusedDisableDirectives === "boolean") { + reportUnusedDisableDirectives = reportUnusedDisableDirectives + ? "error" + : "off"; + } + if (typeof reportUnusedDisableDirectives !== "string") { + if (typeof linterOptions.reportUnusedDisableDirectives === "boolean") { + reportUnusedDisableDirectives = + linterOptions.reportUnusedDisableDirectives ? "warn" : "off"; + } else { + reportUnusedDisableDirectives = + linterOptions.reportUnusedDisableDirectives === void 0 + ? "off" + : normalizeSeverityToString( + linterOptions.reportUnusedDisableDirectives, + ); + } + } + + const reportUnusedInlineConfigs = + linterOptions.reportUnusedInlineConfigs === void 0 + ? "off" + : normalizeSeverityToString( + linterOptions.reportUnusedInlineConfigs, + ); + + let ruleFilter = providedOptions.ruleFilter; + + if (typeof ruleFilter !== "function") { + ruleFilter = () => true; + } + + return { + filename: normalizeFilename(providedOptions.filename || ""), + allowInlineConfig: !ignoreInlineConfig, + warnInlineConfig: + disableInlineConfig && !ignoreInlineConfig + ? `your config${configNameOfNoInlineConfig}` + : null, + reportUnusedDisableDirectives, + reportUnusedInlineConfigs, + disableFixes: Boolean(providedOptions.disableFixes), + stats: providedOptions.stats, + ruleFilter, + }; +} + +/** + * Combines the provided parserOptions with the options from environments + * @param {Parser} parser The parser which uses this options. + * @param {ParserOptions} providedOptions The provided 'parserOptions' key in a config + * @param {Environment[]} enabledEnvironments The environments enabled in configuration and with inline comments + * @returns {ParserOptions} Resulting parser options after merge + */ +function resolveParserOptions(parser, providedOptions, enabledEnvironments) { + const parserOptionsFromEnv = enabledEnvironments + .filter(env => env.parserOptions) + .reduce( + (parserOptions, env) => merge(parserOptions, env.parserOptions), + {}, + ); + const mergedParserOptions = merge( + parserOptionsFromEnv, + providedOptions || {}, + ); + const isModule = mergedParserOptions.sourceType === "module"; + + if (isModule) { + /* + * can't have global return inside of modules + * TODO: espree validate parserOptions.globalReturn when sourceType is setting to module.(@aladdin-add) + */ + mergedParserOptions.ecmaFeatures = Object.assign( + {}, + mergedParserOptions.ecmaFeatures, + { globalReturn: false }, + ); + } + + mergedParserOptions.ecmaVersion = normalizeEcmaVersion( + parser, + mergedParserOptions.ecmaVersion, + ); + + return mergedParserOptions; +} + +/** + * Converts parserOptions to languageOptions for backwards compatibility with eslintrc. + * @param {ConfigData} config Config object. + * @param {Object} config.globals Global variable definitions. + * @param {Parser} config.parser The parser to use. + * @param {ParserOptions} config.parserOptions The parserOptions to use. + * @returns {JSLanguageOptions} The languageOptions equivalent. + */ +function createLanguageOptions({ + globals: configuredGlobals, + parser, + parserOptions, +}) { + const { ecmaVersion, sourceType } = parserOptions; + + return { + globals: configuredGlobals, + ecmaVersion: normalizeEcmaVersionForLanguageOptions(ecmaVersion), + sourceType, + parser, + parserOptions, + }; +} + +/** + * Combines the provided globals object with the globals from environments + * @param {Record} providedGlobals The 'globals' key in a config + * @param {Environment[]} enabledEnvironments The environments enabled in configuration and with inline comments + * @returns {Record} The resolved globals object + */ +function resolveGlobals(providedGlobals, enabledEnvironments) { + return Object.assign( + Object.create(null), + ...enabledEnvironments + .filter(env => env.globals) + .map(env => env.globals), + providedGlobals, + ); +} + +/** + * Store time measurements in map + * @param {number} time Time measurement + * @param {Object} timeOpts Options relating which time was measured + * @param {WeakMap} slots Linter internal slots map + * @returns {void} + */ +function storeTime(time, timeOpts, slots) { + const { type, key } = timeOpts; + + if (!slots.times) { + slots.times = { passes: [{}] }; + } + + const passIndex = slots.fixPasses; + + if (passIndex > slots.times.passes.length - 1) { + slots.times.passes.push({}); + } + + if (key) { + slots.times.passes[passIndex][type] ??= {}; + slots.times.passes[passIndex][type][key] ??= { total: 0 }; + slots.times.passes[passIndex][type][key].total += time; + } else { + slots.times.passes[passIndex][type] ??= { total: 0 }; + slots.times.passes[passIndex][type].total += time; + } +} + +/** + * Get the options for a rule (not including severity), if any + * @param {RuleConfig} ruleConfig rule configuration + * @param {Object|undefined} defaultOptions rule.meta.defaultOptions + * @returns {Array} of rule options, empty Array if none + */ +function getRuleOptions(ruleConfig, defaultOptions) { + if (Array.isArray(ruleConfig)) { + return deepMergeArrays(defaultOptions, ruleConfig.slice(1)); + } + return defaultOptions ?? []; +} + +/** + * Analyze scope of the given AST. + * @param {ASTNode} ast The `Program` node to analyze. + * @param {JSLanguageOptions} languageOptions The language options. + * @param {Record} visitorKeys The visitor keys. + * @returns {ScopeManager} The analysis result. + */ +function analyzeScope(ast, languageOptions, visitorKeys) { + const parserOptions = languageOptions.parserOptions; + const ecmaFeatures = parserOptions.ecmaFeatures || {}; + const ecmaVersion = languageOptions.ecmaVersion || DEFAULT_ECMA_VERSION; + + return eslintScope.analyze(ast, { + ignoreEval: true, + nodejsScope: ecmaFeatures.globalReturn, + impliedStrict: ecmaFeatures.impliedStrict, + ecmaVersion: typeof ecmaVersion === "number" ? ecmaVersion : 6, + sourceType: languageOptions.sourceType || "script", + childVisitorKeys: visitorKeys || evk.KEYS, + fallback: Traverser.getKeys, + }); +} + +/** + * Runs a rule, and gets its listeners + * @param {RuleDefinition} rule A rule object + * @param {Context} ruleContext The context that should be passed to the rule + * @throws {TypeError} If `rule` is not an object with a `create` method + * @throws {any} Any error during the rule's `create` + * @returns {Object} A map of selector listeners provided by the rule + */ +function createRuleListeners(rule, ruleContext) { + if ( + !rule || + typeof rule !== "object" || + typeof rule.create !== "function" + ) { + throw new TypeError( + `Error while loading rule '${ruleContext.id}': Rule must be an object with a \`create\` method`, + ); + } + + try { + return rule.create(ruleContext); + } catch (ex) { + ex.message = `Error while loading rule '${ruleContext.id}': ${ex.message}`; + throw ex; + } +} + +/** + * Runs the given rules on the given SourceCode object + * @param {SourceCode} sourceCode A SourceCode object for the given text + * @param {Object} configuredRules The rules configuration + * @param {function(string): RuleDefinition} ruleMapper A mapper function from rule names to rules + * @param {string | undefined} parserName The name of the parser in the config + * @param {Language} language The language object used for parsing. + * @param {LanguageOptions} languageOptions The options for parsing the code. + * @param {Object} settings The settings that were enabled in the config + * @param {string} filename The reported filename of the code + * @param {boolean} applyDefaultOptions If true, apply rules' meta.defaultOptions in computing their config options. + * @param {string | undefined} cwd cwd of the cli + * @param {string} physicalFilename The full path of the file on disk without any code block information + * @param {Function} ruleFilter A predicate function to filter which rules should be executed. + * @param {boolean} stats If true, stats are collected appended to the result + * @param {WeakMap} slots InternalSlotsMap of linter + * @param {FileReport} report The report to add problems to + * @returns {FileReport} report The report with added problems + * @throws {Error} If traversal into a node fails. + */ +function runRules( + sourceCode, + configuredRules, + ruleMapper, + parserName, + language, + languageOptions, + settings, + filename, + applyDefaultOptions, + cwd, + physicalFilename, + ruleFilter, + stats, + slots, + report, +) { + const visitor = new SourceCodeVisitor(); + + /* + * Create a frozen object with the ruleContext properties and methods that are shared by all rules. + * All rule contexts will inherit from this object. This avoids the performance penalty of copying all the + * properties once for each rule. + */ + const fileContext = new FileContext({ + cwd, + filename, + physicalFilename: physicalFilename || filename, + sourceCode, + parserOptions: { + ...languageOptions.parserOptions, + }, + parserPath: parserName, + languageOptions, + settings, + }); + + const steps = sourceCode.traverse(); + + Object.keys(configuredRules).forEach(ruleId => { + const severity = Config.getRuleNumericSeverity(configuredRules[ruleId]); + + // not load disabled rules + if (severity === 0) { + return; + } + + if (ruleFilter && !ruleFilter({ ruleId, severity })) { + return; + } + + const rule = ruleMapper(ruleId); + + if (!rule) { + report.addError({ ruleId }); + return; + } + + const ruleContext = fileContext.extend({ + id: ruleId, + options: getRuleOptions( + configuredRules[ruleId], + applyDefaultOptions ? rule.meta?.defaultOptions : void 0, + ), + report(...args) { + const problem = report.addRuleMessage( + ruleId, + severity, + ...args, + ); + + if (problem.fix && !(rule.meta && rule.meta.fixable)) { + throw new Error( + 'Fixable rules must set the `meta.fixable` property to "code" or "whitespace".', + ); + } + + if ( + problem.suggestions && + !(rule.meta && rule.meta.hasSuggestions === true) + ) { + if ( + rule.meta && + rule.meta.docs && + typeof rule.meta.docs.suggestion !== "undefined" + ) { + // Encourage migration from the former property name. + throw new Error( + "Rules with suggestions must set the `meta.hasSuggestions` property to `true`. `meta.docs.suggestion` is ignored by ESLint.", + ); + } + throw new Error( + "Rules with suggestions must set the `meta.hasSuggestions` property to `true`.", + ); + } + }, + }); + + const ruleListenersReturn = + timing.enabled || stats + ? timing.time( + ruleId, + createRuleListeners, + stats, + )(rule, ruleContext) + : createRuleListeners(rule, ruleContext); + + const ruleListeners = stats + ? ruleListenersReturn.result + : ruleListenersReturn; + + if (stats) { + storeTime( + ruleListenersReturn.tdiff, + { type: "rules", key: ruleId }, + slots, + ); + } + + /** + * Include `ruleId` in error logs + * @param {Function} ruleListener A rule method that listens for a node. + * @returns {Function} ruleListener wrapped in error handler + */ + function addRuleErrorHandler(ruleListener) { + return function ruleErrorHandler(...listenerArgs) { + try { + const ruleListenerReturn = ruleListener(...listenerArgs); + + const ruleListenerResult = stats + ? ruleListenerReturn.result + : ruleListenerReturn; + + if (stats) { + storeTime( + ruleListenerReturn.tdiff, + { type: "rules", key: ruleId }, + slots, + ); + } + + return ruleListenerResult; + } catch (e) { + e.ruleId = ruleId; + throw e; + } + }; + } + + if (typeof ruleListeners === "undefined" || ruleListeners === null) { + throw new Error( + `The create() function for rule '${ruleId}' did not return an object.`, + ); + } + + // add all the selectors from the rule as listeners + Object.keys(ruleListeners).forEach(selector => { + const ruleListener = + timing.enabled || stats + ? timing.time(ruleId, ruleListeners[selector], stats) + : ruleListeners[selector]; + + visitor.add(selector, addRuleErrorHandler(ruleListener)); + }); + }); + + const traverser = SourceCodeTraverser.getInstance(language); + + traverser.traverseSync(sourceCode, visitor, { steps }); + + return report; +} + +/** + * Ensure the source code to be a string. + * @param {string|SourceCode} textOrSourceCode The text or source code object. + * @returns {string} The source code text. + */ +function ensureText(textOrSourceCode) { + if (typeof textOrSourceCode === "object") { + const { hasBOM, text } = textOrSourceCode; + const bom = hasBOM ? "\uFEFF" : ""; + + return bom + text; + } + + return String(textOrSourceCode); +} + +/** + * Get an environment. + * @param {LinterInternalSlots} slots The internal slots of Linter. + * @param {string} envId The environment ID to get. + * @returns {Environment|null} The environment. + */ +function getEnv(slots, envId) { + return ( + (slots.lastConfigArray && + slots.lastConfigArray.pluginEnvironments.get(envId)) || + BuiltInEnvironments.get(envId) || + null + ); +} + +/** + * Get a rule. + * @param {LinterInternalSlots} slots The internal slots of Linter. + * @param {string} ruleId The rule ID to get. + * @returns {Rule|null} The rule. + */ +function getRule(slots, ruleId) { + return ( + (slots.lastConfigArray && + slots.lastConfigArray.pluginRules.get(ruleId)) || + slots.ruleMap.get(ruleId) + ); +} + +/** + * Normalize the value of the cwd + * @param {string | undefined} cwd raw value of the cwd, path to a directory that should be considered as the current working directory, can be undefined. + * @returns {string | undefined} normalized cwd + */ +function normalizeCwd(cwd) { + if (cwd) { + return cwd; + } + if (typeof process === "object") { + return process.cwd(); + } + + // It's more explicit to assign the undefined + // eslint-disable-next-line no-undefined -- Consistently returning a value + return undefined; +} + +/** + * The map to store private data. + * @type {WeakMap} + */ +const internalSlotsMap = new WeakMap(); + +/** + * Throws an error when the given linter is in flat config mode. + * @param {Linter} linter The linter to check. + * @returns {void} + * @throws {Error} If the linter is in flat config mode. + */ +function assertEslintrcConfig(linter) { + const { configType } = internalSlotsMap.get(linter); + + if (configType === "flat") { + throw new Error( + "This method cannot be used with flat config. Add your entries directly into the config array.", + ); + } +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Object that is responsible for verifying JavaScript text + * @name Linter + */ +class Linter { + /** + * Initialize the Linter. + * @param {Object} [config] the config object + * @param {string} [config.cwd] path to a directory that should be considered as the current working directory, can be undefined. + * @param {Array} [config.flags] the feature flags to enable. + * @param {"flat"|"eslintrc"} [config.configType="flat"] the type of config used. + * @param {WarningService} [config.warningService] The warning service to use. + */ + constructor({ + cwd, + configType = "flat", + flags = [], + warningService = new WarningService(), + } = {}) { + const processedFlags = []; + + flags.forEach(flag => { + if (inactiveFlags.has(flag)) { + const inactiveFlagData = inactiveFlags.get(flag); + const inactivityReason = + getInactivityReasonMessage(inactiveFlagData); + const message = `The flag '${flag}' is inactive: ${inactivityReason}`; + + if (typeof inactiveFlagData.replacedBy === "undefined") { + throw new Error(message); + } + + // if there's a replacement, enable it instead of original + if (typeof inactiveFlagData.replacedBy === "string") { + processedFlags.push(inactiveFlagData.replacedBy); + } + + warningService.emitInactiveFlagWarning(flag, message); + + return; + } + + if (!activeFlags.has(flag)) { + throw new Error(`Unknown flag '${flag}'.`); + } + + processedFlags.push(flag); + }); + + internalSlotsMap.set(this, { + cwd: normalizeCwd(cwd), + flags: processedFlags, + lastConfigArray: null, + lastSourceCode: null, + lastSuppressedMessages: [], + configType, // TODO: Remove after flat config conversion + parserMap: new Map([["espree", espree]]), + ruleMap: new Rules(), + warningService, + }); + + this.version = pkg.version; + } + + /** + * Getter for package version. + * @static + * @returns {string} The version from package.json. + */ + static get version() { + return pkg.version; + } + + /** + * Indicates if the given feature flag is enabled for this instance. + * @param {string} flag The feature flag to check. + * @returns {boolean} `true` if the feature flag is enabled, `false` if not. + */ + hasFlag(flag) { + return internalSlotsMap.get(this).flags.includes(flag); + } + + /** + * Lint using eslintrc and without processors. + * @param {VFile} file The file to lint. + * @param {ConfigData} providedConfig An ESLintConfig instance to configure everything. + * @param {VerifyOptions} [providedOptions] The optional filename of the file being checked. + * @throws {Error} If during rule execution. + * @returns {(LintMessage|SuppressedLintMessage)[]} The results as an array of messages or an empty array if no messages. + */ + #eslintrcVerifyWithoutProcessors(file, providedConfig, providedOptions) { + const slots = internalSlotsMap.get(this); + const config = providedConfig || {}; + const options = normalizeVerifyOptions(providedOptions, config); + + // Resolve parser. + let parserName = DEFAULT_PARSER_NAME; + let parser = espree; + + if (typeof config.parser === "object" && config.parser !== null) { + parserName = config.parser.filePath; + parser = config.parser.definition; + } else if (typeof config.parser === "string") { + if (!slots.parserMap.has(config.parser)) { + return [ + { + ruleId: null, + fatal: true, + severity: 2, + message: `Configured parser '${config.parser}' was not found.`, + line: 0, + column: 0, + nodeType: null, + }, + ]; + } + parserName = config.parser; + parser = slots.parserMap.get(config.parser); + } + + // search and apply "eslint-env *". + const envInFile = + options.allowInlineConfig && !options.warnInlineConfig + ? findEslintEnv(file.body) + : {}; + const resolvedEnvConfig = Object.assign( + { builtin: true }, + config.env, + envInFile, + ); + const enabledEnvs = Object.keys(resolvedEnvConfig) + .filter(envName => resolvedEnvConfig[envName]) + .map(envName => getEnv(slots, envName)) + .filter(env => env); + + const parserOptions = resolveParserOptions( + parser, + config.parserOptions || {}, + enabledEnvs, + ); + const configuredGlobals = resolveGlobals( + config.globals || {}, + enabledEnvs, + ); + const settings = config.settings || {}; + const languageOptions = createLanguageOptions({ + globals: config.globals, + parser, + parserOptions, + }); + + if (!slots.lastSourceCode) { + let t; + + if (options.stats) { + t = startTime(); + } + + const parserService = new ParserService(); + const parseResult = parserService.parseSync(file, { + language: jslang, + languageOptions, + }); + + if (options.stats) { + const time = endTime(t); + const timeOpts = { type: "parse" }; + + storeTime(time, timeOpts, slots); + } + + if (!parseResult.ok) { + return parseResult.errors; + } + + slots.lastSourceCode = parseResult.sourceCode; + } else { + /* + * If the given source code object as the first argument does not have scopeManager, analyze the scope. + * This is for backward compatibility (SourceCode is frozen so it cannot rebind). + */ + if (!slots.lastSourceCode.scopeManager) { + slots.lastSourceCode = new SourceCode({ + text: slots.lastSourceCode.text, + ast: slots.lastSourceCode.ast, + hasBOM: slots.lastSourceCode.hasBOM, + parserServices: slots.lastSourceCode.parserServices, + visitorKeys: slots.lastSourceCode.visitorKeys, + scopeManager: analyzeScope( + slots.lastSourceCode.ast, + languageOptions, + ), + }); + } + } + + const sourceCode = slots.lastSourceCode; + const report = new FileReport({ + ruleMapper: ruleId => getRule(slots, ruleId), + language: jslang, + sourceCode, + disableFixes: options.disableFixes, + }); + + const commentDirectives = options.allowInlineConfig + ? getDirectiveComments( + sourceCode, + ruleId => getRule(slots, ruleId), + options.warnInlineConfig, + config, + report, + ) + : { + configuredRules: {}, + enabledGlobals: {}, + exportedVariables: {}, + disableDirectives: [], + }; + + addDeclaredGlobals( + sourceCode.scopeManager.scopes[0], + configuredGlobals, + { + exportedVariables: commentDirectives.exportedVariables, + enabledGlobals: commentDirectives.enabledGlobals, + }, + ); + + const configuredRules = Object.assign( + {}, + config.rules, + commentDirectives.configuredRules, + ); + + try { + runRules( + sourceCode, + configuredRules, + ruleId => getRule(slots, ruleId), + parserName, + jslang, + languageOptions, + settings, + options.filename, + true, + slots.cwd, + providedOptions.physicalFilename, + null, + options.stats, + slots, + report, + ); + } catch (err) { + err.message += `\nOccurred while linting ${options.filename}`; + debug("An error occurred while traversing"); + debug("Filename:", options.filename); + if (err.currentNode) { + const { line } = sourceCode.getLoc(err.currentNode).start; + + debug("Line:", line); + err.message += `:${line}`; + } + debug("Parser Options:", parserOptions); + debug("Parser Path:", parserName); + debug("Settings:", settings); + + if (err.ruleId) { + err.message += `\nRule: "${err.ruleId}"`; + } + + throw err; + } + + return applyDisableDirectives({ + language: jslang, + sourceCode, + directives: commentDirectives.disableDirectives, + disableFixes: options.disableFixes, + problems: report.messages.sort( + (problemA, problemB) => + problemA.line - problemB.line || + problemA.column - problemB.column, + ), + reportUnusedDisableDirectives: + options.reportUnusedDisableDirectives, + }); + } + + /** + * Same as linter.verify, except without support for processors. + * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object. + * @param {ConfigData} providedConfig An ESLintConfig instance to configure everything. + * @param {VerifyOptions} [providedOptions] The optional filename of the file being checked. + * @throws {Error} If during rule execution. + * @returns {(LintMessage|SuppressedLintMessage)[]} The results as an array of messages or an empty array if no messages. + */ + _verifyWithoutProcessors( + textOrSourceCode, + providedConfig, + providedOptions, + ) { + const slots = internalSlotsMap.get(this); + const filename = normalizeFilename( + providedOptions.filename || "", + ); + let text; + + // evaluate arguments + if (typeof textOrSourceCode === "string") { + slots.lastSourceCode = null; + text = textOrSourceCode; + } else { + slots.lastSourceCode = textOrSourceCode; + text = textOrSourceCode.text; + } + + const file = new VFile(filename, text, { + physicalPath: providedOptions.physicalFilename, + }); + + return this.#eslintrcVerifyWithoutProcessors( + file, + providedConfig, + providedOptions, + ); + } + + /** + * Verifies the text against the rules specified by the second argument. + * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object. + * @param {ConfigData|ConfigArray} config An ESLintConfig instance to configure everything. + * @param {(string|(VerifyOptions&ProcessorOptions))} [filenameOrOptions] The optional filename of the file being checked. + * If this is not set, the filename will default to '' in the rule context. If + * an object, then it has "filename", "allowInlineConfig", and some properties. + * @returns {LintMessage[]} The results as an array of messages or an empty array if no messages. + */ + verify(textOrSourceCode, config, filenameOrOptions) { + debug("Verify"); + + const { configType, cwd } = internalSlotsMap.get(this); + + const options = + typeof filenameOrOptions === "string" + ? { filename: filenameOrOptions } + : filenameOrOptions || {}; + + const configToUse = config ?? {}; + + if (configType !== "eslintrc") { + /* + * Because of how Webpack packages up the files, we can't + * compare directly to `FlatConfigArray` using `instanceof` + * because it's not the same `FlatConfigArray` as in the tests. + * So, we work around it by assuming an array is, in fact, a + * `FlatConfigArray` if it has a `getConfig()` method. + */ + let configArray = configToUse; + + if ( + !Array.isArray(configToUse) || + typeof configToUse.getConfig !== "function" + ) { + configArray = new FlatConfigArray(configToUse, { + basePath: cwd, + }); + configArray.normalizeSync(); + } + + return this._distinguishSuppressedMessages( + this._verifyWithFlatConfigArray( + textOrSourceCode, + configArray, + options, + true, + ), + ); + } + + if (typeof configToUse.extractConfig === "function") { + return this._distinguishSuppressedMessages( + this._verifyWithConfigArray( + textOrSourceCode, + configToUse, + options, + ), + ); + } + + /* + * If we get to here, it means `config` is just an object rather + * than a config array so we can go right into linting. + */ + + /* + * `Linter` doesn't support `overrides` property in configuration. + * So we cannot apply multiple processors. + */ + if (options.preprocess || options.postprocess) { + return this._distinguishSuppressedMessages( + this._verifyWithProcessor( + textOrSourceCode, + configToUse, + options, + ), + ); + } + return this._distinguishSuppressedMessages( + this._verifyWithoutProcessors( + textOrSourceCode, + configToUse, + options, + ), + ); + } + + /** + * Verify with a processor. + * @param {string|SourceCode} textOrSourceCode The source code. + * @param {Config} config The config array. + * @param {VerifyOptions&ProcessorOptions} options The options. + * @param {FlatConfigArray} [configForRecursive] The `ConfigArray` object to apply multiple processors recursively. + * @returns {(LintMessage|SuppressedLintMessage)[]} The found problems. + */ + _verifyWithFlatConfigArrayAndProcessor( + textOrSourceCode, + config, + options, + configForRecursive, + ) { + const slots = internalSlotsMap.get(this); + const filename = options.filename || ""; + const filenameToExpose = normalizeFilename(filename); + const physicalFilename = options.physicalFilename || filenameToExpose; + const text = ensureText(textOrSourceCode); + const file = new VFile(filenameToExpose, text, { + physicalPath: physicalFilename, + }); + + const preprocess = options.preprocess || (rawText => [rawText]); + const postprocess = + options.postprocess || (messagesList => messagesList.flat()); + + const processorService = new ProcessorService(); + const preprocessResult = processorService.preprocessSync(file, { + processor: { + preprocess, + postprocess, + }, + }); + + if (!preprocessResult.ok) { + return preprocessResult.errors; + } + + const filterCodeBlock = + options.filterCodeBlock || + (blockFilename => blockFilename.endsWith(".js")); + const originalExtname = path.extname(filename); + const { files } = preprocessResult; + + const messageLists = files.map(block => { + debug("A code block was found: %o", block.path || "(unnamed)"); + + // Keep the legacy behavior. + if (typeof block === "string") { + return this._verifyWithFlatConfigArrayAndWithoutProcessors( + block, + config, + options, + ); + } + + // Skip this block if filtered. + if (!filterCodeBlock(block.path, block.body)) { + debug("This code block was skipped."); + return []; + } + + // Resolve configuration again if the file content or extension was changed. + if ( + configForRecursive && + (text !== block.rawBody || + path.extname(block.path) !== originalExtname) + ) { + debug( + "Resolving configuration again because the file content or extension was changed.", + ); + return this._verifyWithFlatConfigArray( + block.rawBody, + configForRecursive, + { + ...options, + filename: block.path, + physicalFilename: block.physicalPath, + }, + ); + } + + slots.lastSourceCode = null; + + // Does lint. + return this.#flatVerifyWithoutProcessors(block, config, { + ...options, + filename: block.path, + physicalFilename: block.physicalPath, + }); + }); + + return processorService.postprocessSync(file, messageLists, { + processor: { + preprocess, + postprocess, + }, + }); + } + + /** + * Verify using flat config and without any processors. + * @param {VFile} file The file to lint. + * @param {Config} providedConfig An ESLintConfig instance to configure everything. + * @param {VerifyOptions} [providedOptions] The optional filename of the file being checked. + * @throws {Error} If during rule execution. + * @returns {(LintMessage|SuppressedLintMessage)[]} The results as an array of messages or an empty array if no messages. + */ + #flatVerifyWithoutProcessors(file, providedConfig, providedOptions) { + const slots = internalSlotsMap.get(this); + const config = providedConfig || {}; + const { settings = {}, languageOptions } = config; + const options = normalizeVerifyOptions(providedOptions, config); + + if (!slots.lastSourceCode) { + let t; + + if (options.stats) { + t = startTime(); + } + + const parserService = new ParserService(); + const parseResult = parserService.parseSync(file, config); + + if (options.stats) { + const time = endTime(t); + + storeTime(time, { type: "parse" }, slots); + } + + if (!parseResult.ok) { + return parseResult.errors; + } + + slots.lastSourceCode = parseResult.sourceCode; + } else { + /* + * If the given source code object as the first argument does not have scopeManager, analyze the scope. + * This is for backward compatibility (SourceCode is frozen so it cannot rebind). + * + * We check explicitly for `null` to ensure that this is a JS-flavored language. + * For non-JS languages we don't want to do this. + * + * TODO: Remove this check when we stop exporting the `SourceCode` object. + */ + if (slots.lastSourceCode.scopeManager === null) { + slots.lastSourceCode = new SourceCode({ + text: slots.lastSourceCode.text, + ast: slots.lastSourceCode.ast, + hasBOM: slots.lastSourceCode.hasBOM, + parserServices: slots.lastSourceCode.parserServices, + visitorKeys: slots.lastSourceCode.visitorKeys, + scopeManager: analyzeScope( + slots.lastSourceCode.ast, + languageOptions, + ), + }); + } + } + + const sourceCode = slots.lastSourceCode; + const report = new FileReport({ + ruleMapper: ruleId => config.getRuleDefinition(ruleId), + language: config.language, + sourceCode, + disableFixes: options.disableFixes, + }); + + /* + * Make adjustments based on the language options. For JavaScript, + * this is primarily about adding variables into the global scope + * to account for ecmaVersion and configured globals. + */ + sourceCode.applyLanguageOptions?.(languageOptions); + + const mergedInlineConfig = { + rules: {}, + }; + + /* + * Inline config can be either enabled or disabled. If disabled, it's possible + * to detect the inline config and emit a warning (though this is not required). + * So we first check to see if inline config is allowed at all, and if so, we + * need to check if it's a warning or not. + */ + if (options.allowInlineConfig) { + // if inline config should warn then add the warnings + if (options.warnInlineConfig) { + if (sourceCode.getInlineConfigNodes) { + sourceCode.getInlineConfigNodes().forEach(node => { + const loc = sourceCode.getLoc(node); + const range = sourceCode.getRange(node); + + report.addWarning({ + message: `'${sourceCode.text.slice(range[0], range[1])}' has no effect because you have 'noInlineConfig' setting in ${options.warnInlineConfig}.`, + loc, + }); + }); + } + } else { + if (config.language === jslang) { + for (const comment of sourceCode.getInlineConfigNodes()) { + const { label } = commentParser.parseDirective( + comment.value, + ); + if (label === "eslint-env") { + slots.warningService.emitESLintEnvWarning( + options.filename, + comment.loc.start.line, + ); + } + } + } + + const inlineConfigResult = sourceCode.applyInlineConfig?.(); + + if (inlineConfigResult) { + inlineConfigResult.problems.forEach(problem => { + report.addFatal(problem); + }); + + for (const { + config: inlineConfig, + loc, + } of inlineConfigResult.configs) { + Object.keys(inlineConfig.rules).forEach(ruleId => { + const rule = config.getRuleDefinition(ruleId); + const ruleValue = inlineConfig.rules[ruleId]; + + if (!rule) { + report.addError({ + ruleId, + loc, + }); + return; + } + + if ( + Object.hasOwn(mergedInlineConfig.rules, ruleId) + ) { + report.addError({ + message: `Rule "${ruleId}" is already configured by another configuration comment in the preceding code. This configuration is ignored.`, + loc, + }); + return; + } + + try { + const ruleOptionsInline = asArray(ruleValue); + let ruleOptions = ruleOptionsInline; + + assertIsRuleSeverity(ruleId, ruleOptions[0]); + + /* + * If the rule was already configured, inline rule configuration that + * only has severity should retain options from the config and just override the severity. + * + * Example: + * + * { + * rules: { + * curly: ["error", "multi"] + * } + * } + * + * /* eslint curly: ["warn"] * / + * + * Results in: + * + * curly: ["warn", "multi"] + */ + + let shouldValidateOptions = true; + + if ( + /* + * If inline config for the rule has only severity + */ + ruleOptions.length === 1 && + /* + * And the rule was already configured + */ + config.rules && + Object.hasOwn(config.rules, ruleId) + ) { + /* + * Then use severity from the inline config and options from the provided config + */ + ruleOptions = [ + ruleOptions[0], // severity from the inline config + ...config.rules[ruleId].slice(1), // options from the provided config + ]; + + // if the rule was enabled, the options have already been validated + if (config.rules[ruleId][0] > 0) { + shouldValidateOptions = false; + } + } else { + /** + * Since we know the user provided options, apply defaults on top of them + */ + const slicedOptions = ruleOptions.slice(1); + const mergedOptions = deepMergeArrays( + rule.meta?.defaultOptions, + slicedOptions, + ); + + if (mergedOptions.length) { + ruleOptions = [ + ruleOptions[0], + ...mergedOptions, + ]; + } + } + + if ( + options.reportUnusedInlineConfigs !== "off" + ) { + addProblemIfSameSeverityAndOptions( + config, + loc, + report, + ruleId, + ruleOptions, + ruleOptionsInline, + options.reportUnusedInlineConfigs, + ); + } + + if (shouldValidateOptions) { + config.validateRulesConfig({ + [ruleId]: ruleOptions, + }); + } + + mergedInlineConfig.rules[ruleId] = ruleOptions; + } catch (err) { + /* + * If the rule has invalid `meta.schema`, throw the error because + * this is not an invalid inline configuration but an invalid rule. + */ + if ( + err.code === + "ESLINT_INVALID_RULE_OPTIONS_SCHEMA" + ) { + throw err; + } + + let baseMessage = err.message + .slice( + err.message.startsWith('Key "rules":') + ? err.message.indexOf(":", 12) + 1 + : err.message.indexOf(":") + 1, + ) + .trim(); + + if (err.messageTemplate) { + baseMessage += ` You passed "${ruleValue}".`; + } + + report.addError({ + ruleId, + message: `Inline configuration for rule "${ruleId}" is invalid:\n\t${baseMessage}\n`, + loc, + }); + } + }); + } + } + } + } + + const commentDirectives = + options.allowInlineConfig && !options.warnInlineConfig + ? getDirectiveCommentsForFlatConfig( + sourceCode, + ruleId => config.getRuleDefinition(ruleId), + config.language, + report, + ) + : []; + + const configuredRules = Object.assign( + {}, + config.rules, + mergedInlineConfig.rules, + ); + + sourceCode.finalize?.(); + + try { + runRules( + sourceCode, + configuredRules, + ruleId => config.getRuleDefinition(ruleId), + void 0, + config.language, + languageOptions, + settings, + options.filename, + false, + slots.cwd, + providedOptions.physicalFilename, + options.ruleFilter, + options.stats, + slots, + report, + ); + } catch (err) { + err.message += `\nOccurred while linting ${options.filename}`; + debug("An error occurred while traversing"); + debug("Filename:", options.filename); + if (err.currentNode) { + const { line } = sourceCode.getLoc(err.currentNode).start; + + debug("Line:", line); + err.message += `:${line}`; + } + debug("Parser Options:", languageOptions.parserOptions); + + // debug("Parser Path:", parserName); + debug("Settings:", settings); + + if (err.ruleId) { + err.message += `\nRule: "${err.ruleId}"`; + } + + throw err; + } + + return applyDisableDirectives({ + language: config.language, + sourceCode, + directives: commentDirectives, + disableFixes: options.disableFixes, + problems: report.messages.sort( + (problemA, problemB) => + problemA.line - problemB.line || + problemA.column - problemB.column, + ), + reportUnusedDisableDirectives: + options.reportUnusedDisableDirectives, + ruleFilter: options.ruleFilter, + configuredRules, + }); + } + + /** + * Same as linter.verify, except without support for processors. + * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object. + * @param {Config} providedConfig An ESLintConfig instance to configure everything. + * @param {VerifyOptions} [providedOptions] The optional filename of the file being checked. + * @throws {Error} If during rule execution. + * @returns {(LintMessage|SuppressedLintMessage)[]} The results as an array of messages or an empty array if no messages. + */ + _verifyWithFlatConfigArrayAndWithoutProcessors( + textOrSourceCode, + providedConfig, + providedOptions, + ) { + const slots = internalSlotsMap.get(this); + const filename = normalizeFilename( + providedOptions.filename || "", + ); + let text; + + // evaluate arguments + if (typeof textOrSourceCode === "string") { + slots.lastSourceCode = null; + text = textOrSourceCode; + } else { + slots.lastSourceCode = textOrSourceCode; + text = textOrSourceCode.text; + } + + const file = new VFile(filename, text, { + physicalPath: providedOptions.physicalFilename, + }); + + return this.#flatVerifyWithoutProcessors( + file, + providedConfig, + providedOptions, + ); + } + + /** + * Verify a given code with `ConfigArray`. + * @param {string|SourceCode} textOrSourceCode The source code. + * @param {ConfigArray} configArray The config array. + * @param {VerifyOptions&ProcessorOptions} options The options. + * @returns {(LintMessage|SuppressedLintMessage)[]} The found problems. + */ + _verifyWithConfigArray(textOrSourceCode, configArray, options) { + debug("With ConfigArray: %s", options.filename); + + // Store the config array in order to get plugin envs and rules later. + internalSlotsMap.get(this).lastConfigArray = configArray; + + // Extract the final config for this file. + const config = configArray.extractConfig(options.filename); + const processor = + config.processor && + configArray.pluginProcessors.get(config.processor); + + // Verify. + if (processor) { + debug("Apply the processor: %o", config.processor); + const { preprocess, postprocess, supportsAutofix } = processor; + const disableFixes = options.disableFixes || !supportsAutofix; + + return this._verifyWithProcessor( + textOrSourceCode, + config, + { ...options, disableFixes, postprocess, preprocess }, + configArray, + ); + } + return this._verifyWithoutProcessors(textOrSourceCode, config, options); + } + + /** + * Verify a given code with a flat config. + * @param {string|SourceCode} textOrSourceCode The source code. + * @param {FlatConfigArray} configArray The config array. + * @param {VerifyOptions&ProcessorOptions} options The options. + * @param {boolean} [firstCall=false] Indicates if this is being called directly + * from verify(). (TODO: Remove once eslintrc is removed.) + * @returns {(LintMessage|SuppressedLintMessage)[]} The found problems. + */ + _verifyWithFlatConfigArray( + textOrSourceCode, + configArray, + options, + firstCall = false, + ) { + debug("With flat config: %s", options.filename); + + // we need a filename to match configs against + const filename = options.filename || "__placeholder__.js"; + + // Store the config array in order to get plugin envs and rules later. + internalSlotsMap.get(this).lastConfigArray = configArray; + const config = configArray.getConfig(filename); + + if (!config) { + return [ + { + ruleId: null, + severity: 1, + message: `No matching configuration found for ${filename}.`, + line: 0, + column: 0, + nodeType: null, + }, + ]; + } + + // Verify. + if (config.processor) { + debug("Apply the processor: %o", config.processor); + const { preprocess, postprocess, supportsAutofix } = + config.processor; + const disableFixes = options.disableFixes || !supportsAutofix; + + return this._verifyWithFlatConfigArrayAndProcessor( + textOrSourceCode, + config, + { ...options, filename, disableFixes, postprocess, preprocess }, + configArray, + ); + } + + // check for options-based processing + if (firstCall && (options.preprocess || options.postprocess)) { + return this._verifyWithFlatConfigArrayAndProcessor( + textOrSourceCode, + config, + options, + ); + } + + return this._verifyWithFlatConfigArrayAndWithoutProcessors( + textOrSourceCode, + config, + options, + ); + } + + /** + * Verify with a processor. + * @param {string|SourceCode} textOrSourceCode The source code. + * @param {ConfigData|ExtractedConfig} config The config array. + * @param {VerifyOptions&ProcessorOptions} options The options. + * @param {ConfigArray} [configForRecursive] The `ConfigArray` object to apply multiple processors recursively. + * @returns {(LintMessage|SuppressedLintMessage)[]} The found problems. + */ + _verifyWithProcessor( + textOrSourceCode, + config, + options, + configForRecursive, + ) { + const slots = internalSlotsMap.get(this); + const filename = options.filename || ""; + const filenameToExpose = normalizeFilename(filename); + const physicalFilename = options.physicalFilename || filenameToExpose; + const text = ensureText(textOrSourceCode); + const file = new VFile(filenameToExpose, text, { + physicalPath: physicalFilename, + }); + + const preprocess = options.preprocess || (rawText => [rawText]); + const postprocess = + options.postprocess || (messagesList => messagesList.flat()); + + const processorService = new ProcessorService(); + const preprocessResult = processorService.preprocessSync(file, { + processor: { + preprocess, + postprocess, + }, + }); + + if (!preprocessResult.ok) { + return preprocessResult.errors; + } + + const filterCodeBlock = + options.filterCodeBlock || + (blockFilePath => blockFilePath.endsWith(".js")); + const originalExtname = path.extname(filename); + + const { files } = preprocessResult; + + const messageLists = files.map(block => { + debug("A code block was found: %o", block.path ?? "(unnamed)"); + + // Keep the legacy behavior. + if (typeof block === "string") { + return this._verifyWithoutProcessors(block, config, options); + } + + // Skip this block if filtered. + if (!filterCodeBlock(block.path, block.body)) { + debug("This code block was skipped."); + return []; + } + + // Resolve configuration again if the file content or extension was changed. + if ( + configForRecursive && + (text !== block.rawBody || + path.extname(block.path) !== originalExtname) + ) { + debug( + "Resolving configuration again because the file content or extension was changed.", + ); + return this._verifyWithConfigArray( + block.rawBody, + configForRecursive, + { + ...options, + filename: block.path, + physicalFilename: block.physicalPath, + }, + ); + } + + slots.lastSourceCode = null; + + // Does lint. + return this.#eslintrcVerifyWithoutProcessors(block, config, { + ...options, + filename: block.path, + physicalFilename: block.physicalPath, + }); + }); + + return processorService.postprocessSync(file, messageLists, { + processor: { + preprocess, + postprocess, + }, + }); + } + + /** + * Given a list of reported problems, distinguish problems between normal messages and suppressed messages. + * The normal messages will be returned and the suppressed messages will be stored as lastSuppressedMessages. + * @param {Array} problems A list of reported problems. + * @returns {LintMessage[]} A list of LintMessage. + */ + _distinguishSuppressedMessages(problems) { + const messages = []; + const suppressedMessages = []; + const slots = internalSlotsMap.get(this); + + for (const problem of problems) { + if (problem.suppressions) { + suppressedMessages.push(problem); + } else { + messages.push(problem); + } + } + + slots.lastSuppressedMessages = suppressedMessages; + + return messages; + } + + /** + * Gets the SourceCode object representing the parsed source. + * @returns {SourceCode} The SourceCode object. + */ + getSourceCode() { + return internalSlotsMap.get(this).lastSourceCode; + } + + /** + * Gets the times spent on (parsing, fixing, linting) a file. + * @returns {{ passes: TimePass[]; }} The times. + */ + getTimes() { + return internalSlotsMap.get(this).times ?? { passes: [] }; + } + + /** + * Gets the number of autofix passes that were made in the last run. + * @returns {number} The number of autofix passes. + */ + getFixPassCount() { + return internalSlotsMap.get(this).fixPasses ?? 0; + } + + /** + * Gets the list of SuppressedLintMessage produced in the last running. + * @returns {SuppressedLintMessage[]} The list of SuppressedLintMessage + */ + getSuppressedMessages() { + return internalSlotsMap.get(this).lastSuppressedMessages; + } + + /** + * Defines a new linting rule. + * @param {string} ruleId A unique rule identifier + * @param {Rule} rule A rule object + * @returns {void} + */ + defineRule(ruleId, rule) { + assertEslintrcConfig(this); + internalSlotsMap.get(this).ruleMap.define(ruleId, rule); + } + + /** + * Defines many new linting rules. + * @param {Record} rulesToDefine map from unique rule identifier to rule + * @returns {void} + */ + defineRules(rulesToDefine) { + assertEslintrcConfig(this); + Object.getOwnPropertyNames(rulesToDefine).forEach(ruleId => { + this.defineRule(ruleId, rulesToDefine[ruleId]); + }); + } + + /** + * Gets an object with all loaded rules. + * @returns {Map} All loaded rules + */ + getRules() { + assertEslintrcConfig(this); + const { lastConfigArray, ruleMap } = internalSlotsMap.get(this); + + return new Map( + (function* () { + yield* ruleMap; + + if (lastConfigArray) { + yield* lastConfigArray.pluginRules; + } + })(), + ); + } + + /** + * Define a new parser module + * @param {string} parserId Name of the parser + * @param {Parser} parserModule The parser object + * @returns {void} + */ + defineParser(parserId, parserModule) { + assertEslintrcConfig(this); + internalSlotsMap.get(this).parserMap.set(parserId, parserModule); + } + + /** + * Performs multiple autofix passes over the text until as many fixes as possible + * have been applied. + * @param {string} text The source text to apply fixes to. + * @param {ConfigData|ConfigArray|FlatConfigArray} config The ESLint config object to use. + * @param {VerifyOptions&ProcessorOptions&FixOptions} options The ESLint options object to use. + * @returns {{fixed:boolean,messages:LintMessage[],output:string}} The result of the fix operation as returned from the + * SourceCodeFixer. + */ + verifyAndFix(text, config, options) { + let messages, + fixedResult, + fixed = false, + passNumber = 0, + currentText = text, + secondPreviousText, + previousText; + const debugTextDescription = + (options && options.filename) || `${text.slice(0, 10)}...`; + const shouldFix = + options && typeof options.fix !== "undefined" ? options.fix : true; + const stats = options?.stats; + + const slots = internalSlotsMap.get(this); + + // Remove lint times from the last run. + if (stats) { + delete slots.times; + slots.fixPasses = 0; + } + + /** + * This loop continues until one of the following is true: + * + * 1. No more fixes have been applied. + * 2. Ten passes have been made. + * + * That means anytime a fix is successfully applied, there will be another pass. + * Essentially, guaranteeing a minimum of two passes. + */ + do { + passNumber++; + let tTotal; + + if (stats) { + tTotal = startTime(); + } + + debug( + `Linting code for ${debugTextDescription} (pass ${passNumber})`, + ); + messages = this.verify(currentText, config, options); + + debug( + `Generating fixed text for ${debugTextDescription} (pass ${passNumber})`, + ); + let t; + + if (stats) { + t = startTime(); + } + + fixedResult = SourceCodeFixer.applyFixes( + currentText, + messages, + shouldFix, + ); + + if (stats) { + if (fixedResult.fixed) { + const time = endTime(t); + + storeTime(time, { type: "fix" }, slots); + slots.fixPasses++; + } else { + storeTime(0, { type: "fix" }, slots); + } + } + + /* + * stop if there are any syntax errors. + * 'fixedResult.output' is a empty string. + */ + if (messages.length === 1 && messages[0].fatal) { + break; + } + + // keep track if any fixes were ever applied - important for return value + fixed = fixed || fixedResult.fixed; + + // update to use the fixed output instead of the original text + secondPreviousText = previousText; + previousText = currentText; + currentText = fixedResult.output; + + if (stats) { + tTotal = endTime(tTotal); + const passIndex = slots.times.passes.length - 1; + + slots.times.passes[passIndex].total = tTotal; + } + + // Stop if we've made a circular fix + if ( + passNumber > 1 && + currentText.length === secondPreviousText.length && + currentText === secondPreviousText + ) { + debug( + `Circular fixes detected after pass ${passNumber}. Exiting fix loop.`, + ); + slots.warningService.emitCircularFixesWarning( + options?.filename ?? "text", + ); + break; + } + } while (fixedResult.fixed && passNumber < MAX_AUTOFIX_PASSES); + + /* + * If the last result had fixes, we need to lint again to be sure we have + * the most up-to-date information. + */ + if (fixedResult.fixed) { + let tTotal; + + if (stats) { + tTotal = startTime(); + } + + fixedResult.messages = this.verify(currentText, config, options); + + if (stats) { + storeTime(0, { type: "fix" }, slots); + slots.times.passes.at(-1).total = endTime(tTotal); + } + } + + // ensure the last result properly reflects if fixes were done + fixedResult.fixed = fixed; + fixedResult.output = currentText; + + return fixedResult; + } +} + +module.exports = { + Linter, + + /** + * Get the internal slots of a given Linter instance for tests. + * @param {Linter} instance The Linter instance to get. + * @returns {LinterInternalSlots} The internal slots. + */ + getLinterInternalSlots(instance) { + return internalSlotsMap.get(instance); + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/linter/rule-fixer.js b/tools/ui/node_modules/eslint/lib/linter/rule-fixer.js new file mode 100644 index 0000000000000000000000000000000000000000..e73dac6721d41bf2eec1fe9f47a01e316df3895a --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/linter/rule-fixer.js @@ -0,0 +1,169 @@ +/** + * @fileoverview An object that creates fix commands for rules. + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** + * @import { SourceRange } from "@eslint/core"; + */ + +/* eslint class-methods-use-this: off -- Methods desired on instance */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +// none! + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Creates a fix command that inserts text at the specified index in the source text. + * @param {number} index The 0-based index at which to insert the new text. + * @param {string} text The text to insert. + * @returns {Object} The fix command. + * @private + */ +function insertTextAt(index, text) { + return { + range: [index, index], + text, + }; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Creates code fixing commands for rules. + */ +class RuleFixer { + /** + * The source code object representing the text to be fixed. + * @type {SourceCode} + */ + #sourceCode; + + /** + * Creates a new instance. + * @param {Object} options The options for the fixer. + * @param {SourceCode} options.sourceCode The source code object representing the text to be fixed. + */ + constructor({ sourceCode }) { + this.#sourceCode = sourceCode; + } + + /** + * Creates a fix command that inserts text after the given node or token. + * The fix is not applied until applyFixes() is called. + * @param {ASTNode|Token} nodeOrToken The node or token to insert after. + * @param {string} text The text to insert. + * @returns {Object} The fix command. + */ + insertTextAfter(nodeOrToken, text) { + const range = this.#sourceCode.getRange(nodeOrToken); + + return this.insertTextAfterRange(range, text); + } + + /** + * Creates a fix command that inserts text after the specified range in the source text. + * The fix is not applied until applyFixes() is called. + * @param {SourceRange} range The range to replace, first item is start of range, second + * is end of range. + * @param {string} text The text to insert. + * @returns {Object} The fix command. + */ + insertTextAfterRange(range, text) { + return insertTextAt(range[1], text); + } + + /** + * Creates a fix command that inserts text before the given node or token. + * The fix is not applied until applyFixes() is called. + * @param {ASTNode|Token} nodeOrToken The node or token to insert before. + * @param {string} text The text to insert. + * @returns {Object} The fix command. + */ + insertTextBefore(nodeOrToken, text) { + const range = this.#sourceCode.getRange(nodeOrToken); + + return this.insertTextBeforeRange(range, text); + } + + /** + * Creates a fix command that inserts text before the specified range in the source text. + * The fix is not applied until applyFixes() is called. + * @param {SourceRange} range The range to replace, first item is start of range, second + * is end of range. + * @param {string} text The text to insert. + * @returns {Object} The fix command. + */ + insertTextBeforeRange(range, text) { + return insertTextAt(range[0], text); + } + + /** + * Creates a fix command that replaces text at the node or token. + * The fix is not applied until applyFixes() is called. + * @param {ASTNode|Token} nodeOrToken The node or token to remove. + * @param {string} text The text to insert. + * @returns {Object} The fix command. + */ + replaceText(nodeOrToken, text) { + const range = this.#sourceCode.getRange(nodeOrToken); + + return this.replaceTextRange(range, text); + } + + /** + * Creates a fix command that replaces text at the specified range in the source text. + * The fix is not applied until applyFixes() is called. + * @param {SourceRange} range The range to replace, first item is start of range, second + * is end of range. + * @param {string} text The text to insert. + * @returns {Object} The fix command. + */ + replaceTextRange(range, text) { + return { + range, + text, + }; + } + + /** + * Creates a fix command that removes the node or token from the source. + * The fix is not applied until applyFixes() is called. + * @param {ASTNode|Token} nodeOrToken The node or token to remove. + * @returns {Object} The fix command. + */ + remove(nodeOrToken) { + const range = this.#sourceCode.getRange(nodeOrToken); + + return this.removeRange(range); + } + + /** + * Creates a fix command that removes the specified range of text from the source. + * The fix is not applied until applyFixes() is called. + * @param {SourceRange} range The range to remove, first item is start of range, second + * is end of range. + * @returns {Object} The fix command. + */ + removeRange(range) { + return { + range, + text: "", + }; + } +} + +module.exports = { RuleFixer }; diff --git a/tools/ui/node_modules/eslint/lib/linter/rules.js b/tools/ui/node_modules/eslint/lib/linter/rules.js new file mode 100644 index 0000000000000000000000000000000000000000..ec017eefb1a59bcd2217b6177fc1ba4c0cbec2a0 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/linter/rules.js @@ -0,0 +1,71 @@ +/** + * @fileoverview Defines a storage for rules. + * @author Nicholas C. Zakas + * @author aladdin-add + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const builtInRules = require("../rules"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** @typedef {import("../types").Rule.RuleModule} Rule */ + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * A storage for rules. + */ +class Rules { + constructor() { + this._rules = Object.create(null); + } + + /** + * Registers a rule module for rule id in storage. + * @param {string} ruleId Rule id (file name). + * @param {Rule} rule Rule object. + * @returns {void} + */ + define(ruleId, rule) { + this._rules[ruleId] = rule; + } + + /** + * Access rule handler by id (file name). + * @param {string} ruleId Rule id (file name). + * @returns {Rule} Rule object. + */ + get(ruleId) { + if (typeof this._rules[ruleId] === "string") { + this.define(ruleId, require(this._rules[ruleId])); + } + if (this._rules[ruleId]) { + return this._rules[ruleId]; + } + if (builtInRules.has(ruleId)) { + return builtInRules.get(ruleId); + } + + return null; + } + + *[Symbol.iterator]() { + yield* builtInRules; + + for (const ruleId of Object.keys(this._rules)) { + yield [ruleId, this.get(ruleId)]; + } + } +} + +module.exports = Rules; diff --git a/tools/ui/node_modules/eslint/lib/linter/source-code-fixer.js b/tools/ui/node_modules/eslint/lib/linter/source-code-fixer.js new file mode 100644 index 0000000000000000000000000000000000000000..2cea2c60403321b28e3c3942749ad6dd848c37ba --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/linter/source-code-fixer.js @@ -0,0 +1,154 @@ +/** + * @fileoverview An object that caches and applies source code fixes. + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const debug = require("debug")("eslint:source-code-fixer"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const BOM = "\uFEFF"; + +/** + * Compares items in a messages array by range. + * @param {Message} a The first message. + * @param {Message} b The second message. + * @returns {number} -1 if a comes before b, 1 if a comes after b, 0 if equal. + * @private + */ +function compareMessagesByFixRange(a, b) { + return a.fix.range[0] - b.fix.range[0] || a.fix.range[1] - b.fix.range[1]; +} + +/** + * Compares items in a messages array by line and column. + * @param {Message} a The first message. + * @param {Message} b The second message. + * @returns {number} -1 if a comes before b, 1 if a comes after b, 0 if equal. + * @private + */ +function compareMessagesByLocation(a, b) { + return a.line - b.line || a.column - b.column; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Utility for apply fixes to source code. + * @constructor + */ +function SourceCodeFixer() { + Object.freeze(this); +} + +/** + * Applies the fixes specified by the messages to the given text. Tries to be + * smart about the fixes and won't apply fixes over the same area in the text. + * @param {string} sourceText The text to apply the changes to. + * @param {Message[]} messages The array of messages reported by ESLint. + * @param {boolean|Function} [shouldFix=true] Determines whether each message should be fixed + * @returns {Object} An object containing the fixed text and any unfixed messages. + */ +SourceCodeFixer.applyFixes = function (sourceText, messages, shouldFix) { + debug("Applying fixes"); + + if (shouldFix === false) { + debug("shouldFix parameter was false, not attempting fixes"); + return { + fixed: false, + messages, + output: sourceText, + }; + } + + // clone the array + const remainingMessages = [], + fixes = [], + bom = sourceText.startsWith(BOM) ? BOM : "", + text = bom ? sourceText.slice(1) : sourceText; + let lastPos = Number.NEGATIVE_INFINITY, + output = bom; + + /** + * Try to use the 'fix' from a problem. + * @param {Message} problem The message object to apply fixes from + * @returns {boolean} Whether fix was successfully applied + */ + function attemptFix(problem) { + const fix = problem.fix; + const start = fix.range[0]; + const end = fix.range[1]; + + // Remain it as a problem if it's overlapped or it's a negative range + if (lastPos >= start || start > end) { + remainingMessages.push(problem); + return false; + } + + // Remove BOM. + if ( + (start < 0 && end >= 0) || + (start === 0 && fix.text.startsWith(BOM)) + ) { + output = ""; + } + + // Make output to this fix. + output += text.slice(Math.max(0, lastPos), Math.max(0, start)); + output += fix.text; + lastPos = end; + return true; + } + + messages.forEach(problem => { + if (Object.hasOwn(problem, "fix") && problem.fix) { + fixes.push(problem); + } else { + remainingMessages.push(problem); + } + }); + + if (fixes.length) { + debug("Found fixes to apply"); + let fixesWereApplied = false; + + for (const problem of fixes.sort(compareMessagesByFixRange)) { + if (typeof shouldFix !== "function" || shouldFix(problem)) { + attemptFix(problem); + + /* + * The only time attemptFix will fail is if a previous fix was + * applied which conflicts with it. So we can mark this as true. + */ + fixesWereApplied = true; + } else { + remainingMessages.push(problem); + } + } + output += text.slice(Math.max(0, lastPos)); + + return { + fixed: fixesWereApplied, + messages: remainingMessages.sort(compareMessagesByLocation), + output, + }; + } + + debug("No fixes to apply"); + return { + fixed: false, + messages, + output: bom + text, + }; +}; + +module.exports = SourceCodeFixer; diff --git a/tools/ui/node_modules/eslint/lib/linter/source-code-traverser.js b/tools/ui/node_modules/eslint/lib/linter/source-code-traverser.js new file mode 100644 index 0000000000000000000000000000000000000000..0a6235e0491ad99fe8e26981fc906cd663762dbe --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/linter/source-code-traverser.js @@ -0,0 +1,333 @@ +/** + * @fileoverview Traverser for SourceCode objects. + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { parse, matches } = require("./esquery"); +const vk = require("eslint-visitor-keys"); + +//----------------------------------------------------------------------------- +// Typedefs +//----------------------------------------------------------------------------- + +/** + * @import { Language, SourceCode } from "@eslint/core"; + * @import { ESQueryOptions } from "esquery"; + * @import { ESQueryParsedSelector } from "./esquery.js"; + * @import { SourceCodeVisitor } from "./source-code-visitor.js"; + */ + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +const STEP_KIND_VISIT = 1; +const STEP_KIND_CALL = 2; + +/** + * Compares two ESQuery selectors by specificity. + * @param {ESQueryParsedSelector} a The first selector to compare. + * @param {ESQueryParsedSelector} b The second selector to compare. + * @returns {number} A negative number if `a` is less specific than `b` or they are equally specific and `a` <= `b` alphabetically, a positive number if `a` is more specific than `b`. + */ +function compareSpecificity(a, b) { + return a.compare(b); +} + +/** + * Helper to wrap ESQuery operations. + */ +class ESQueryHelper { + /** + * Creates a new instance. + * @param {SourceCodeVisitor} visitor The visitor containing the functions to call. + * @param {ESQueryOptions} esqueryOptions `esquery` options for traversing custom nodes. + */ + constructor(visitor, esqueryOptions) { + /** + * The visitor to use during traversal. + * @type {SourceCodeVisitor} + */ + this.visitor = visitor; + + /** + * The options for `esquery` to use during matching. + * @type {ESQueryOptions} + */ + this.esqueryOptions = esqueryOptions; + + /** + * A map of node type to selectors targeting that node type on the + * enter phase of traversal. + * @type {Map} + */ + this.enterSelectorsByNodeType = new Map(); + + /** + * A map of node type to selectors targeting that node type on the + * exit phase of traversal. + * @type {Map} + */ + this.exitSelectorsByNodeType = new Map(); + + /** + * An array of selectors that match any node type on the + * enter phase of traversal. + * @type {ESQueryParsedSelector[]} + */ + this.anyTypeEnterSelectors = []; + + /** + * An array of selectors that match any node type on the + * exit phase of traversal. + * @type {ESQueryParsedSelector[]} + */ + this.anyTypeExitSelectors = []; + + visitor.forEachName(rawSelector => { + const selector = parse(rawSelector); + + /* + * If this selector has identified specific node types, + * add it to the map for these node types for faster lookup. + */ + if (selector.nodeTypes) { + const typeMap = selector.isExit + ? this.exitSelectorsByNodeType + : this.enterSelectorsByNodeType; + + selector.nodeTypes.forEach(nodeType => { + if (!typeMap.has(nodeType)) { + typeMap.set(nodeType, []); + } + typeMap.get(nodeType).push(selector); + }); + return; + } + + /* + * Remaining selectors are added to the "any type" selectors + * list for the appropriate phase of traversal. This ensures + * that all selectors will still be applied even if no + * specific node type is matched. + */ + const selectors = selector.isExit + ? this.anyTypeExitSelectors + : this.anyTypeEnterSelectors; + + selectors.push(selector); + }); + + // sort all selectors by specificity for prioritizing call order + this.anyTypeEnterSelectors.sort(compareSpecificity); + this.anyTypeExitSelectors.sort(compareSpecificity); + this.enterSelectorsByNodeType.forEach(selectorList => + selectorList.sort(compareSpecificity), + ); + this.exitSelectorsByNodeType.forEach(selectorList => + selectorList.sort(compareSpecificity), + ); + } + + /** + * Checks if a node matches a given selector. + * @param {ASTNode} node The node to check + * @param {ASTNode[]} ancestry The ancestry of the node being checked. + * @param {ESQueryParsedSelector} selector An AST selector descriptor + * @returns {boolean} `true` if the selector matches the node, `false` otherwise + */ + matches(node, ancestry, selector) { + return matches(node, selector.root, ancestry, this.esqueryOptions); + } + + /** + * Calculates all appropriate selectors to a node, in specificity order + * @param {ASTNode} node The node to check + * @param {ASTNode[]} ancestry The ancestry of the node being checked. + * @param {boolean} isExit `false` if the node is currently being entered, `true` if it's currently being exited + * @returns {string[]} An array of selectors that match the node. + */ + calculateSelectors(node, ancestry, isExit) { + const nodeTypeKey = this.esqueryOptions?.nodeTypeKey || "type"; + const selectors = []; + + /* + * Get the selectors that may match this node. First, check + * to see if the node type has specific selectors, + * then gather the "any type" selectors. + */ + const selectorsByNodeType = + (isExit + ? this.exitSelectorsByNodeType + : this.enterSelectorsByNodeType + ).get(node[nodeTypeKey]) || []; + const anyTypeSelectors = isExit + ? this.anyTypeExitSelectors + : this.anyTypeEnterSelectors; + + /* + * selectorsByNodeType and anyTypeSelectors were already sorted by specificity in the constructor. + * Iterate through each of them, applying selectors in the right order. + */ + let selectorsByNodeTypeIndex = 0; + let anyTypeSelectorsIndex = 0; + + while ( + selectorsByNodeTypeIndex < selectorsByNodeType.length || + anyTypeSelectorsIndex < anyTypeSelectors.length + ) { + /* + * If we've already exhausted the selectors for this node type, + * or if the next any type selector is more specific than the + * next selector for this node type, apply the any type selector. + */ + const hasMoreNodeTypeSelectors = + selectorsByNodeTypeIndex < selectorsByNodeType.length; + const hasMoreAnyTypeSelectors = + anyTypeSelectorsIndex < anyTypeSelectors.length; + const anyTypeSelector = anyTypeSelectors[anyTypeSelectorsIndex]; + const nodeTypeSelector = + selectorsByNodeType[selectorsByNodeTypeIndex]; + + // Only compare specificity if both selectors exist + const isAnyTypeSelectorLessSpecific = + hasMoreAnyTypeSelectors && + hasMoreNodeTypeSelectors && + anyTypeSelector.compare(nodeTypeSelector) < 0; + + if (!hasMoreNodeTypeSelectors || isAnyTypeSelectorLessSpecific) { + anyTypeSelectorsIndex++; + + if (this.matches(node, ancestry, anyTypeSelector)) { + selectors.push(anyTypeSelector.source); + } + } else { + selectorsByNodeTypeIndex++; + + if (this.matches(node, ancestry, nodeTypeSelector)) { + selectors.push(nodeTypeSelector.source); + } + } + } + + return selectors; + } +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Traverses source code and ensures that visitor methods are called when + * entering and leaving each node. + */ +class SourceCodeTraverser { + /** + * The language of the source code being traversed. + * @type {Language} + */ + #language; + + /** + * Map of languages to instances of this class. + * @type {WeakMap} + */ + static instances = new WeakMap(); + + /** + * Creates a new instance. + * @param {Language} language The language of the source code being traversed. + */ + constructor(language) { + this.#language = language; + } + + static getInstance(language) { + if (!this.instances.has(language)) { + this.instances.set(language, new this(language)); + } + + return this.instances.get(language); + } + + /** + * Traverses the given source code synchronously. + * @param {SourceCode} sourceCode The source code to traverse. + * @param {SourceCodeVisitor} visitor The emitter to use for events. + * @param {Object} options Options for traversal. + * @param {ReturnType} options.steps The steps to take during traversal. + * @returns {void} + * @throws {Error} If an error occurs during traversal. + */ + traverseSync(sourceCode, visitor, { steps } = {}) { + const esquery = new ESQueryHelper(visitor, { + visitorKeys: sourceCode.visitorKeys ?? this.#language.visitorKeys, + fallback: vk.getKeys, + matchClass: this.#language.matchesSelectorClass ?? (() => false), + nodeTypeKey: this.#language.nodeTypeKey, + }); + + const currentAncestry = []; + + for (const step of steps ?? sourceCode.traverse()) { + switch (step.kind) { + case STEP_KIND_VISIT: { + try { + if (step.phase === 1) { + esquery + .calculateSelectors( + step.target, + currentAncestry, + false, + ) + .forEach(selector => { + visitor.callSync( + selector, + ...(step.args ?? [step.target]), + ); + }); + currentAncestry.unshift(step.target); + } else { + currentAncestry.shift(); + esquery + .calculateSelectors( + step.target, + currentAncestry, + true, + ) + .forEach(selector => { + visitor.callSync( + selector, + ...(step.args ?? [step.target]), + ); + }); + } + } catch (err) { + err.currentNode = step.target; + throw err; + } + break; + } + + case STEP_KIND_CALL: { + visitor.callSync(step.target, ...step.args); + break; + } + + default: + throw new Error( + `Invalid traversal step found: "${step.kind}".`, + ); + } + } + } +} + +module.exports = { SourceCodeTraverser }; diff --git a/tools/ui/node_modules/eslint/lib/linter/source-code-visitor.js b/tools/ui/node_modules/eslint/lib/linter/source-code-visitor.js new file mode 100644 index 0000000000000000000000000000000000000000..0f5af565833876c8d1641a2afc69c8bd6cf20f4e --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/linter/source-code-visitor.js @@ -0,0 +1,81 @@ +/** + * @fileoverview SourceCodeVisitor class + * @author Nicholas C. Zakas + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +const emptyArray = Object.freeze([]); + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * A structure to hold a list of functions to call for a given name. + * This is used to allow multiple rules to register functions for a given name + * without having to know about each other. + */ +class SourceCodeVisitor { + /** + * The functions to call for a given name. + * @type {Map} + */ + #functions = new Map(); + + /** + * Adds a function to the list of functions to call for a given name. + * @param {string} name The name of the function to call. + * @param {Function} func The function to call. + * @returns {void} + */ + add(name, func) { + if (this.#functions.has(name)) { + this.#functions.get(name).push(func); + } else { + this.#functions.set(name, [func]); + } + } + + /** + * Gets the list of functions to call for a given name. + * @param {string} name The name of the function to call. + * @returns {Function[]} The list of functions to call. + */ + get(name) { + if (this.#functions.has(name)) { + return this.#functions.get(name); + } + + return emptyArray; + } + + /** + * Iterates over all names and calls the callback with the name. + * @param {(name:string) => void} callback The callback to call for each name. + * @returns {void} + */ + forEachName(callback) { + this.#functions.forEach((funcs, name) => { + callback(name); + }); + } + + /** + * Calls the functions for a given name with the given arguments. + * @param {string} name The name of the function to call. + * @param {any[]} args The arguments to pass to the function. + * @returns {void} + */ + callSync(name, ...args) { + if (this.#functions.has(name)) { + this.#functions.get(name).forEach(func => func(...args)); + } + } +} + +module.exports = { SourceCodeVisitor }; diff --git a/tools/ui/node_modules/eslint/lib/linter/timing.js b/tools/ui/node_modules/eslint/lib/linter/timing.js new file mode 100644 index 0000000000000000000000000000000000000000..1791f8fdf74b1fd351e80852820c134c211e824b --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/linter/timing.js @@ -0,0 +1,209 @@ +/** + * @fileoverview Tracks performance of individual rules. + * @author Brandon Mills + */ + +"use strict"; + +const { startTime, endTime } = require("../shared/stats"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/* c8 ignore next */ +/** + * Align the string to left + * @param {string} str string to evaluate + * @param {number} len length of the string + * @param {string} ch delimiter character + * @returns {string} modified string + * @private + */ +function alignLeft(str, len, ch) { + return str + new Array(len - str.length + 1).join(ch || " "); +} + +/* c8 ignore next */ +/** + * Align the string to right + * @param {string} str string to evaluate + * @param {number} len length of the string + * @param {string} ch delimiter character + * @returns {string} modified string + * @private + */ +function alignRight(str, len, ch) { + return new Array(len - str.length + 1).join(ch || " ") + str; +} + +//------------------------------------------------------------------------------ +// Module definition +//------------------------------------------------------------------------------ + +const enabled = !!process.env.TIMING; + +const HEADERS = ["Rule", "Time (ms)", "Relative"]; +const ALIGN = [alignLeft, alignRight, alignRight]; + +/** + * Decide how many rules to show in the output list. + * @returns {number} the number of rules to show + */ +function getListSize() { + const MINIMUM_SIZE = 10; + + if (typeof process.env.TIMING !== "string") { + return MINIMUM_SIZE; + } + + if (process.env.TIMING.toLowerCase() === "all") { + return Number.POSITIVE_INFINITY; + } + + const TIMING_ENV_VAR_AS_INTEGER = Number.parseInt(process.env.TIMING, 10); + + return TIMING_ENV_VAR_AS_INTEGER > 10 + ? TIMING_ENV_VAR_AS_INTEGER + : MINIMUM_SIZE; +} + +/* c8 ignore next */ +/** + * display the data + * @param {Object} data Data object to be displayed + * @returns {void} prints modified string with console.log + * @private + */ +function display(data) { + let total = 0; + const rows = Object.keys(data) + .map(key => { + const time = data[key]; + + total += time; + return [key, time]; + }) + .sort((a, b) => b[1] - a[1]) + .slice(0, getListSize()); + + rows.forEach(row => { + row.push(`${((row[1] * 100) / total).toFixed(1)}%`); + row[1] = row[1].toFixed(3); + }); + + rows.unshift(HEADERS); + + const widths = []; + + rows.forEach(row => { + const len = row.length; + + for (let i = 0; i < len; i++) { + const n = row[i].length; + + if (!widths[i] || n > widths[i]) { + widths[i] = n; + } + } + }); + + const table = rows.map(row => + row.map((cell, index) => ALIGN[index](cell, widths[index])).join(" | "), + ); + + table.splice( + 1, + 0, + widths + .map((width, index) => { + const extraAlignment = + index !== 0 && index !== widths.length - 1 ? 2 : 1; + + return ALIGN[index](":", width + extraAlignment, "-"); + }) + .join("|"), + ); + + console.log(table.join("\n")); // eslint-disable-line no-console -- Debugging function +} + +/* c8 ignore next */ +module.exports = (function () { + const data = Object.create(null); + let displayEnabled = true; + + /** + * Time the run + * @param {any} key key from the data object + * @param {Function} fn function to be called + * @param {boolean} stats if 'stats' is true, return the result and the time difference + * @returns {Function} function to be executed + * @private + */ + function time(key, fn, stats) { + return function (...args) { + const t = startTime(); + const result = fn(...args); + const tdiff = endTime(t); + + if (enabled) { + if (typeof data[key] === "undefined") { + data[key] = 0; + } + + data[key] += tdiff; + } + + return stats ? { result, tdiff } : result; + }; + } + + /** + * Returns a shallow copy of the collected timings data. + * @returns {Record} mapping of ruleId to total time in ms + */ + function getData() { + return { ...data }; + } + + /** + * Merges rule timing totals collected elsewhere into this process' totals. + * @param {Record} dataToMerge mapping of ruleId to total time in ms + * @returns {void} + */ + function mergeData(dataToMerge) { + for (const [key, value] of Object.entries(dataToMerge)) { + if (typeof data[key] === "undefined") { + data[key] = 0; + } + data[key] += value; + } + } + + /** + * Disables printing of timing data on process exit. + * Intended for worker threads or non-main contexts. + * @returns {void} + */ + function disableDisplay() { + displayEnabled = false; + } + + if (enabled) { + process.on("exit", () => { + if (displayEnabled && Object.keys(data).length > 0) { + display(data); + } + }); + } + + return { + time, + enabled, + getListSize, + getData, + mergeData, + disableDisplay, + }; +})(); diff --git a/tools/ui/node_modules/eslint/lib/linter/vfile.js b/tools/ui/node_modules/eslint/lib/linter/vfile.js new file mode 100644 index 0000000000000000000000000000000000000000..4bdbf99128609b806098fe781983c3c918887146 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/linter/vfile.js @@ -0,0 +1,115 @@ +/** + * @fileoverview Virtual file + * @author Nicholas C. Zakas + */ + +"use strict"; + +//----------------------------------------------------------------------------- +// Type Definitions +//----------------------------------------------------------------------------- + +/** @typedef {import("@eslint/core").File} File */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Determines if a given value has a byte order mark (BOM). + * @param {string|Uint8Array} value The value to check. + * @returns {boolean} `true` if the value has a BOM, `false` otherwise. + */ +function hasUnicodeBOM(value) { + return typeof value === "string" + ? value.charCodeAt(0) === 0xfeff + : value[0] === 0xef && value[1] === 0xbb && value[2] === 0xbf; +} + +/** + * Strips Unicode BOM from the given value. + * @param {string|Uint8Array} value The value to remove the BOM from. + * @returns {string|Uint8Array} The stripped value. + */ +function stripUnicodeBOM(value) { + if (!hasUnicodeBOM(value)) { + return value; + } + + if (typeof value === "string") { + /* + * Check Unicode BOM. + * In JavaScript, string data is stored as UTF-16, so BOM is 0xFEFF. + * http://www.ecma-international.org/ecma-262/6.0/#sec-unicode-format-control-characters + */ + return value.slice(1); + } + + /* + * In a Uint8Array, the BOM is represented by three bytes: 0xEF, 0xBB, and 0xBF, + * so we can just remove the first three bytes. + */ + return value.slice(3); +} + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * Represents a virtual file inside of ESLint. + * @implements {File} + */ +class VFile { + /** + * The file path including any processor-created virtual path. + * @type {string} + * @readonly + */ + path; + + /** + * The file path on disk. + * @type {string} + * @readonly + */ + physicalPath; + + /** + * The file contents. + * @type {string|Uint8Array} + * @readonly + */ + body; + + /** + * The raw body of the file, including a BOM if present. + * @type {string|Uint8Array} + * @readonly + */ + rawBody; + + /** + * Indicates whether the file has a byte order mark (BOM). + * @type {boolean} + * @readonly + */ + bom; + + /** + * Creates a new instance. + * @param {string} path The file path. + * @param {string|Uint8Array} body The file contents. + * @param {Object} [options] Additional options. + * @param {string} [options.physicalPath] The file path on disk. + */ + constructor(path, body, { physicalPath } = {}) { + this.path = path; + this.physicalPath = physicalPath ?? path; + this.bom = hasUnicodeBOM(body); + this.body = stripUnicodeBOM(body); + this.rawBody = body; + } +} + +module.exports = { VFile }; diff --git a/tools/ui/node_modules/eslint/lib/options.js b/tools/ui/node_modules/eslint/lib/options.js new file mode 100644 index 0000000000000000000000000000000000000000..71365eb16388724da588be01ffd2db793b8ce275 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/options.js @@ -0,0 +1,536 @@ +/** + * @fileoverview Options configuration for optionator. + * @author George Zahariev + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const optionator = require("optionator"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** + * The options object parsed by Optionator. + * @typedef {Object} ParsedCLIOptions + * @property {boolean} cache Only check changed files + * @property {string} cacheFile Path to the cache file. Deprecated: use --cache-location + * @property {string} [cacheLocation] Path to the cache file or directory + * @property {"metadata" | "content"} cacheStrategy Strategy to use for detecting changed files in the cache + * @property {boolean} [color] Force enabling/disabling of color + * @property {number | "auto" | "off"} [concurrency] Number of linting threads, "auto" to choose automatically, "off" for no multithreading + * @property {string} [config] Use this configuration, overriding .eslintrc.* config options if present + * @property {boolean} debug Output debugging information + * @property {string[]} [env] Specify environments + * @property {boolean} envInfo Output execution environment information + * @property {boolean} errorOnUnmatchedPattern Prevent errors when pattern is unmatched + * @property {boolean} eslintrc Disable use of configuration from .eslintrc.* + * @property {string[]} [ext] Specify JavaScript file extensions + * @property {string[]} [flag] Feature flags + * @property {boolean} fix Automatically fix problems + * @property {boolean} fixDryRun Automatically fix problems without saving the changes to the file system + * @property {("directive" | "problem" | "suggestion" | "layout")[]} [fixType] Specify the types of fixes to apply (directive, problem, suggestion, layout) + * @property {string} format Use a specific output format + * @property {string[]} [global] Define global variables + * @property {boolean} [help] Show help + * @property {boolean} ignore Disable use of ignore files and patterns + * @property {string} [ignorePath] Specify path of ignore file + * @property {string[]} [ignorePattern] Patterns of files to ignore. In eslintrc mode, these are in addition to `.eslintignore` + * @property {boolean} init Run config initialization wizard + * @property {boolean} inlineConfig Prevent comments from changing config or rules + * @property {number} maxWarnings Number of warnings to trigger nonzero exit code + * @property {string} [outputFile] Specify file to write report to + * @property {string} [parser] Specify the parser to be used + * @property {Object} [parserOptions] Specify parser options + * @property {boolean} [passOnNoPatterns=false] When set to true, missing patterns cause + * the linting operation to short circuit and not report any failures. + * @property {boolean} [passOnUnprunedSuppressions] Ignore unused suppressions + * @property {string[]} [plugin] Specify plugins + * @property {string} [printConfig] Print the configuration for the given file + * @property {boolean} [pruneSuppressions] Prune unused suppressions + * @property {boolean} quiet Report errors only + * @property {boolean | undefined} reportUnusedDisableDirectives Adds reported errors for unused eslint-disable and eslint-enable directives + * @property {string | undefined} reportUnusedDisableDirectivesSeverity A severity string indicating if and how unused disable and enable directives should be tracked and reported. + * @property {string} [resolvePluginsRelativeTo] A folder where plugins should be resolved from, CWD by default + * @property {Object} [rule] Specify rules + * @property {string[]} [rulesdir] Load additional rules from this directory. Deprecated: Use rules from plugins + * @property {boolean} [stats] Report additional statistics + * @property {boolean} stdin Lint code provided on + * @property {string} [stdinFilename] Specify filename to process STDIN as + * @property {boolean} [suppressAll] Suppress all error violations + * @property {string} [suppressionsLocation] Path to the suppressions file or directory + * @property {string[]} [suppressRule] Suppress specific rules + * @property {boolean} [version] Output the version number + * @property {boolean} warnIgnored Show warnings when the file list includes ignored files + * @property {string[]} _ Positional filenames or patterns + */ + +//------------------------------------------------------------------------------ +// Initialization and Public Interface +//------------------------------------------------------------------------------ + +// exports "parse(args)", "generateHelp()", and "generateHelpForOption(optionName)" + +/** + * Creates the CLI options for ESLint. + * @param {boolean} usingFlatConfig Indicates if flat config is being used. + * @returns {Object} The optionator instance. + */ +module.exports = function (usingFlatConfig) { + let lookupFlag; + + if (usingFlatConfig) { + lookupFlag = { + option: "config-lookup", + type: "Boolean", + default: "true", + description: "Disable look up for eslint.config.js", + }; + } else { + lookupFlag = { + option: "eslintrc", + type: "Boolean", + default: "true", + description: "Disable use of configuration from .eslintrc.*", + }; + } + + let envFlag; + + if (!usingFlatConfig) { + envFlag = { + option: "env", + type: "[String]", + description: "Specify environments", + }; + } + + let inspectConfigFlag; + + if (usingFlatConfig) { + inspectConfigFlag = { + option: "inspect-config", + type: "Boolean", + description: + "Open the config inspector with the current configuration", + }; + } + + let extFlag; + + if (!usingFlatConfig) { + extFlag = { + option: "ext", + type: "[String]", + description: "Specify JavaScript file extensions", + }; + } else { + extFlag = { + option: "ext", + type: "[String]", + description: "Specify additional file extensions to lint", + }; + } + + let resolvePluginsFlag; + + if (!usingFlatConfig) { + resolvePluginsFlag = { + option: "resolve-plugins-relative-to", + type: "path::String", + description: + "A folder where plugins should be resolved from, CWD by default", + }; + } + + let rulesDirFlag; + + if (!usingFlatConfig) { + rulesDirFlag = { + option: "rulesdir", + type: "[path::String]", + description: + "Load additional rules from this directory. Deprecated: Use rules from plugins", + }; + } + + let ignorePathFlag; + + if (!usingFlatConfig) { + ignorePathFlag = { + option: "ignore-path", + type: "path::String", + description: "Specify path of ignore file", + }; + } + + let statsFlag; + + if (usingFlatConfig) { + statsFlag = { + option: "stats", + type: "Boolean", + default: "false", + description: "Add statistics to the lint report", + }; + } + + let warnIgnoredFlag; + + if (usingFlatConfig) { + warnIgnoredFlag = { + option: "warn-ignored", + type: "Boolean", + default: "true", + description: + "Suppress warnings when the file list includes ignored files", + }; + } + + let flagFlag; + + if (usingFlatConfig) { + flagFlag = { + option: "flag", + type: "[String]", + description: "Enable a feature flag", + }; + } + + let reportUnusedInlineConfigsFlag; + + if (usingFlatConfig) { + reportUnusedInlineConfigsFlag = { + option: "report-unused-inline-configs", + type: "String", + default: void 0, + description: + "Adds reported errors for unused eslint inline config comments", + enum: ["off", "warn", "error", "0", "1", "2"], + }; + } + + let mcpFlag; + + if (usingFlatConfig) { + mcpFlag = { + option: "mcp", + type: "Boolean", + description: "Start the ESLint MCP server", + }; + } + + let concurrencyFlag; + + if (usingFlatConfig) { + concurrencyFlag = { + option: "concurrency", + type: "Int|String", + default: "off", + description: + "Number of linting threads, auto to choose automatically, off for no multithreading", + }; + } + + return optionator({ + prepend: "eslint [options] file.js [file.js] [dir]", + defaults: { + concatRepeatedArrays: true, + mergeRepeatedObjects: true, + }, + options: [ + { + heading: "Basic configuration", + }, + lookupFlag, + { + option: "config", + alias: "c", + type: "path::String", + description: usingFlatConfig + ? "Use this configuration instead of eslint.config.js, eslint.config.mjs, or eslint.config.cjs" + : "Use this configuration, overriding .eslintrc.* config options if present", + }, + inspectConfigFlag, + envFlag, + extFlag, + { + option: "global", + type: "[String]", + description: "Define global variables", + }, + { + option: "parser", + type: "String", + description: "Specify the parser to be used", + }, + { + option: "parser-options", + type: "Object", + description: "Specify parser options", + }, + resolvePluginsFlag, + { + heading: "Specify Rules and Plugins", + }, + { + option: "plugin", + type: "[String]", + description: "Specify plugins", + }, + { + option: "rule", + type: "Object", + description: "Specify rules", + }, + rulesDirFlag, + { + heading: "Fix Problems", + }, + { + option: "fix", + type: "Boolean", + default: false, + description: "Automatically fix problems", + }, + { + option: "fix-dry-run", + type: "Boolean", + default: false, + description: + "Automatically fix problems without saving the changes to the file system", + }, + { + option: "fix-type", + type: "Array", + description: + "Specify the types of fixes to apply (directive, problem, suggestion, layout)", + }, + { + heading: "Ignore Files", + }, + ignorePathFlag, + { + option: "ignore", + type: "Boolean", + default: "true", + description: "Disable use of ignore files and patterns", + }, + { + option: "ignore-pattern", + type: "[String]", + description: `Patterns of files to ignore${usingFlatConfig ? "" : " (in addition to those in .eslintignore)"}`, + concatRepeatedArrays: [ + true, + { + oneValuePerFlag: true, + }, + ], + }, + { + heading: "Use stdin", + }, + { + option: "stdin", + type: "Boolean", + default: "false", + description: "Lint code provided on ", + }, + { + option: "stdin-filename", + type: "String", + description: "Specify filename to process STDIN as", + }, + { + heading: "Handle Warnings", + }, + { + option: "quiet", + type: "Boolean", + default: "false", + description: "Report errors only", + }, + { + option: "max-warnings", + type: "Int", + default: "-1", + description: "Number of warnings to trigger nonzero exit code", + }, + { + heading: "Output", + }, + { + option: "output-file", + alias: "o", + type: "path::String", + description: "Specify file to write report to", + }, + { + option: "format", + alias: "f", + type: "String", + default: "stylish", + description: "Use a specific output format", + }, + { + option: "color", + type: "Boolean", + alias: "no-color", + description: "Force enabling/disabling of color", + }, + { + heading: "Inline configuration comments", + }, + { + option: "inline-config", + type: "Boolean", + default: "true", + description: "Prevent comments from changing config or rules", + }, + { + option: "report-unused-disable-directives", + type: "Boolean", + default: void 0, + description: + "Adds reported errors for unused eslint-disable and eslint-enable directives", + }, + { + option: "report-unused-disable-directives-severity", + type: "String", + default: void 0, + description: + "Chooses severity level for reporting unused eslint-disable and eslint-enable directives", + enum: ["off", "warn", "error", "0", "1", "2"], + }, + reportUnusedInlineConfigsFlag, + { + heading: "Caching", + }, + { + option: "cache", + type: "Boolean", + default: "false", + description: "Only check changed files", + }, + { + option: "cache-file", + type: "path::String", + default: ".eslintcache", + description: + "Path to the cache file. Deprecated: use --cache-location", + }, + { + option: "cache-location", + type: "path::String", + description: "Path to the cache file or directory", + }, + { + option: "cache-strategy", + dependsOn: ["cache"], + type: "String", + default: "metadata", + enum: ["metadata", "content"], + description: + "Strategy to use for detecting changed files in the cache", + }, + { + heading: "Suppressing Violations", + }, + { + option: "suppress-all", + type: "Boolean", + default: "false", + description: "Suppress all violations", + }, + { + option: "suppress-rule", + type: "[String]", + description: "Suppress specific rules", + }, + { + option: "suppressions-location", + type: "path::String", + description: "Specify the location of the suppressions file", + }, + { + option: "prune-suppressions", + type: "Boolean", + default: "false", + description: "Prune unused suppressions", + }, + { + option: "pass-on-unpruned-suppressions", + type: "Boolean", + default: "false", + description: "Ignore unused suppressions", + }, + { + heading: "Miscellaneous", + }, + { + option: "init", + type: "Boolean", + default: "false", + description: "Run config initialization wizard", + }, + { + option: "env-info", + type: "Boolean", + default: "false", + description: "Output execution environment information", + }, + { + option: "error-on-unmatched-pattern", + type: "Boolean", + default: "true", + description: "Prevent errors when pattern is unmatched", + }, + { + option: "exit-on-fatal-error", + type: "Boolean", + default: "false", + description: "Exit with exit code 2 in case of fatal error", + }, + warnIgnoredFlag, + { + option: "pass-on-no-patterns", + type: "Boolean", + default: false, + description: + "Exit with exit code 0 in case no file patterns are passed", + }, + { + option: "debug", + type: "Boolean", + default: false, + description: "Output debugging information", + }, + { + option: "help", + alias: "h", + type: "Boolean", + description: "Show help", + }, + { + option: "version", + alias: "v", + type: "Boolean", + description: "Output the version number", + }, + { + option: "print-config", + type: "path::String", + description: "Print the configuration for the given file", + }, + statsFlag, + flagFlag, + mcpFlag, + concurrencyFlag, + ].filter(value => !!value), + }); +}; diff --git a/tools/ui/node_modules/eslint/lib/rule-tester/index.js b/tools/ui/node_modules/eslint/lib/rule-tester/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4fa651eb8fe53938ff0d747702c0da03b4a49520 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rule-tester/index.js @@ -0,0 +1,7 @@ +"use strict"; + +const RuleTester = require("./rule-tester"); + +module.exports = { + RuleTester, +}; diff --git a/tools/ui/node_modules/eslint/lib/rule-tester/rule-tester.js b/tools/ui/node_modules/eslint/lib/rule-tester/rule-tester.js new file mode 100644 index 0000000000000000000000000000000000000000..0085cd6bc5f2d9d4fde9429cd03bfadbac401321 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rule-tester/rule-tester.js @@ -0,0 +1,1579 @@ +/** + * @fileoverview Mocha/Jest test wrapper + * @author Ilya Volodin + */ +"use strict"; + +/* globals describe, it -- Mocha globals */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const assert = require("node:assert"), + util = require("node:util"), + path = require("node:path"), + equal = require("fast-deep-equal"), + Traverser = require("../shared/traverser"), + { Config } = require("../config/config"), + { Linter, SourceCodeFixer } = require("../linter"), + { interpolate, getPlaceholderMatcher } = require("../linter/interpolate"), + stringify = require("json-stable-stringify-without-jsonify"); + +const { FlatConfigArray } = require("../config/flat-config-array"); +const { + defaultConfig, + defaultRuleTesterConfig, +} = require("../config/default-config"); + +const ajv = require("../shared/ajv")({ strictDefaults: true }); + +const parserSymbol = Symbol.for("eslint.RuleTester.parser"); +const { ConfigArraySymbol } = require("@eslint/config-array"); +const { isSerializable } = require("../shared/serialization"); + +const jslang = require("../languages/js"); +const { SourceCode } = require("../languages/js/source-code"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** @import { LanguageOptions, RuleDefinition } from "@eslint/core" */ + +/** @typedef {import("../types").Linter.Parser} Parser */ + +/** + * A test case that is expected to pass lint. + * @typedef {Object} ValidTestCase + * @property {string} [name] Name for the test case. + * @property {string} code Code for the test case. + * @property {any[]} [options] Options for the test case. + * @property {Function} [before] Function to execute before testing the case. + * @property {Function} [after] Function to execute after testing the case regardless of its result. + * @property {LanguageOptions} [languageOptions] The language options to use in the test case. + * @property {{ [name: string]: any }} [settings] Settings for the test case. + * @property {string} [filename] The fake filename for the test case. Useful for rules that make assertion about filenames. + * @property {boolean} [only] Run only this test case or the subset of test cases with this property. + */ + +/** + * A test case that is expected to fail lint. + * @typedef {Object} InvalidTestCase + * @property {string} [name] Name for the test case. + * @property {string} code Code for the test case. + * @property {number | Array} errors Expected errors. + * @property {string | null} [output] The expected code after autofixes are applied. If set to `null`, the test runner will assert that no autofix is suggested. + * @property {any[]} [options] Options for the test case. + * @property {Function} [before] Function to execute before testing the case. + * @property {Function} [after] Function to execute after testing the case regardless of its result. + * @property {{ [name: string]: any }} [settings] Settings for the test case. + * @property {string} [filename] The fake filename for the test case. Useful for rules that make assertion about filenames. + * @property {LanguageOptions} [languageOptions] The language options to use in the test case. + * @property {boolean} [only] Run only this test case or the subset of test cases with this property. + */ + +/** + * A description of a reported error used in a rule tester test. + * @typedef {Object} TestCaseError + * @property {string | RegExp} [message] Message. + * @property {string} [messageId] Message ID. + * @property {string} [type] The type of the reported AST node. + * @property {{ [name: string]: string }} [data] The data used to fill the message template. + * @property {number} [line] The 1-based line number of the reported start location. + * @property {number} [column] The 1-based column number of the reported start location. + * @property {number} [endLine] The 1-based line number of the reported end location. + * @property {number} [endColumn] The 1-based column number of the reported end location. + */ + +//------------------------------------------------------------------------------ +// Private Members +//------------------------------------------------------------------------------ + +/* + * testerDefaultConfig must not be modified as it allows to reset the tester to + * the initial default configuration + */ +const testerDefaultConfig = { rules: {} }; + +/* + * RuleTester uses this config as its default. This can be overwritten via + * setDefaultConfig(). + */ +let sharedDefaultConfig = { rules: {} }; + +/* + * List every parameters possible on a test case that are not related to eslint + * configuration + */ +const RuleTesterParameters = [ + "name", + "code", + "filename", + "options", + "before", + "after", + "errors", + "output", + "only", +]; + +/* + * All allowed property names in error objects. + */ +const errorObjectParameters = new Set([ + "message", + "messageId", + "data", + "type", + "line", + "column", + "endLine", + "endColumn", + "suggestions", +]); +const friendlyErrorObjectParameterList = `[${[...errorObjectParameters].map(key => `'${key}'`).join(", ")}]`; + +/* + * All allowed property names in suggestion objects. + */ +const suggestionObjectParameters = new Set([ + "desc", + "messageId", + "data", + "output", +]); +const friendlySuggestionObjectParameterList = `[${[...suggestionObjectParameters].map(key => `'${key}'`).join(", ")}]`; + +/* + * Ignored test case properties when checking for test case duplicates. + */ +const duplicationIgnoredParameters = new Set(["name", "errors", "output"]); + +const forbiddenMethods = [ + "applyInlineConfig", + "applyLanguageOptions", + "finalize", +]; + +/** @type {Map} */ +const forbiddenMethodCalls = new Map( + forbiddenMethods.map(methodName => [methodName, new WeakSet()]), +); + +const hasOwnProperty = Function.call.bind(Object.hasOwnProperty); + +/** + * Clones a given value deeply. + * Note: This ignores `parent` property. + * @param {any} x A value to clone. + * @returns {any} A cloned value. + */ +function cloneDeeplyExcludesParent(x) { + if (typeof x === "object" && x !== null) { + if (Array.isArray(x)) { + return x.map(cloneDeeplyExcludesParent); + } + + const retv = {}; + + for (const key in x) { + if (key !== "parent" && hasOwnProperty(x, key)) { + retv[key] = cloneDeeplyExcludesParent(x[key]); + } + } + + return retv; + } + + return x; +} + +/** + * Freezes a given value deeply. + * @param {any} x A value to freeze. + * @param {Set} seenObjects Objects already seen during the traversal. + * @returns {void} + */ +function freezeDeeply(x, seenObjects = new Set()) { + if (typeof x === "object" && x !== null) { + if (seenObjects.has(x)) { + return; // skip to avoid infinite recursion + } + seenObjects.add(x); + + if (Array.isArray(x)) { + x.forEach(element => { + freezeDeeply(element, seenObjects); + }); + } else { + for (const key in x) { + if (key !== "parent" && hasOwnProperty(x, key)) { + freezeDeeply(x[key], seenObjects); + } + } + } + Object.freeze(x); + } +} + +/** + * Replace control characters by `\u00xx` form. + * @param {string} text The text to sanitize. + * @returns {string} The sanitized text. + */ +function sanitize(text) { + if (typeof text !== "string") { + return ""; + } + return text.replace( + /[\u0000-\u0009\u000b-\u001a]/gu, // eslint-disable-line no-control-regex -- Escaping controls + c => `\\u${c.codePointAt(0).toString(16).padStart(4, "0")}`, + ); +} + +/** + * Define `start`/`end` properties as throwing error. + * @param {string} objName Object name used for error messages. + * @param {ASTNode} node The node to define. + * @returns {void} + */ +function defineStartEndAsError(objName, node) { + Object.defineProperties(node, { + start: { + get() { + throw new Error( + `Use ${objName}.range[0] instead of ${objName}.start`, + ); + }, + configurable: true, + enumerable: false, + }, + end: { + get() { + throw new Error( + `Use ${objName}.range[1] instead of ${objName}.end`, + ); + }, + configurable: true, + enumerable: false, + }, + }); +} + +/** + * Define `start`/`end` properties of all nodes of the given AST as throwing error. + * @param {ASTNode} ast The root node to errorize `start`/`end` properties. + * @param {Object} [visitorKeys] Visitor keys to be used for traversing the given ast. + * @returns {void} + */ +function defineStartEndAsErrorInTree(ast, visitorKeys) { + Traverser.traverse(ast, { + visitorKeys, + enter: defineStartEndAsError.bind(null, "node"), + }); + ast.tokens.forEach(defineStartEndAsError.bind(null, "token")); + ast.comments.forEach(defineStartEndAsError.bind(null, "token")); +} + +/** + * Wraps the given parser in order to intercept and modify return values from the `parse` and `parseForESLint` methods, for test purposes. + * In particular, to modify ast nodes, tokens and comments to throw on access to their `start` and `end` properties. + * @param {Parser} parser Parser object. + * @returns {Parser} Wrapped parser object. + */ +function wrapParser(parser) { + if (typeof parser.parseForESLint === "function") { + return { + [parserSymbol]: parser, + parseForESLint(...args) { + const ret = parser.parseForESLint(...args); + + defineStartEndAsErrorInTree(ret.ast, ret.visitorKeys); + return ret; + }, + }; + } + + return { + [parserSymbol]: parser, + parse(...args) { + const ast = parser.parse(...args); + + defineStartEndAsErrorInTree(ast); + return ast; + }, + }; +} + +/** + * Function to replace forbidden `SourceCode` methods. Allows just one call per method. + * @param {string} methodName The name of the method to forbid. + * @param {Function} prototype The prototype with the original method to call. + * @returns {Function} The function that throws the error. + */ +function throwForbiddenMethodError(methodName, prototype) { + const original = prototype[methodName]; + + return function (...args) { + const called = forbiddenMethodCalls.get(methodName); + + /* eslint-disable no-invalid-this -- needed to operate as a method. */ + if (!called.has(this)) { + called.add(this); + + return original.apply(this, args); + } + /* eslint-enable no-invalid-this -- not needed past this point */ + + throw new Error( + `\`SourceCode#${methodName}()\` cannot be called inside a rule.`, + ); + }; +} + +/** + * Extracts names of {{ placeholders }} from the reported message. + * @param {string} message Reported message + * @returns {string[]} Array of placeholder names + */ +function getMessagePlaceholders(message) { + const matcher = getPlaceholderMatcher(); + + return Array.from(message.matchAll(matcher), ([, name]) => name.trim()); +} + +/** + * Returns the placeholders in the reported messages but + * only includes the placeholders available in the raw message and not in the provided data. + * @param {string} message The reported message + * @param {string} raw The raw message specified in the rule meta.messages + * @param {undefined|Record} data The passed + * @returns {string[]} Missing placeholder names + */ +function getUnsubstitutedMessagePlaceholders(message, raw, data = {}) { + const unsubstituted = getMessagePlaceholders(message); + + if (unsubstituted.length === 0) { + return []; + } + + // Remove false positives by only counting placeholders in the raw message, which were not provided in the data matcher or added with a data property + const known = getMessagePlaceholders(raw); + const provided = Object.keys(data); + + return unsubstituted.filter( + name => known.includes(name) && !provided.includes(name), + ); +} + +const metaSchemaDescription = ` +\t- If the rule has options, set \`meta.schema\` to an array or non-empty object to enable options validation. +\t- If the rule doesn't have options, omit \`meta.schema\` to enforce that no options can be passed to the rule. +\t- You can also set \`meta.schema\` to \`false\` to opt-out of options validation (not recommended). + +\thttps://eslint.org/docs/latest/extend/custom-rules#options-schemas +`; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +// default separators for testing +const DESCRIBE = Symbol("describe"); +const IT = Symbol("it"); +const IT_ONLY = Symbol("itOnly"); + +/** + * This is `it` default handler if `it` don't exist. + * @this {Mocha} + * @param {string} text The description of the test case. + * @param {Function} method The logic of the test case. + * @throws {Error} Any error upon execution of `method`. + * @returns {any} Returned value of `method`. + */ +function itDefaultHandler(text, method) { + try { + return method.call(this); + } catch (err) { + if (err instanceof assert.AssertionError) { + err.message += ` (${util.inspect(err.actual)} ${err.operator} ${util.inspect(err.expected)})`; + } + throw err; + } +} + +/** + * This is `describe` default handler if `describe` don't exist. + * @this {Mocha} + * @param {string} text The description of the test case. + * @param {Function} method The logic of the test case. + * @returns {any} Returned value of `method`. + */ +function describeDefaultHandler(text, method) { + return method.call(this); +} + +/** + * Mocha test wrapper. + */ +class RuleTester { + /** + * Creates a new instance of RuleTester. + * @param {Object} [testerConfig] Optional, extra configuration for the tester + */ + constructor(testerConfig = {}) { + /** + * The configuration to use for this tester. Combination of the tester + * configuration and the default configuration. + * @type {Object} + */ + this.testerConfig = [ + sharedDefaultConfig, + testerConfig, + { rules: { "rule-tester/validate-ast": "error" } }, + ]; + + this.linter = new Linter({ configType: "flat" }); + } + + /** + * Set the configuration to use for all future tests + * @param {Object} config the configuration to use. + * @throws {TypeError} If non-object config. + * @returns {void} + */ + static setDefaultConfig(config) { + if (typeof config !== "object" || config === null) { + throw new TypeError( + "RuleTester.setDefaultConfig: config must be an object", + ); + } + sharedDefaultConfig = config; + + // Make sure the rules object exists since it is assumed to exist later + sharedDefaultConfig.rules = sharedDefaultConfig.rules || {}; + } + + /** + * Get the current configuration used for all tests + * @returns {Object} the current configuration + */ + static getDefaultConfig() { + return sharedDefaultConfig; + } + + /** + * Reset the configuration to the initial configuration of the tester removing + * any changes made until now. + * @returns {void} + */ + static resetDefaultConfig() { + sharedDefaultConfig = { + rules: { + ...testerDefaultConfig.rules, + }, + }; + } + + /* + * If people use `mocha test.js --watch` command, `describe` and `it` function + * instances are different for each execution. So `describe` and `it` should get fresh instance + * always. + */ + static get describe() { + return ( + this[DESCRIBE] || + (typeof describe === "function" ? describe : describeDefaultHandler) + ); + } + + static set describe(value) { + this[DESCRIBE] = value; + } + + static get it() { + return this[IT] || (typeof it === "function" ? it : itDefaultHandler); + } + + static set it(value) { + this[IT] = value; + } + + /** + * Adds the `only` property to a test to run it in isolation. + * @param {string | ValidTestCase | InvalidTestCase} item A single test to run by itself. + * @returns {ValidTestCase | InvalidTestCase} The test with `only` set. + */ + static only(item) { + if (typeof item === "string") { + return { code: item, only: true }; + } + + return { ...item, only: true }; + } + + static get itOnly() { + if (typeof this[IT_ONLY] === "function") { + return this[IT_ONLY]; + } + if ( + typeof this[IT] === "function" && + typeof this[IT].only === "function" + ) { + return Function.bind.call(this[IT].only, this[IT]); + } + if (typeof it === "function" && typeof it.only === "function") { + return Function.bind.call(it.only, it); + } + + if ( + typeof this[DESCRIBE] === "function" || + typeof this[IT] === "function" + ) { + throw new Error( + "Set `RuleTester.itOnly` to use `only` with a custom test framework.\n" + + "See https://eslint.org/docs/latest/integrate/nodejs-api#customizing-ruletester for more.", + ); + } + if (typeof it === "function") { + throw new Error( + "The current test framework does not support exclusive tests with `only`.", + ); + } + throw new Error( + "To use `only`, use RuleTester with a test framework that provides `it.only()` like Mocha.", + ); + } + + static set itOnly(value) { + this[IT_ONLY] = value; + } + + /** + * Adds a new rule test to execute. + * @param {string} ruleName The name of the rule to run. + * @param {RuleDefinition} rule The rule to test. + * @param {{ + * valid: (ValidTestCase | string)[], + * invalid: InvalidTestCase[] + * }} test The collection of tests to run. + * @throws {TypeError|Error} If `rule` is not an object with a `create` method, + * or if non-object `test`, or if a required scenario of the given type is missing. + * @returns {void} + */ + run(ruleName, rule, test) { + const testerConfig = this.testerConfig, + requiredScenarios = ["valid", "invalid"], + scenarioErrors = [], + linter = this.linter, + ruleId = `rule-to-test/${ruleName}`; + + const seenValidTestCases = new Set(); + const seenInvalidTestCases = new Set(); + + if ( + !rule || + typeof rule !== "object" || + typeof rule.create !== "function" + ) { + throw new TypeError( + "Rule must be an object with a `create` method", + ); + } + + if (!test || typeof test !== "object") { + throw new TypeError( + `Test Scenarios for rule ${ruleName} : Could not find test scenario object`, + ); + } + + requiredScenarios.forEach(scenarioType => { + if (!test[scenarioType]) { + scenarioErrors.push( + `Could not find any ${scenarioType} test scenarios`, + ); + } + }); + + if (scenarioErrors.length > 0) { + throw new Error( + [`Test Scenarios for rule ${ruleName} is invalid:`] + .concat(scenarioErrors) + .join("\n"), + ); + } + + const baseConfig = [ + { + plugins: { + // copy root plugin over + "@": { + /* + * Parsers are wrapped to detect more errors, so this needs + * to be a new object for each call to run(), otherwise the + * parsers will be wrapped multiple times. + */ + parsers: { + ...defaultConfig[0].plugins["@"].parsers, + }, + + /* + * The rules key on the default plugin is a proxy to lazy-load + * just the rules that are needed. So, don't create a new object + * here, just use the default one to keep that performance + * enhancement. + */ + rules: defaultConfig[0].plugins["@"].rules, + languages: defaultConfig[0].plugins["@"].languages, + }, + "rule-to-test": { + rules: { + [ruleName]: Object.assign({}, rule, { + // Create a wrapper rule that freezes the `context` properties. + create(context) { + freezeDeeply(context.options); + freezeDeeply(context.settings); + freezeDeeply(context.parserOptions); + + // freezeDeeply(context.languageOptions); + + return rule.create(context); + }, + }), + }, + }, + }, + language: defaultConfig[0].language, + }, + ...defaultRuleTesterConfig, + ]; + + /** + * Runs a hook on the given item when it's assigned to the given property + * @param {string|Object} item Item to run the hook on + * @param {string} prop The property having the hook assigned to + * @throws {Error} If the property is not a function or that function throws an error + * @returns {void} + * @private + */ + function runHook(item, prop) { + if (typeof item === "object" && hasOwnProperty(item, prop)) { + assert.strictEqual( + typeof item[prop], + "function", + `Optional test case property '${prop}' must be a function`, + ); + item[prop](); + } + } + + /** + * Run the rule for the given item + * @param {string|Object} item Item to run the rule against + * @throws {Error} If an invalid schema. + * @returns {Object} Eslint run result + * @private + */ + function runRuleForItem(item) { + const flatConfigArrayOptions = { + baseConfig, + }; + + if (item.filename) { + flatConfigArrayOptions.basePath = + path.parse(item.filename).root || void 0; + } + + const configs = new FlatConfigArray( + testerConfig, + flatConfigArrayOptions, + ); + + /* + * Modify the returned config so that the parser is wrapped to catch + * access of the start/end properties. This method is called just + * once per code snippet being tested, so each test case gets a clean + * parser. + */ + configs[ConfigArraySymbol.finalizeConfig] = function (...args) { + // can't do super here :( + const proto = Object.getPrototypeOf(this); + const calculatedConfig = proto[ + ConfigArraySymbol.finalizeConfig + ].apply(this, args); + + // wrap the parser to catch start/end property access + if (calculatedConfig.language === jslang) { + calculatedConfig.languageOptions.parser = wrapParser( + calculatedConfig.languageOptions.parser, + ); + } + + return calculatedConfig; + }; + + let code, filename, output, beforeAST, afterAST; + + if (typeof item === "string") { + code = item; + } else { + code = item.code; + + /* + * Assumes everything on the item is a config except for the + * parameters used by this tester + */ + const itemConfig = { ...item }; + + for (const parameter of RuleTesterParameters) { + delete itemConfig[parameter]; + } + + /* + * Create the config object from the tester config and this item + * specific configurations. + */ + configs.push(itemConfig); + } + + if (hasOwnProperty(item, "only")) { + assert.ok( + typeof item.only === "boolean", + "Optional test case property 'only' must be a boolean", + ); + } + if (hasOwnProperty(item, "filename")) { + assert.ok( + typeof item.filename === "string", + "Optional test case property 'filename' must be a string", + ); + filename = item.filename; + } + + let ruleConfig = 1; + + if (hasOwnProperty(item, "options")) { + assert(Array.isArray(item.options), "options must be an array"); + ruleConfig = [1, ...item.options]; + } + + configs.push({ + rules: { + [ruleId]: ruleConfig, + }, + }); + + let schema; + + try { + schema = Config.getRuleOptionsSchema(rule); + } catch (err) { + err.message += metaSchemaDescription; + throw err; + } + + /* + * Check and throw an error if the schema is an empty object (`schema:{}`), because such schema + * doesn't validate or enforce anything and is therefore considered a possible error. If the intent + * was to skip options validation, `schema:false` should be set instead (explicit opt-out). + * + * For this purpose, a schema object is considered empty if it doesn't have any own enumerable string-keyed + * properties. While `ajv.compile()` does use enumerable properties from the prototype chain as well, + * it caches compiled schemas by serializing only own enumerable properties, so it's generally not a good idea + * to use inherited properties in schemas because schemas that differ only in inherited properties would end up + * having the same cache entry that would be correct for only one of them. + * + * At this point, `schema` can only be an object or `null`. + */ + if (schema && Object.keys(schema).length === 0) { + throw new Error( + `\`schema: {}\` is a no-op${metaSchemaDescription}`, + ); + } + + /* + * Setup AST getters. + * The goal is to check whether or not AST was modified when + * running the rule under test. + */ + configs.push({ + plugins: { + "rule-tester": { + rules: { + "validate-ast": { + create() { + return { + Program(node) { + beforeAST = + cloneDeeplyExcludesParent(node); + }, + "Program:exit"(node) { + afterAST = node; + }, + }; + }, + }, + }, + }, + }, + }); + + if (schema) { + ajv.validateSchema(schema); + + if (ajv.errors) { + const errors = ajv.errors + .map(error => { + const field = + error.dataPath[0] === "." + ? error.dataPath.slice(1) + : error.dataPath; + + return `\t${field}: ${error.message}`; + }) + .join("\n"); + + throw new Error([ + `Schema for rule ${ruleName} is invalid:`, + errors, + ]); + } + + /* + * `ajv.validateSchema` checks for errors in the structure of the schema (by comparing the schema against a "meta-schema"), + * and it reports those errors individually. However, there are other types of schema errors that only occur when compiling + * the schema (e.g. using invalid defaults in a schema), and only one of these errors can be reported at a time. As a result, + * the schema is compiled here separately from checking for `validateSchema` errors. + */ + try { + ajv.compile(schema); + } catch (err) { + throw new Error( + `Schema for rule ${ruleName} is invalid: ${err.message}`, + { + cause: err, + }, + ); + } + } + + // check for validation errors + try { + configs.normalizeSync(); + configs.getConfig("test.js"); + } catch (error) { + error.message = `ESLint configuration in rule-tester is invalid: ${error.message}`; + throw error; + } + + // Verify the code. + const { applyLanguageOptions, applyInlineConfig, finalize } = + SourceCode.prototype; + let messages; + + try { + forbiddenMethods.forEach(methodName => { + SourceCode.prototype[methodName] = + throwForbiddenMethodError( + methodName, + SourceCode.prototype, + ); + }); + + messages = linter.verify(code, configs, filename); + } finally { + SourceCode.prototype.applyInlineConfig = applyInlineConfig; + SourceCode.prototype.applyLanguageOptions = + applyLanguageOptions; + SourceCode.prototype.finalize = finalize; + } + + const fatalErrorMessage = messages.find(m => m.fatal); + + assert( + !fatalErrorMessage, + `A fatal parsing error occurred: ${fatalErrorMessage && fatalErrorMessage.message}`, + ); + + // Verify if autofix makes a syntax error or not. + if (messages.some(m => m.fix)) { + output = SourceCodeFixer.applyFixes(code, messages).output; + const errorMessageInFix = linter + .verify(output, configs, filename) + .find(m => m.fatal); + + assert( + !errorMessageInFix, + [ + "A fatal parsing error occurred in autofix.", + `Error: ${errorMessageInFix && errorMessageInFix.message}`, + "Autofix output:", + output, + ].join("\n"), + ); + } else { + output = code; + } + + return { + messages, + output, + beforeAST, + afterAST: cloneDeeplyExcludesParent(afterAST), + configs, + filename, + }; + } + + /** + * Check if the AST was changed + * @param {ASTNode} beforeAST AST node before running + * @param {ASTNode} afterAST AST node after running + * @returns {void} + * @private + */ + function assertASTDidntChange(beforeAST, afterAST) { + if (!equal(beforeAST, afterAST)) { + assert.fail("Rule should not modify AST."); + } + } + + /** + * Check if this test case is a duplicate of one we have seen before. + * @param {string|Object} item test case object + * @param {Set} seenTestCases set of serialized test cases we have seen so far (managed by this function) + * @returns {void} + * @private + */ + function checkDuplicateTestCase(item, seenTestCases) { + if (!isSerializable(item)) { + /* + * If we can't serialize a test case (because it contains a function, RegExp, etc), skip the check. + * This might happen with properties like: options, plugins, settings, languageOptions.parser, languageOptions.parserOptions. + */ + return; + } + + const normalizedItem = + typeof item === "string" ? { code: item } : item; + const serializedTestCase = stringify(normalizedItem, { + replacer(key, value) { + // "this" is the currently stringified object --> only ignore top-level properties + return normalizedItem !== this || + !duplicationIgnoredParameters.has(key) + ? value + : void 0; + }, + }); + + assert( + !seenTestCases.has(serializedTestCase), + "detected duplicate test case", + ); + seenTestCases.add(serializedTestCase); + } + + /** + * Check if the template is valid or not + * all valid cases go through this + * @param {string|Object} item Item to run the rule against + * @returns {void} + * @private + */ + function testValidTemplate(item) { + const code = typeof item === "object" ? item.code : item; + + assert.ok( + typeof code === "string", + "Test case must specify a string value for 'code'", + ); + if (item.name) { + assert.ok( + typeof item.name === "string", + "Optional test case property 'name' must be a string", + ); + } + + checkDuplicateTestCase(item, seenValidTestCases); + + const result = runRuleForItem(item); + const messages = result.messages; + + assert.strictEqual( + messages.length, + 0, + util.format( + "Should have no errors but had %d: %s", + messages.length, + util.inspect(messages), + ), + ); + + assertASTDidntChange(result.beforeAST, result.afterAST); + } + + /** + * Asserts that the message matches its expected value. If the expected + * value is a regular expression, it is checked against the actual + * value. + * @param {string} actual Actual value + * @param {string|RegExp} expected Expected value + * @returns {void} + * @private + */ + function assertMessageMatches(actual, expected) { + if (expected instanceof RegExp) { + // assert.js doesn't have a built-in RegExp match function + assert.ok( + expected.test(actual), + `Expected '${actual}' to match ${expected}`, + ); + } else { + assert.strictEqual(actual, expected); + } + } + + /** + * Check if the template is invalid or not + * all invalid cases go through this. + * @param {string|Object} item Item to run the rule against + * @returns {void} + * @private + */ + function testInvalidTemplate(item) { + assert.ok( + typeof item.code === "string", + "Test case must specify a string value for 'code'", + ); + if (item.name) { + assert.ok( + typeof item.name === "string", + "Optional test case property 'name' must be a string", + ); + } + assert.ok( + item.errors || item.errors === 0, + `Did not specify errors for an invalid test of ${ruleName}`, + ); + + if (Array.isArray(item.errors) && item.errors.length === 0) { + assert.fail("Invalid cases must have at least one error"); + } + + checkDuplicateTestCase(item, seenInvalidTestCases); + + const ruleHasMetaMessages = + hasOwnProperty(rule, "meta") && + hasOwnProperty(rule.meta, "messages"); + const friendlyIDList = ruleHasMetaMessages + ? `[${Object.keys(rule.meta.messages) + .map(key => `'${key}'`) + .join(", ")}]` + : null; + + const result = runRuleForItem(item); + const messages = result.messages; + + for (const message of messages) { + if (hasOwnProperty(message, "suggestions")) { + /** @type {Map} */ + const seenMessageIndices = new Map(); + + for (let i = 0; i < message.suggestions.length; i += 1) { + const suggestionMessage = message.suggestions[i].desc; + const previous = + seenMessageIndices.get(suggestionMessage); + + assert.ok( + !seenMessageIndices.has(suggestionMessage), + `Suggestion message '${suggestionMessage}' reported from suggestion ${i} was previously reported by suggestion ${previous}. Suggestion messages should be unique within an error.`, + ); + seenMessageIndices.set(suggestionMessage, i); + } + } + } + + if (typeof item.errors === "number") { + if (item.errors === 0) { + assert.fail( + "Invalid cases must have 'error' value greater than 0", + ); + } + + assert.strictEqual( + messages.length, + item.errors, + util.format( + "Should have %d error%s but had %d: %s", + item.errors, + item.errors === 1 ? "" : "s", + messages.length, + util.inspect(messages), + ), + ); + } else { + assert.strictEqual( + messages.length, + item.errors.length, + util.format( + "Should have %d error%s but had %d: %s", + item.errors.length, + item.errors.length === 1 ? "" : "s", + messages.length, + util.inspect(messages), + ), + ); + + const hasMessageOfThisRule = messages.some( + m => m.ruleId === ruleId, + ); + + for (let i = 0, l = item.errors.length; i < l; i++) { + const error = item.errors[i]; + const message = messages[i]; + + assert( + hasMessageOfThisRule, + "Error rule name should be the same as the name of the rule being tested", + ); + + if (typeof error === "string" || error instanceof RegExp) { + // Just an error message. + assertMessageMatches(message.message, error); + assert.ok( + message.suggestions === void 0, + `Error at index ${i} has suggestions. Please convert the test error into an object and specify 'suggestions' property on it to test suggestions.`, + ); + } else if (typeof error === "object" && error !== null) { + /* + * Error object. + * This may have a message, messageId, data, node type, line, and/or + * column. + */ + + Object.keys(error).forEach(propertyName => { + assert.ok( + errorObjectParameters.has(propertyName), + `Invalid error property name '${propertyName}'. Expected one of ${friendlyErrorObjectParameterList}.`, + ); + }); + + if (hasOwnProperty(error, "message")) { + assert.ok( + !hasOwnProperty(error, "messageId"), + "Error should not specify both 'message' and a 'messageId'.", + ); + assert.ok( + !hasOwnProperty(error, "data"), + "Error should not specify both 'data' and 'message'.", + ); + assertMessageMatches( + message.message, + error.message, + ); + } else if (hasOwnProperty(error, "messageId")) { + assert.ok( + ruleHasMetaMessages, + "Error can not use 'messageId' if rule under test doesn't define 'meta.messages'.", + ); + if ( + !hasOwnProperty( + rule.meta.messages, + error.messageId, + ) + ) { + assert( + false, + `Invalid messageId '${error.messageId}'. Expected one of ${friendlyIDList}.`, + ); + } + assert.strictEqual( + message.messageId, + error.messageId, + `messageId '${message.messageId}' does not match expected messageId '${error.messageId}'.`, + ); + + const unsubstitutedPlaceholders = + getUnsubstitutedMessagePlaceholders( + message.message, + rule.meta.messages[message.messageId], + error.data, + ); + + assert.ok( + unsubstitutedPlaceholders.length === 0, + `The reported message has ${unsubstitutedPlaceholders.length > 1 ? `unsubstituted placeholders: ${unsubstitutedPlaceholders.map(name => `'${name}'`).join(", ")}` : `an unsubstituted placeholder '${unsubstitutedPlaceholders[0]}'`}. Please provide the missing ${unsubstitutedPlaceholders.length > 1 ? "values" : "value"} via the 'data' property in the context.report() call.`, + ); + + if (hasOwnProperty(error, "data")) { + /* + * if data was provided, then directly compare the returned message to a synthetic + * interpolated message using the same message ID and data provided in the test. + * See https://github.com/eslint/eslint/issues/9890 for context. + */ + const unformattedOriginalMessage = + rule.meta.messages[error.messageId]; + const rehydratedMessage = interpolate( + unformattedOriginalMessage, + error.data, + ); + + assert.strictEqual( + message.message, + rehydratedMessage, + `Hydrated message "${rehydratedMessage}" does not match "${message.message}"`, + ); + } + } else { + assert.fail( + "Test error must specify either a 'messageId' or 'message'.", + ); + } + + if (error.type) { + assert.strictEqual( + message.nodeType, + error.type, + `Error type should be ${error.type}, found ${message.nodeType}`, + ); + } + + const actualLocation = {}; + const expectedLocation = {}; + + if (hasOwnProperty(error, "line")) { + actualLocation.line = message.line; + expectedLocation.line = error.line; + } + + if (hasOwnProperty(error, "column")) { + actualLocation.column = message.column; + expectedLocation.column = error.column; + } + + if (hasOwnProperty(error, "endLine")) { + actualLocation.endLine = message.endLine; + expectedLocation.endLine = error.endLine; + } + + if (hasOwnProperty(error, "endColumn")) { + actualLocation.endColumn = message.endColumn; + expectedLocation.endColumn = error.endColumn; + } + + if (Object.keys(expectedLocation).length > 0) { + assert.deepStrictEqual( + actualLocation, + expectedLocation, + "Actual error location does not match expected error location.", + ); + } + + assert.ok( + !message.suggestions || + hasOwnProperty(error, "suggestions"), + `Error at index ${i} has suggestions. Please specify 'suggestions' property on the test error object.`, + ); + if (hasOwnProperty(error, "suggestions")) { + // Support asserting there are no suggestions + const expectsSuggestions = Array.isArray( + error.suggestions, + ) + ? error.suggestions.length > 0 + : Boolean(error.suggestions); + const hasSuggestions = + message.suggestions !== void 0; + + if (!hasSuggestions && expectsSuggestions) { + assert.ok( + !error.suggestions, + `Error should have suggestions on error with message: "${message.message}"`, + ); + } else if (hasSuggestions) { + assert.ok( + expectsSuggestions, + `Error should have no suggestions on error with message: "${message.message}"`, + ); + if (typeof error.suggestions === "number") { + assert.strictEqual( + message.suggestions.length, + error.suggestions, + `Error should have ${error.suggestions} suggestions. Instead found ${message.suggestions.length} suggestions`, + ); + } else if (Array.isArray(error.suggestions)) { + assert.strictEqual( + message.suggestions.length, + error.suggestions.length, + `Error should have ${error.suggestions.length} suggestions. Instead found ${message.suggestions.length} suggestions`, + ); + + error.suggestions.forEach( + (expectedSuggestion, index) => { + assert.ok( + typeof expectedSuggestion === + "object" && + expectedSuggestion !== null, + "Test suggestion in 'suggestions' array must be an object.", + ); + Object.keys( + expectedSuggestion, + ).forEach(propertyName => { + assert.ok( + suggestionObjectParameters.has( + propertyName, + ), + `Invalid suggestion property name '${propertyName}'. Expected one of ${friendlySuggestionObjectParameterList}.`, + ); + }); + + const actualSuggestion = + message.suggestions[index]; + const suggestionPrefix = `Error Suggestion at index ${index}:`; + + if ( + hasOwnProperty( + expectedSuggestion, + "desc", + ) + ) { + assert.ok( + !hasOwnProperty( + expectedSuggestion, + "data", + ), + `${suggestionPrefix} Test should not specify both 'desc' and 'data'.`, + ); + assert.ok( + !hasOwnProperty( + expectedSuggestion, + "messageId", + ), + `${suggestionPrefix} Test should not specify both 'desc' and 'messageId'.`, + ); + assert.strictEqual( + actualSuggestion.desc, + expectedSuggestion.desc, + `${suggestionPrefix} desc should be "${expectedSuggestion.desc}" but got "${actualSuggestion.desc}" instead.`, + ); + } else if ( + hasOwnProperty( + expectedSuggestion, + "messageId", + ) + ) { + assert.ok( + ruleHasMetaMessages, + `${suggestionPrefix} Test can not use 'messageId' if rule under test doesn't define 'meta.messages'.`, + ); + assert.ok( + hasOwnProperty( + rule.meta.messages, + expectedSuggestion.messageId, + ), + `${suggestionPrefix} Test has invalid messageId '${expectedSuggestion.messageId}', the rule under test allows only one of ${friendlyIDList}.`, + ); + assert.strictEqual( + actualSuggestion.messageId, + expectedSuggestion.messageId, + `${suggestionPrefix} messageId should be '${expectedSuggestion.messageId}' but got '${actualSuggestion.messageId}' instead.`, + ); + + const unsubstitutedPlaceholders = + getUnsubstitutedMessagePlaceholders( + actualSuggestion.desc, + rule.meta.messages[ + expectedSuggestion + .messageId + ], + expectedSuggestion.data, + ); + + assert.ok( + unsubstitutedPlaceholders.length === + 0, + `The message of the suggestion has ${unsubstitutedPlaceholders.length > 1 ? `unsubstituted placeholders: ${unsubstitutedPlaceholders.map(name => `'${name}'`).join(", ")}` : `an unsubstituted placeholder '${unsubstitutedPlaceholders[0]}'`}. Please provide the missing ${unsubstitutedPlaceholders.length > 1 ? "values" : "value"} via the 'data' property for the suggestion in the context.report() call.`, + ); + + if ( + hasOwnProperty( + expectedSuggestion, + "data", + ) + ) { + const unformattedMetaMessage = + rule.meta.messages[ + expectedSuggestion + .messageId + ]; + const rehydratedDesc = + interpolate( + unformattedMetaMessage, + expectedSuggestion.data, + ); + + assert.strictEqual( + actualSuggestion.desc, + rehydratedDesc, + `${suggestionPrefix} Hydrated test desc "${rehydratedDesc}" does not match received desc "${actualSuggestion.desc}".`, + ); + } + } else if ( + hasOwnProperty( + expectedSuggestion, + "data", + ) + ) { + assert.fail( + `${suggestionPrefix} Test must specify 'messageId' if 'data' is used.`, + ); + } else { + assert.fail( + `${suggestionPrefix} Test must specify either 'messageId' or 'desc'.`, + ); + } + + assert.ok( + hasOwnProperty( + expectedSuggestion, + "output", + ), + `${suggestionPrefix} The "output" property is required.`, + ); + const codeWithAppliedSuggestion = + SourceCodeFixer.applyFixes( + item.code, + [actualSuggestion], + ).output; + + // Verify if suggestion fix makes a syntax error or not. + const errorMessageInSuggestion = + linter + .verify( + codeWithAppliedSuggestion, + result.configs, + result.filename, + ) + .find(m => m.fatal); + + assert( + !errorMessageInSuggestion, + [ + "A fatal parsing error occurred in suggestion fix.", + `Error: ${errorMessageInSuggestion && errorMessageInSuggestion.message}`, + "Suggestion output:", + codeWithAppliedSuggestion, + ].join("\n"), + ); + + assert.strictEqual( + codeWithAppliedSuggestion, + expectedSuggestion.output, + `Expected the applied suggestion fix to match the test suggestion output for suggestion at index: ${index} on error with message: "${message.message}"`, + ); + assert.notStrictEqual( + expectedSuggestion.output, + item.code, + `The output of a suggestion should differ from the original source code for suggestion at index: ${index} on error with message: "${message.message}"`, + ); + }, + ); + } else { + assert.fail( + "Test error object property 'suggestions' should be an array or a number", + ); + } + } + } + } else { + // Message was an unexpected type + assert.fail( + `Error should be a string, object, or RegExp, but found (${util.inspect(message)})`, + ); + } + } + } + + if (hasOwnProperty(item, "output")) { + if (item.output === null) { + assert.strictEqual( + result.output, + item.code, + "Expected no autofixes to be suggested", + ); + } else { + assert.strictEqual( + result.output, + item.output, + "Output is incorrect.", + ); + assert.notStrictEqual( + item.code, + item.output, + "Test property 'output' matches 'code'. If no autofix is expected, then omit the 'output' property or set it to null.", + ); + } + } else { + assert.strictEqual( + result.output, + item.code, + "The rule fixed the code. Please add 'output' property.", + ); + } + + assertASTDidntChange(result.beforeAST, result.afterAST); + } + + /* + * This creates a mocha test suite and pipes all supplied info through + * one of the templates above. + * The test suites for valid/invalid are created conditionally as + * test runners (eg. vitest) fail for empty test suites. + */ + this.constructor.describe(ruleName, () => { + if (test.valid.length > 0) { + this.constructor.describe("valid", () => { + test.valid.forEach(valid => { + this.constructor[valid.only ? "itOnly" : "it"]( + sanitize( + typeof valid === "object" + ? valid.name || valid.code + : valid, + ), + () => { + try { + runHook(valid, "before"); + testValidTemplate(valid); + } finally { + runHook(valid, "after"); + } + }, + ); + }); + }); + } + + if (test.invalid.length > 0) { + this.constructor.describe("invalid", () => { + test.invalid.forEach(invalid => { + this.constructor[invalid.only ? "itOnly" : "it"]( + sanitize(invalid.name || invalid.code), + () => { + try { + runHook(invalid, "before"); + testInvalidTemplate(invalid); + } finally { + runHook(invalid, "after"); + } + }, + ); + }); + }); + } + }); + } +} + +RuleTester[DESCRIBE] = RuleTester[IT] = RuleTester[IT_ONLY] = null; + +module.exports = RuleTester; diff --git a/tools/ui/node_modules/eslint/lib/rules/accessor-pairs.js b/tools/ui/node_modules/eslint/lib/rules/accessor-pairs.js new file mode 100644 index 0000000000000000000000000000000000000000..4af67ad772ca8425568930065b0ea00229f7aaa8 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/accessor-pairs.js @@ -0,0 +1,420 @@ +/** + * @fileoverview Rule to enforce getter and setter pairs in objects and classes. + * @author Gyandeep Singh + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** + * Property name if it can be computed statically, otherwise the list of the tokens of the key node. + * @typedef {string|Token[]} Key + */ + +/** + * Accessor nodes with the same key. + * @typedef {Object} AccessorData + * @property {Key} key Accessor's key + * @property {ASTNode[]} getters List of getter nodes. + * @property {ASTNode[]} setters List of setter nodes. + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not the given lists represent the equal tokens in the same order. + * Tokens are compared by their properties, not by instance. + * @param {Token[]} left First list of tokens. + * @param {Token[]} right Second list of tokens. + * @returns {boolean} `true` if the lists have same tokens. + */ +function areEqualTokenLists(left, right) { + if (left.length !== right.length) { + return false; + } + + for (let i = 0; i < left.length; i++) { + const leftToken = left[i], + rightToken = right[i]; + + if ( + leftToken.type !== rightToken.type || + leftToken.value !== rightToken.value + ) { + return false; + } + } + + return true; +} + +/** + * Checks whether or not the given keys are equal. + * @param {Key} left First key. + * @param {Key} right Second key. + * @returns {boolean} `true` if the keys are equal. + */ +function areEqualKeys(left, right) { + if (typeof left === "string" && typeof right === "string") { + // Statically computed names. + return left === right; + } + if (Array.isArray(left) && Array.isArray(right)) { + // Token lists. + return areEqualTokenLists(left, right); + } + + return false; +} + +/** + * Checks whether or not a given node is of an accessor kind ('get' or 'set'). + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is of an accessor kind. + */ +function isAccessorKind(node) { + return node.kind === "get" || node.kind === "set"; +} + +/** + * Checks whether or not a given node is an argument of a specified method call. + * @param {ASTNode} node A node to check. + * @param {number} index An expected index of the node in arguments. + * @param {string} object An expected name of the object of the method. + * @param {string} property An expected name of the method. + * @returns {boolean} `true` if the node is an argument of the specified method call. + */ +function isArgumentOfMethodCall(node, index, object, property) { + const parent = node.parent; + + return ( + parent.type === "CallExpression" && + astUtils.isSpecificMemberAccess(parent.callee, object, property) && + parent.arguments[index] === node + ); +} + +/** + * Checks whether or not a given node is a property descriptor. + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is a property descriptor. + */ +function isPropertyDescriptor(node) { + // Object.defineProperty(obj, "foo", {set: ...}) + if ( + isArgumentOfMethodCall(node, 2, "Object", "defineProperty") || + isArgumentOfMethodCall(node, 2, "Reflect", "defineProperty") + ) { + return true; + } + + /* + * Object.defineProperties(obj, {foo: {set: ...}}) + * Object.create(proto, {foo: {set: ...}}) + */ + const grandparent = node.parent.parent; + + return ( + grandparent.type === "ObjectExpression" && + (isArgumentOfMethodCall(grandparent, 1, "Object", "create") || + isArgumentOfMethodCall( + grandparent, + 1, + "Object", + "defineProperties", + )) + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + enforceForTSTypes: false, + enforceForClassMembers: true, + getWithoutSet: false, + setWithoutGet: true, + }, + ], + + docs: { + description: + "Enforce getter and setter pairs in objects and classes", + recommended: false, + url: "https://eslint.org/docs/latest/rules/accessor-pairs", + }, + + schema: [ + { + type: "object", + properties: { + getWithoutSet: { + type: "boolean", + }, + setWithoutGet: { + type: "boolean", + }, + enforceForClassMembers: { + type: "boolean", + }, + enforceForTSTypes: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + missingGetterInPropertyDescriptor: + "Getter is not present in property descriptor.", + missingSetterInPropertyDescriptor: + "Setter is not present in property descriptor.", + missingGetterInObjectLiteral: + "Getter is not present for {{ name }}.", + missingSetterInObjectLiteral: + "Setter is not present for {{ name }}.", + missingGetterInClass: "Getter is not present for class {{ name }}.", + missingSetterInClass: "Setter is not present for class {{ name }}.", + missingGetterInType: "Getter is not present for type {{ name }}.", + missingSetterInType: "Setter is not present for type {{ name }}.", + }, + }, + create(context) { + const [ + { + getWithoutSet: checkGetWithoutSet, + setWithoutGet: checkSetWithoutGet, + enforceForClassMembers, + enforceForTSTypes, + }, + ] = context.options; + const sourceCode = context.sourceCode; + + /** + * Reports the given node. + * @param {ASTNode} node The node to report. + * @param {string} messageKind "missingGetter" or "missingSetter". + * @returns {void} + * @private + */ + function report(node, messageKind) { + if (node.type === "Property") { + context.report({ + node, + messageId: `${messageKind}InObjectLiteral`, + loc: astUtils.getFunctionHeadLoc(node.value, sourceCode), + data: { + name: astUtils.getFunctionNameWithKind(node.value), + }, + }); + } else if (node.type === "MethodDefinition") { + context.report({ + node, + messageId: `${messageKind}InClass`, + loc: astUtils.getFunctionHeadLoc(node.value, sourceCode), + data: { + name: astUtils.getFunctionNameWithKind(node.value), + }, + }); + } else if (node.type === "TSMethodSignature") { + context.report({ + node, + messageId: `${messageKind}InType`, + loc: astUtils.getFunctionHeadLoc(node, sourceCode), + data: { + name: astUtils.getFunctionNameWithKind(node), + }, + }); + } else { + context.report({ + node, + messageId: `${messageKind}InPropertyDescriptor`, + }); + } + } + + /** + * Reports each of the nodes in the given list using the same messageId. + * @param {ASTNode[]} nodes Nodes to report. + * @param {string} messageKind "missingGetter" or "missingSetter". + * @returns {void} + * @private + */ + function reportList(nodes, messageKind) { + for (const node of nodes) { + report(node, messageKind); + } + } + + /** + * Checks accessor pairs in the given list of nodes. + * @param {ASTNode[]} nodes The list to check. + * @returns {void} + * @private + */ + function checkList(nodes) { + const accessors = []; + let found = false; + + for (let i = 0; i < nodes.length; i++) { + const node = nodes[i]; + + if (isAccessorKind(node)) { + // Creates a new `AccessorData` object for the given getter or setter node. + const name = astUtils.getStaticPropertyName(node); + const key = + name !== null ? name : sourceCode.getTokens(node.key); + + // Merges the given `AccessorData` object into the given accessors list. + for (let j = 0; j < accessors.length; j++) { + const accessor = accessors[j]; + + if (areEqualKeys(accessor.key, key)) { + accessor.getters.push( + ...(node.kind === "get" ? [node] : []), + ); + accessor.setters.push( + ...(node.kind === "set" ? [node] : []), + ); + found = true; + break; + } + } + if (!found) { + accessors.push({ + key, + getters: node.kind === "get" ? [node] : [], + setters: node.kind === "set" ? [node] : [], + }); + } + found = false; + } + } + + for (const { getters, setters } of accessors) { + if (checkSetWithoutGet && setters.length && !getters.length) { + reportList(setters, "missingGetter"); + } + if (checkGetWithoutSet && getters.length && !setters.length) { + reportList(getters, "missingSetter"); + } + } + } + + /** + * Checks accessor pairs in an object literal. + * @param {ASTNode} node `ObjectExpression` node to check. + * @returns {void} + * @private + */ + function checkObjectLiteral(node) { + checkList(node.properties.filter(p => p.type === "Property")); + } + + /** + * Checks accessor pairs in a property descriptor. + * @param {ASTNode} node Property descriptor `ObjectExpression` node to check. + * @returns {void} + * @private + */ + function checkPropertyDescriptor(node) { + const namesToCheck = new Set( + node.properties + .filter( + p => + p.type === "Property" && + p.kind === "init" && + !p.computed, + ) + .map(({ key }) => key.name), + ); + + const hasGetter = namesToCheck.has("get"); + const hasSetter = namesToCheck.has("set"); + + if (checkSetWithoutGet && hasSetter && !hasGetter) { + report(node, "missingGetter"); + } + if (checkGetWithoutSet && hasGetter && !hasSetter) { + report(node, "missingSetter"); + } + } + + /** + * Checks the given object expression as an object literal and as a possible property descriptor. + * @param {ASTNode} node `ObjectExpression` node to check. + * @returns {void} + * @private + */ + function checkObjectExpression(node) { + checkObjectLiteral(node); + if (isPropertyDescriptor(node)) { + checkPropertyDescriptor(node); + } + } + + /** + * Checks the given class body. + * @param {ASTNode} node `ClassBody` node to check. + * @returns {void} + * @private + */ + function checkClassBody(node) { + const methodDefinitions = node.body.filter( + m => m.type === "MethodDefinition", + ); + + checkList(methodDefinitions.filter(m => m.static)); + checkList(methodDefinitions.filter(m => !m.static)); + } + + /** + * Checks the given type. + * @param {ASTNode} node `TSTypeLiteral` or `TSInterfaceBody` node to check. + * @returns {void} + * @private + */ + function checkType(node) { + const members = + node.type === "TSTypeLiteral" ? node.members : node.body; + const methodDefinitions = members.filter( + m => m.type === "TSMethodSignature", + ); + + checkList(methodDefinitions); + } + + const listeners = {}; + + if (checkSetWithoutGet || checkGetWithoutSet) { + listeners.ObjectExpression = checkObjectExpression; + if (enforceForClassMembers) { + listeners.ClassBody = checkClassBody; + } + if (enforceForTSTypes) { + listeners["TSTypeLiteral, TSInterfaceBody"] = checkType; + } + } + + return listeners; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/array-bracket-newline.js b/tools/ui/node_modules/eslint/lib/rules/array-bracket-newline.js new file mode 100644 index 0000000000000000000000000000000000000000..56887af130e2c5f98870b7f0b4885b60d0c97479 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/array-bracket-newline.js @@ -0,0 +1,291 @@ +/** + * @fileoverview Rule to enforce linebreaks after open and before close array brackets + * @author Jan Peer Stöcklmair + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "array-bracket-newline", + url: "https://eslint.style/rules/array-bracket-newline", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Enforce linebreaks after opening and before closing array brackets", + recommended: false, + url: "https://eslint.org/docs/latest/rules/array-bracket-newline", + }, + + fixable: "whitespace", + + schema: [ + { + oneOf: [ + { + enum: ["always", "never", "consistent"], + }, + { + type: "object", + properties: { + multiline: { + type: "boolean", + }, + minItems: { + type: ["integer", "null"], + minimum: 0, + }, + }, + additionalProperties: false, + }, + ], + }, + ], + + messages: { + unexpectedOpeningLinebreak: + "There should be no linebreak after '['.", + unexpectedClosingLinebreak: + "There should be no linebreak before ']'.", + missingOpeningLinebreak: "A linebreak is required after '['.", + missingClosingLinebreak: "A linebreak is required before ']'.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + //---------------------------------------------------------------------- + // Helpers + //---------------------------------------------------------------------- + + /** + * Normalizes a given option value. + * @param {string|Object|undefined} option An option value to parse. + * @returns {{multiline: boolean, minItems: number}} Normalized option object. + */ + function normalizeOptionValue(option) { + let consistent = false; + let multiline = false; + let minItems; + + if (option) { + if (option === "consistent") { + consistent = true; + minItems = Number.POSITIVE_INFINITY; + } else if (option === "always" || option.minItems === 0) { + minItems = 0; + } else if (option === "never") { + minItems = Number.POSITIVE_INFINITY; + } else { + multiline = Boolean(option.multiline); + minItems = option.minItems || Number.POSITIVE_INFINITY; + } + } else { + consistent = false; + multiline = true; + minItems = Number.POSITIVE_INFINITY; + } + + return { consistent, multiline, minItems }; + } + + /** + * Normalizes a given option value. + * @param {string|Object|undefined} options An option value to parse. + * @returns {{ArrayExpression: {multiline: boolean, minItems: number}, ArrayPattern: {multiline: boolean, minItems: number}}} Normalized option object. + */ + function normalizeOptions(options) { + const value = normalizeOptionValue(options); + + return { ArrayExpression: value, ArrayPattern: value }; + } + + /** + * Reports that there shouldn't be a linebreak after the first token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportNoBeginningLinebreak(node, token) { + context.report({ + node, + loc: token.loc, + messageId: "unexpectedOpeningLinebreak", + fix(fixer) { + const nextToken = sourceCode.getTokenAfter(token, { + includeComments: true, + }); + + if (astUtils.isCommentToken(nextToken)) { + return null; + } + + return fixer.removeRange([ + token.range[1], + nextToken.range[0], + ]); + }, + }); + } + + /** + * Reports that there shouldn't be a linebreak before the last token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportNoEndingLinebreak(node, token) { + context.report({ + node, + loc: token.loc, + messageId: "unexpectedClosingLinebreak", + fix(fixer) { + const previousToken = sourceCode.getTokenBefore(token, { + includeComments: true, + }); + + if (astUtils.isCommentToken(previousToken)) { + return null; + } + + return fixer.removeRange([ + previousToken.range[1], + token.range[0], + ]); + }, + }); + } + + /** + * Reports that there should be a linebreak after the first token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportRequiredBeginningLinebreak(node, token) { + context.report({ + node, + loc: token.loc, + messageId: "missingOpeningLinebreak", + fix(fixer) { + return fixer.insertTextAfter(token, "\n"); + }, + }); + } + + /** + * Reports that there should be a linebreak before the last token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportRequiredEndingLinebreak(node, token) { + context.report({ + node, + loc: token.loc, + messageId: "missingClosingLinebreak", + fix(fixer) { + return fixer.insertTextBefore(token, "\n"); + }, + }); + } + + /** + * Reports a given node if it violated this rule. + * @param {ASTNode} node A node to check. This is an ArrayExpression node or an ArrayPattern node. + * @returns {void} + */ + function check(node) { + const elements = node.elements; + const normalizedOptions = normalizeOptions(context.options[0]); + const options = normalizedOptions[node.type]; + const openBracket = sourceCode.getFirstToken(node); + const closeBracket = sourceCode.getLastToken(node); + const firstIncComment = sourceCode.getTokenAfter(openBracket, { + includeComments: true, + }); + const lastIncComment = sourceCode.getTokenBefore(closeBracket, { + includeComments: true, + }); + const first = sourceCode.getTokenAfter(openBracket); + const last = sourceCode.getTokenBefore(closeBracket); + + const needsLinebreaks = + elements.length >= options.minItems || + (options.multiline && + elements.length > 0 && + firstIncComment.loc.start.line !== + lastIncComment.loc.end.line) || + (elements.length === 0 && + firstIncComment.type === "Block" && + firstIncComment.loc.start.line !== + lastIncComment.loc.end.line && + firstIncComment === lastIncComment) || + (options.consistent && + openBracket.loc.end.line !== first.loc.start.line); + + /* + * Use tokens or comments to check multiline or not. + * But use only tokens to check whether linebreaks are needed. + * This allows: + * var arr = [ // eslint-disable-line foo + * 'a' + * ] + */ + + if (needsLinebreaks) { + if (astUtils.isTokenOnSameLine(openBracket, first)) { + reportRequiredBeginningLinebreak(node, openBracket); + } + if (astUtils.isTokenOnSameLine(last, closeBracket)) { + reportRequiredEndingLinebreak(node, closeBracket); + } + } else { + if (!astUtils.isTokenOnSameLine(openBracket, first)) { + reportNoBeginningLinebreak(node, openBracket); + } + if (!astUtils.isTokenOnSameLine(last, closeBracket)) { + reportNoEndingLinebreak(node, closeBracket); + } + } + } + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + + return { + ArrayPattern: check, + ArrayExpression: check, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/array-bracket-spacing.js b/tools/ui/node_modules/eslint/lib/rules/array-bracket-spacing.js new file mode 100644 index 0000000000000000000000000000000000000000..dbe88f1b4eb54d655b57c401b9441b2e09368c6e --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/array-bracket-spacing.js @@ -0,0 +1,301 @@ +/** + * @fileoverview Disallows or enforces spaces inside of array brackets. + * @author Jamund Ferguson + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "array-bracket-spacing", + url: "https://eslint.style/rules/array-bracket-spacing", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce consistent spacing inside array brackets", + recommended: false, + url: "https://eslint.org/docs/latest/rules/array-bracket-spacing", + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["always", "never"], + }, + { + type: "object", + properties: { + singleValue: { + type: "boolean", + }, + objectsInArrays: { + type: "boolean", + }, + arraysInArrays: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpectedSpaceAfter: + "There should be no space after '{{tokenValue}}'.", + unexpectedSpaceBefore: + "There should be no space before '{{tokenValue}}'.", + missingSpaceAfter: "A space is required after '{{tokenValue}}'.", + missingSpaceBefore: "A space is required before '{{tokenValue}}'.", + }, + }, + create(context) { + const spaced = context.options[0] === "always", + sourceCode = context.sourceCode; + + /** + * Determines whether an option is set, relative to the spacing option. + * If spaced is "always", then check whether option is set to false. + * If spaced is "never", then check whether option is set to true. + * @param {Object} option The option to exclude. + * @returns {boolean} Whether or not the property is excluded. + */ + function isOptionSet(option) { + return context.options[1] + ? context.options[1][option] === !spaced + : false; + } + + const options = { + spaced, + singleElementException: isOptionSet("singleValue"), + objectsInArraysException: isOptionSet("objectsInArrays"), + arraysInArraysException: isOptionSet("arraysInArrays"), + }; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Reports that there shouldn't be a space after the first token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportNoBeginningSpace(node, token) { + const nextToken = sourceCode.getTokenAfter(token); + + context.report({ + node, + loc: { start: token.loc.end, end: nextToken.loc.start }, + messageId: "unexpectedSpaceAfter", + data: { + tokenValue: token.value, + }, + fix(fixer) { + return fixer.removeRange([ + token.range[1], + nextToken.range[0], + ]); + }, + }); + } + + /** + * Reports that there shouldn't be a space before the last token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportNoEndingSpace(node, token) { + const previousToken = sourceCode.getTokenBefore(token); + + context.report({ + node, + loc: { start: previousToken.loc.end, end: token.loc.start }, + messageId: "unexpectedSpaceBefore", + data: { + tokenValue: token.value, + }, + fix(fixer) { + return fixer.removeRange([ + previousToken.range[1], + token.range[0], + ]); + }, + }); + } + + /** + * Reports that there should be a space after the first token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportRequiredBeginningSpace(node, token) { + context.report({ + node, + loc: token.loc, + messageId: "missingSpaceAfter", + data: { + tokenValue: token.value, + }, + fix(fixer) { + return fixer.insertTextAfter(token, " "); + }, + }); + } + + /** + * Reports that there should be a space before the last token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportRequiredEndingSpace(node, token) { + context.report({ + node, + loc: token.loc, + messageId: "missingSpaceBefore", + data: { + tokenValue: token.value, + }, + fix(fixer) { + return fixer.insertTextBefore(token, " "); + }, + }); + } + + /** + * Determines if a node is an object type + * @param {ASTNode} node The node to check. + * @returns {boolean} Whether or not the node is an object type. + */ + function isObjectType(node) { + return ( + node && + (node.type === "ObjectExpression" || + node.type === "ObjectPattern") + ); + } + + /** + * Determines if a node is an array type + * @param {ASTNode} node The node to check. + * @returns {boolean} Whether or not the node is an array type. + */ + function isArrayType(node) { + return ( + node && + (node.type === "ArrayExpression" || + node.type === "ArrayPattern") + ); + } + + /** + * Validates the spacing around array brackets + * @param {ASTNode} node The node we're checking for spacing + * @returns {void} + */ + function validateArraySpacing(node) { + if (options.spaced && node.elements.length === 0) { + return; + } + + const first = sourceCode.getFirstToken(node), + second = sourceCode.getFirstToken(node, 1), + last = node.typeAnnotation + ? sourceCode.getTokenBefore(node.typeAnnotation) + : sourceCode.getLastToken(node), + penultimate = sourceCode.getTokenBefore(last), + firstElement = node.elements[0], + lastElement = node.elements.at(-1); + + const openingBracketMustBeSpaced = + (options.objectsInArraysException && + isObjectType(firstElement)) || + (options.arraysInArraysException && + isArrayType(firstElement)) || + (options.singleElementException && node.elements.length === 1) + ? !options.spaced + : options.spaced; + + const closingBracketMustBeSpaced = + (options.objectsInArraysException && + isObjectType(lastElement)) || + (options.arraysInArraysException && isArrayType(lastElement)) || + (options.singleElementException && node.elements.length === 1) + ? !options.spaced + : options.spaced; + + if (astUtils.isTokenOnSameLine(first, second)) { + if ( + openingBracketMustBeSpaced && + !sourceCode.isSpaceBetweenTokens(first, second) + ) { + reportRequiredBeginningSpace(node, first); + } + if ( + !openingBracketMustBeSpaced && + sourceCode.isSpaceBetweenTokens(first, second) + ) { + reportNoBeginningSpace(node, first); + } + } + + if ( + first !== penultimate && + astUtils.isTokenOnSameLine(penultimate, last) + ) { + if ( + closingBracketMustBeSpaced && + !sourceCode.isSpaceBetweenTokens(penultimate, last) + ) { + reportRequiredEndingSpace(node, last); + } + if ( + !closingBracketMustBeSpaced && + sourceCode.isSpaceBetweenTokens(penultimate, last) + ) { + reportNoEndingSpace(node, last); + } + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + ArrayPattern: validateArraySpacing, + ArrayExpression: validateArraySpacing, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/array-callback-return.js b/tools/ui/node_modules/eslint/lib/rules/array-callback-return.js new file mode 100644 index 0000000000000000000000000000000000000000..e7e31308f19f0ac145ce89cdcf26f3917e9bbeb5 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/array-callback-return.js @@ -0,0 +1,493 @@ +/** + * @fileoverview Rule to enforce return statements in callbacks of array's methods + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const TARGET_NODE_TYPE = /^(?:Arrow)?FunctionExpression$/u; +const TARGET_METHODS = + /^(?:every|filter|find(?:Last)?(?:Index)?|flatMap|forEach|map|reduce(?:Right)?|some|sort|toSorted)$/u; + +/** + * Checks a given node is a member access which has the specified name's + * property. + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is a member access which has + * the specified name's property. The node may be a `(Chain|Member)Expression` node. + */ +function isTargetMethod(node) { + return astUtils.isSpecificMemberAccess(node, null, TARGET_METHODS); +} + +/** + * Checks all segments in a set and returns true if any are reachable. + * @param {Set} segments The segments to check. + * @returns {boolean} True if any segment is reachable; false otherwise. + */ +function isAnySegmentReachable(segments) { + for (const segment of segments) { + if (segment.reachable) { + return true; + } + } + + return false; +} + +/** + * Returns a human-legible description of an array method + * @param {string} arrayMethodName A method name to fully qualify + * @returns {string} the method name prefixed with `Array.` if it is a class method, + * or else `Array.prototype.` if it is an instance method. + */ +function fullMethodName(arrayMethodName) { + if (["from", "of", "isArray"].includes(arrayMethodName)) { + return "Array.".concat(arrayMethodName); + } + return "Array.prototype.".concat(arrayMethodName); +} + +/** + * Checks whether or not a given node is a function expression which is the + * callback of an array method, returning the method name. + * @param {ASTNode} node A node to check. This is one of + * FunctionExpression or ArrowFunctionExpression. + * @returns {string} The method name if the node is a callback method, + * null otherwise. + */ +function getArrayMethodName(node) { + let currentNode = node; + + while (currentNode) { + const parent = currentNode.parent; + + switch (parent.type) { + /* + * Looks up the destination. e.g., + * foo.every(nativeFoo || function foo() { ... }); + */ + case "LogicalExpression": + case "ConditionalExpression": + case "ChainExpression": + currentNode = parent; + break; + + /* + * If the upper function is IIFE, checks the destination of the return value. + * e.g. + * foo.every((function() { + * // setup... + * return function callback() { ... }; + * })()); + */ + case "ReturnStatement": { + const func = astUtils.getUpperFunction(parent); + + if (func === null || !astUtils.isCallee(func)) { + return null; + } + currentNode = func.parent; + break; + } + + /* + * e.g. + * Array.from([], function() {}); + * list.every(function() {}); + */ + case "CallExpression": + if (astUtils.isArrayFromMethod(parent.callee)) { + if ( + parent.arguments.length >= 2 && + parent.arguments[1] === currentNode + ) { + return "from"; + } + } + if (isTargetMethod(parent.callee)) { + if ( + parent.arguments.length >= 1 && + parent.arguments[0] === currentNode + ) { + return astUtils.getStaticPropertyName(parent.callee); + } + } + return null; + + // Otherwise this node is not target. + default: + return null; + } + } + + /* c8 ignore next */ + return null; +} + +/** + * Checks if the given node is a void expression. + * @param {ASTNode} node The node to check. + * @returns {boolean} - `true` if the node is a void expression + */ +function isExpressionVoid(node) { + return node.type === "UnaryExpression" && node.operator === "void"; +} + +/** + * Fixes the linting error by prepending "void " to the given node + * @param {Object} sourceCode context given by context.sourceCode + * @param {ASTNode} node The node to fix. + * @param {Object} fixer The fixer object provided by ESLint. + * @returns {Array} - An array of fix objects to apply to the node. + */ +function voidPrependFixer(sourceCode, node, fixer) { + const requiresParens = + // prepending `void ` will fail if the node has a lower precedence than void + astUtils.getPrecedence(node) < + astUtils.getPrecedence({ + type: "UnaryExpression", + operator: "void", + }) && + // check if there are parentheses around the node to avoid redundant parentheses + !astUtils.isParenthesised(sourceCode, node); + + // avoid parentheses issues + const returnOrArrowToken = sourceCode.getTokenBefore( + node, + node.parent.type === "ArrowFunctionExpression" + ? astUtils.isArrowToken + : // isReturnToken + token => token.type === "Keyword" && token.value === "return", + ); + + const firstToken = sourceCode.getTokenAfter(returnOrArrowToken); + + const prependSpace = + // is return token, as => allows void to be adjacent + returnOrArrowToken.value === "return" && + // If two tokens (return and "(") are adjacent + returnOrArrowToken.range[1] === firstToken.range[0]; + + return [ + fixer.insertTextBefore( + firstToken, + `${prependSpace ? " " : ""}void ${requiresParens ? "(" : ""}`, + ), + fixer.insertTextAfter(node, requiresParens ? ")" : ""), + ]; +} + +/** + * Fixes the linting error by `wrapping {}` around the given node's body. + * @param {Object} sourceCode context given by context.sourceCode + * @param {ASTNode} node The node to fix. + * @param {Object} fixer The fixer object provided by ESLint. + * @returns {Array} - An array of fix objects to apply to the node. + */ +function curlyWrapFixer(sourceCode, node, fixer) { + const arrowToken = sourceCode.getTokenBefore( + node.body, + astUtils.isArrowToken, + ); + const firstToken = sourceCode.getTokenAfter(arrowToken); + const lastToken = sourceCode.getLastToken(node); + + return [ + fixer.insertTextBefore(firstToken, "{"), + fixer.insertTextAfter(lastToken, "}"), + ]; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: [ + { + allowImplicit: false, + checkForEach: false, + allowVoid: false, + }, + ], + + docs: { + description: + "Enforce `return` statements in callbacks of array methods", + recommended: false, + url: "https://eslint.org/docs/latest/rules/array-callback-return", + }, + + hasSuggestions: true, + + schema: [ + { + type: "object", + properties: { + allowImplicit: { + type: "boolean", + }, + checkForEach: { + type: "boolean", + }, + allowVoid: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + expectedAtEnd: + "{{arrayMethodName}}() expects a value to be returned at the end of {{name}}.", + expectedInside: + "{{arrayMethodName}}() expects a return value from {{name}}.", + expectedReturnValue: + "{{arrayMethodName}}() expects a return value from {{name}}.", + expectedNoReturnValue: + "{{arrayMethodName}}() expects no useless return value from {{name}}.", + wrapBraces: "Wrap the expression in `{}`.", + prependVoid: "Prepend `void` to the expression.", + }, + }, + + create(context) { + const [options] = context.options; + const sourceCode = context.sourceCode; + + let funcInfo = { + arrayMethodName: null, + upper: null, + codePath: null, + hasReturn: false, + shouldCheck: false, + node: null, + }; + + /** + * Checks whether or not the last code path segment is reachable. + * Then reports this function if the segment is reachable. + * + * If the last code path segment is reachable, there are paths which are not + * returned or thrown. + * @param {ASTNode} node A node to check. + * @returns {void} + */ + function checkLastSegment(node) { + if (!funcInfo.shouldCheck) { + return; + } + + const messageAndSuggestions = { messageId: "", suggest: [] }; + + if (funcInfo.arrayMethodName === "forEach") { + if ( + options.checkForEach && + node.type === "ArrowFunctionExpression" && + node.expression + ) { + if (options.allowVoid) { + if (isExpressionVoid(node.body)) { + return; + } + + messageAndSuggestions.messageId = + "expectedNoReturnValue"; + messageAndSuggestions.suggest = [ + { + messageId: "wrapBraces", + fix(fixer) { + return curlyWrapFixer( + sourceCode, + node, + fixer, + ); + }, + }, + { + messageId: "prependVoid", + fix(fixer) { + return voidPrependFixer( + sourceCode, + node.body, + fixer, + ); + }, + }, + ]; + } else { + messageAndSuggestions.messageId = + "expectedNoReturnValue"; + messageAndSuggestions.suggest = [ + { + messageId: "wrapBraces", + fix(fixer) { + return curlyWrapFixer( + sourceCode, + node, + fixer, + ); + }, + }, + ]; + } + } + } else { + if ( + node.body.type === "BlockStatement" && + isAnySegmentReachable(funcInfo.currentSegments) + ) { + messageAndSuggestions.messageId = funcInfo.hasReturn + ? "expectedAtEnd" + : "expectedInside"; + } + } + + if (messageAndSuggestions.messageId) { + const name = astUtils.getFunctionNameWithKind(node); + + context.report({ + node, + loc: astUtils.getFunctionHeadLoc(node, sourceCode), + messageId: messageAndSuggestions.messageId, + data: { + name, + arrayMethodName: fullMethodName( + funcInfo.arrayMethodName, + ), + }, + suggest: + messageAndSuggestions.suggest.length !== 0 + ? messageAndSuggestions.suggest + : null, + }); + } + } + + return { + // Stacks this function's information. + onCodePathStart(codePath, node) { + let methodName = null; + + if (TARGET_NODE_TYPE.test(node.type)) { + methodName = getArrayMethodName(node); + } + + funcInfo = { + arrayMethodName: methodName, + upper: funcInfo, + codePath, + hasReturn: false, + shouldCheck: methodName && !node.async && !node.generator, + node, + currentSegments: new Set(), + }; + }, + + // Pops this function's information. + onCodePathEnd() { + funcInfo = funcInfo.upper; + }, + + onUnreachableCodePathSegmentStart(segment) { + funcInfo.currentSegments.add(segment); + }, + + onUnreachableCodePathSegmentEnd(segment) { + funcInfo.currentSegments.delete(segment); + }, + + onCodePathSegmentStart(segment) { + funcInfo.currentSegments.add(segment); + }, + + onCodePathSegmentEnd(segment) { + funcInfo.currentSegments.delete(segment); + }, + + // Checks the return statement is valid. + ReturnStatement(node) { + if (!funcInfo.shouldCheck) { + return; + } + + funcInfo.hasReturn = true; + + const messageAndSuggestions = { messageId: "", suggest: [] }; + + if (funcInfo.arrayMethodName === "forEach") { + // if checkForEach: true, returning a value at any path inside a forEach is not allowed + if (options.checkForEach && node.argument) { + if (options.allowVoid) { + if (isExpressionVoid(node.argument)) { + return; + } + + messageAndSuggestions.messageId = + "expectedNoReturnValue"; + messageAndSuggestions.suggest = [ + { + messageId: "prependVoid", + fix(fixer) { + return voidPrependFixer( + sourceCode, + node.argument, + fixer, + ); + }, + }, + ]; + } else { + messageAndSuggestions.messageId = + "expectedNoReturnValue"; + } + } + } else { + // if allowImplicit: false, should also check node.argument + if (!options.allowImplicit && !node.argument) { + messageAndSuggestions.messageId = "expectedReturnValue"; + } + } + + if (messageAndSuggestions.messageId) { + context.report({ + node, + messageId: messageAndSuggestions.messageId, + data: { + name: astUtils.getFunctionNameWithKind( + funcInfo.node, + ), + arrayMethodName: fullMethodName( + funcInfo.arrayMethodName, + ), + }, + suggest: + messageAndSuggestions.suggest.length !== 0 + ? messageAndSuggestions.suggest + : null, + }); + } + }, + + // Reports a given function if the last path is reachable. + "FunctionExpression:exit": checkLastSegment, + "ArrowFunctionExpression:exit": checkLastSegment, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/array-element-newline.js b/tools/ui/node_modules/eslint/lib/rules/array-element-newline.js new file mode 100644 index 0000000000000000000000000000000000000000..d687cba01a827ca0eff122ef51c9921bd6bfd36c --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/array-element-newline.js @@ -0,0 +1,374 @@ +/** + * @fileoverview Rule to enforce line breaks after each array element + * @author Jan Peer Stöcklmair + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "array-element-newline", + url: "https://eslint.style/rules/array-element-newline", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce line breaks after each array element", + recommended: false, + url: "https://eslint.org/docs/latest/rules/array-element-newline", + }, + + fixable: "whitespace", + + schema: { + definitions: { + basicConfig: { + oneOf: [ + { + enum: ["always", "never", "consistent"], + }, + { + type: "object", + properties: { + multiline: { + type: "boolean", + }, + minItems: { + type: ["integer", "null"], + minimum: 0, + }, + }, + additionalProperties: false, + }, + ], + }, + }, + type: "array", + items: [ + { + oneOf: [ + { + $ref: "#/definitions/basicConfig", + }, + { + type: "object", + properties: { + ArrayExpression: { + $ref: "#/definitions/basicConfig", + }, + ArrayPattern: { + $ref: "#/definitions/basicConfig", + }, + }, + additionalProperties: false, + minProperties: 1, + }, + ], + }, + ], + }, + + messages: { + unexpectedLineBreak: "There should be no linebreak here.", + missingLineBreak: "There should be a linebreak after this element.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + //---------------------------------------------------------------------- + // Helpers + //---------------------------------------------------------------------- + + /** + * Normalizes a given option value. + * @param {string|Object|undefined} providedOption An option value to parse. + * @returns {{multiline: boolean, minItems: number}} Normalized option object. + */ + function normalizeOptionValue(providedOption) { + let consistent = false; + let multiline = false; + let minItems; + + const option = providedOption || "always"; + + if (!option || option === "always" || option.minItems === 0) { + minItems = 0; + } else if (option === "never") { + minItems = Number.POSITIVE_INFINITY; + } else if (option === "consistent") { + consistent = true; + minItems = Number.POSITIVE_INFINITY; + } else { + multiline = Boolean(option.multiline); + minItems = option.minItems || Number.POSITIVE_INFINITY; + } + + return { consistent, multiline, minItems }; + } + + /** + * Normalizes a given option value. + * @param {string|Object|undefined} options An option value to parse. + * @returns {{ArrayExpression: {multiline: boolean, minItems: number}, ArrayPattern: {multiline: boolean, minItems: number}}} Normalized option object. + */ + function normalizeOptions(options) { + if (options && (options.ArrayExpression || options.ArrayPattern)) { + let expressionOptions, patternOptions; + + if (options.ArrayExpression) { + expressionOptions = normalizeOptionValue( + options.ArrayExpression, + ); + } + + if (options.ArrayPattern) { + patternOptions = normalizeOptionValue(options.ArrayPattern); + } + + return { + ArrayExpression: expressionOptions, + ArrayPattern: patternOptions, + }; + } + + const value = normalizeOptionValue(options); + + return { ArrayExpression: value, ArrayPattern: value }; + } + + /** + * Reports that there shouldn't be a line break after the first token + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportNoLineBreak(token) { + const tokenBefore = sourceCode.getTokenBefore(token, { + includeComments: true, + }); + + context.report({ + loc: { + start: tokenBefore.loc.end, + end: token.loc.start, + }, + messageId: "unexpectedLineBreak", + fix(fixer) { + if (astUtils.isCommentToken(tokenBefore)) { + return null; + } + + if (!astUtils.isTokenOnSameLine(tokenBefore, token)) { + return fixer.replaceTextRange( + [tokenBefore.range[1], token.range[0]], + " ", + ); + } + + /* + * This will check if the comma is on the same line as the next element + * Following array: + * [ + * 1 + * , 2 + * , 3 + * ] + * + * will be fixed to: + * [ + * 1, 2, 3 + * ] + */ + const twoTokensBefore = sourceCode.getTokenBefore( + tokenBefore, + { includeComments: true }, + ); + + if (astUtils.isCommentToken(twoTokensBefore)) { + return null; + } + + return fixer.replaceTextRange( + [twoTokensBefore.range[1], tokenBefore.range[0]], + "", + ); + }, + }); + } + + /** + * Reports that there should be a line break after the first token + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportRequiredLineBreak(token) { + const tokenBefore = sourceCode.getTokenBefore(token, { + includeComments: true, + }); + + context.report({ + loc: { + start: tokenBefore.loc.end, + end: token.loc.start, + }, + messageId: "missingLineBreak", + fix(fixer) { + return fixer.replaceTextRange( + [tokenBefore.range[1], token.range[0]], + "\n", + ); + }, + }); + } + + /** + * Reports a given node if it violated this rule. + * @param {ASTNode} node A node to check. This is an ObjectExpression node or an ObjectPattern node. + * @returns {void} + */ + function check(node) { + const elements = node.elements; + const normalizedOptions = normalizeOptions(context.options[0]); + const options = normalizedOptions[node.type]; + + if (!options) { + return; + } + + let elementBreak = false; + + /* + * MULTILINE: true + * loop through every element and check + * if at least one element has linebreaks inside + * this ensures that following is not valid (due to elements are on the same line): + * + * [ + * 1, + * 2, + * 3 + * ] + */ + if (options.multiline) { + elementBreak = elements + .filter(element => element !== null) + .some( + element => + element.loc.start.line !== element.loc.end.line, + ); + } + + let linebreaksCount = 0; + + for (let i = 0; i < node.elements.length; i++) { + const element = node.elements[i]; + + const previousElement = elements[i - 1]; + + if (i === 0 || element === null || previousElement === null) { + continue; + } + + const commaToken = sourceCode.getFirstTokenBetween( + previousElement, + element, + astUtils.isCommaToken, + ); + const lastTokenOfPreviousElement = + sourceCode.getTokenBefore(commaToken); + const firstTokenOfCurrentElement = + sourceCode.getTokenAfter(commaToken); + + if ( + !astUtils.isTokenOnSameLine( + lastTokenOfPreviousElement, + firstTokenOfCurrentElement, + ) + ) { + linebreaksCount++; + } + } + + const needsLinebreaks = + elements.length >= options.minItems || + (options.multiline && elementBreak) || + (options.consistent && + linebreaksCount > 0 && + linebreaksCount < node.elements.length); + + elements.forEach((element, i) => { + const previousElement = elements[i - 1]; + + if (i === 0 || element === null || previousElement === null) { + return; + } + + const commaToken = sourceCode.getFirstTokenBetween( + previousElement, + element, + astUtils.isCommaToken, + ); + const lastTokenOfPreviousElement = + sourceCode.getTokenBefore(commaToken); + const firstTokenOfCurrentElement = + sourceCode.getTokenAfter(commaToken); + + if (needsLinebreaks) { + if ( + astUtils.isTokenOnSameLine( + lastTokenOfPreviousElement, + firstTokenOfCurrentElement, + ) + ) { + reportRequiredLineBreak(firstTokenOfCurrentElement); + } + } else { + if ( + !astUtils.isTokenOnSameLine( + lastTokenOfPreviousElement, + firstTokenOfCurrentElement, + ) + ) { + reportNoLineBreak(firstTokenOfCurrentElement); + } + } + }); + } + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + + return { + ArrayPattern: check, + ArrayExpression: check, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/arrow-body-style.js b/tools/ui/node_modules/eslint/lib/rules/arrow-body-style.js new file mode 100644 index 0000000000000000000000000000000000000000..8272317b5b0fb805002f70354628c662383c10b9 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/arrow-body-style.js @@ -0,0 +1,418 @@ +/** + * @fileoverview Rule to require braces in arrow function body. + * @author Alberto Rodríguez + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: ["as-needed"], + + docs: { + description: "Require braces around arrow function bodies", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/arrow-body-style", + }, + + schema: { + anyOf: [ + { + type: "array", + items: [ + { + enum: ["always", "never"], + }, + ], + minItems: 0, + maxItems: 1, + }, + { + type: "array", + items: [ + { + enum: ["as-needed"], + }, + { + type: "object", + properties: { + requireReturnForObjectLiteral: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + minItems: 0, + maxItems: 2, + }, + ], + }, + + fixable: "code", + + messages: { + unexpectedOtherBlock: + "Unexpected block statement surrounding arrow body.", + unexpectedEmptyBlock: + "Unexpected block statement surrounding arrow body; put a value of `undefined` immediately after the `=>`.", + unexpectedObjectBlock: + "Unexpected block statement surrounding arrow body; parenthesize the returned value and move it immediately after the `=>`.", + unexpectedSingleBlock: + "Unexpected block statement surrounding arrow body; move the returned value immediately after the `=>`.", + expectedBlock: "Expected block statement surrounding arrow body.", + }, + }, + + create(context) { + const options = context.options; + const always = options[0] === "always"; + const asNeeded = options[0] === "as-needed"; + const never = options[0] === "never"; + const requireReturnForObjectLiteral = + options[1] && options[1].requireReturnForObjectLiteral; + const sourceCode = context.sourceCode; + let funcInfo = null; + + /** + * Checks whether the given node has ASI problem or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if it changes semantics if `;` or `}` followed by the token are removed. + */ + function hasASIProblem(token) { + return ( + token && + token.type === "Punctuator" && + /^[([/`+-]/u.test(token.value) + ); + } + + /** + * Gets the closing parenthesis by the given node. + * @param {ASTNode} node first node after an opening parenthesis. + * @returns {Token} The found closing parenthesis token. + */ + function findClosingParen(node) { + let nodeToCheck = node; + + while (!astUtils.isParenthesised(sourceCode, nodeToCheck)) { + nodeToCheck = nodeToCheck.parent; + } + return sourceCode.getTokenAfter(nodeToCheck); + } + + /** + * Check whether the node is inside of a for loop's init + * @param {ASTNode} node node is inside for loop + * @returns {boolean} `true` if the node is inside of a for loop, else `false` + */ + function isInsideForLoopInitializer(node) { + if (node && node.parent) { + if ( + node.parent.type === "ForStatement" && + node.parent.init === node + ) { + return true; + } + return isInsideForLoopInitializer(node.parent); + } + return false; + } + + /** + * Determines whether a arrow function body needs braces + * @param {ASTNode} node The arrow function node. + * @returns {void} + */ + function validate(node) { + const arrowBody = node.body; + + if (arrowBody.type === "BlockStatement") { + const blockBody = arrowBody.body; + + if (blockBody.length !== 1 && !never) { + return; + } + + if ( + asNeeded && + requireReturnForObjectLiteral && + blockBody[0].type === "ReturnStatement" && + blockBody[0].argument && + blockBody[0].argument.type === "ObjectExpression" + ) { + return; + } + + if ( + never || + (asNeeded && blockBody[0].type === "ReturnStatement") + ) { + let messageId; + + if (blockBody.length === 0) { + messageId = "unexpectedEmptyBlock"; + } else if ( + blockBody.length > 1 || + blockBody[0].type !== "ReturnStatement" + ) { + messageId = "unexpectedOtherBlock"; + } else if (blockBody[0].argument === null) { + messageId = "unexpectedSingleBlock"; + } else if ( + astUtils.isOpeningBraceToken( + sourceCode.getFirstToken(blockBody[0], { skip: 1 }), + ) + ) { + messageId = "unexpectedObjectBlock"; + } else { + messageId = "unexpectedSingleBlock"; + } + + context.report({ + node, + loc: arrowBody.loc, + messageId, + fix(fixer) { + const fixes = []; + + if ( + blockBody.length !== 1 || + blockBody[0].type !== "ReturnStatement" || + !blockBody[0].argument || + hasASIProblem( + sourceCode.getTokenAfter(arrowBody), + ) + ) { + return fixes; + } + + const openingBrace = + sourceCode.getFirstToken(arrowBody); + const closingBrace = + sourceCode.getLastToken(arrowBody); + const firstValueToken = sourceCode.getFirstToken( + blockBody[0], + 1, + ); + const lastValueToken = sourceCode.getLastToken( + blockBody[0], + ); + const commentsExist = + sourceCode.commentsExistBetween( + openingBrace, + firstValueToken, + ) || + sourceCode.commentsExistBetween( + lastValueToken, + closingBrace, + ); + + /* + * Remove tokens around the return value. + * If comments don't exist, remove extra spaces as well. + */ + if (commentsExist) { + fixes.push( + fixer.remove(openingBrace), + fixer.remove(closingBrace), + fixer.remove( + sourceCode.getTokenAfter(openingBrace), + ), // return keyword + ); + } else { + fixes.push( + fixer.removeRange([ + openingBrace.range[0], + firstValueToken.range[0], + ]), + fixer.removeRange([ + lastValueToken.range[1], + closingBrace.range[1], + ]), + ); + } + + /* + * If the first token of the return value is `{` or the return value is a sequence expression, + * enclose the return value by parentheses to avoid syntax error. + */ + if ( + astUtils.isOpeningBraceToken(firstValueToken) || + blockBody[0].argument.type === + "SequenceExpression" || + (funcInfo.hasInOperator && + isInsideForLoopInitializer(node)) + ) { + if ( + !astUtils.isParenthesised( + sourceCode, + blockBody[0].argument, + ) + ) { + fixes.push( + fixer.insertTextBefore( + firstValueToken, + "(", + ), + fixer.insertTextAfter( + lastValueToken, + ")", + ), + ); + } + } + + /* + * If the last token of the return statement is semicolon, remove it. + * Non-block arrow body is an expression, not a statement. + */ + if (astUtils.isSemicolonToken(lastValueToken)) { + fixes.push(fixer.remove(lastValueToken)); + } + + return fixes; + }, + }); + } + } else { + if ( + always || + (asNeeded && + requireReturnForObjectLiteral && + arrowBody.type === "ObjectExpression") + ) { + context.report({ + node, + loc: arrowBody.loc, + messageId: "expectedBlock", + fix(fixer) { + const fixes = []; + const arrowToken = sourceCode.getTokenBefore( + arrowBody, + astUtils.isArrowToken, + ); + const [ + firstTokenAfterArrow, + secondTokenAfterArrow, + ] = sourceCode.getTokensAfter(arrowToken, { + count: 2, + }); + const lastToken = sourceCode.getLastToken(node); + + let parenthesisedObjectLiteral = null; + + if ( + astUtils.isOpeningParenToken( + firstTokenAfterArrow, + ) && + astUtils.isOpeningBraceToken( + secondTokenAfterArrow, + ) + ) { + const braceNode = + sourceCode.getNodeByRangeIndex( + secondTokenAfterArrow.range[0], + ); + + if (braceNode.type === "ObjectExpression") { + parenthesisedObjectLiteral = braceNode; + } + } + + // If the value is object literal, remove parentheses which were forced by syntax. + if (parenthesisedObjectLiteral) { + const openingParenToken = firstTokenAfterArrow; + const openingBraceToken = secondTokenAfterArrow; + + if ( + astUtils.isTokenOnSameLine( + openingParenToken, + openingBraceToken, + ) + ) { + fixes.push( + fixer.replaceText( + openingParenToken, + "{return ", + ), + ); + } else { + // Avoid ASI + fixes.push( + fixer.replaceText( + openingParenToken, + "{", + ), + fixer.insertTextBefore( + openingBraceToken, + "return ", + ), + ); + } + + // Closing paren for the object doesn't have to be lastToken, e.g.: () => ({}).foo() + fixes.push( + fixer.remove( + findClosingParen( + parenthesisedObjectLiteral, + ), + ), + ); + fixes.push( + fixer.insertTextAfter(lastToken, "}"), + ); + } else { + fixes.push( + fixer.insertTextBefore( + firstTokenAfterArrow, + "{return ", + ), + ); + fixes.push( + fixer.insertTextAfter(lastToken, "}"), + ); + } + + return fixes; + }, + }); + } + } + } + + return { + "BinaryExpression[operator='in']"() { + let info = funcInfo; + + while (info) { + info.hasInOperator = true; + info = info.upper; + } + }, + ArrowFunctionExpression() { + funcInfo = { + upper: funcInfo, + hasInOperator: false, + }; + }, + "ArrowFunctionExpression:exit"(node) { + validate(node); + funcInfo = funcInfo.upper; + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/arrow-parens.js b/tools/ui/node_modules/eslint/lib/rules/arrow-parens.js new file mode 100644 index 0000000000000000000000000000000000000000..bbb3d335380844359a407e1338aecb941fcafb76 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/arrow-parens.js @@ -0,0 +1,237 @@ +/** + * @fileoverview Rule to require parens in arrow function arguments. + * @author Jxck + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Determines if the given arrow function has block body. + * @param {ASTNode} node `ArrowFunctionExpression` node. + * @returns {boolean} `true` if the function has block body. + */ +function hasBlockBody(node) { + return node.body.type === "BlockStatement"; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "arrow-parens", + url: "https://eslint.style/rules/arrow-parens", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Require parentheses around arrow function arguments", + recommended: false, + url: "https://eslint.org/docs/latest/rules/arrow-parens", + }, + + fixable: "code", + + schema: [ + { + enum: ["always", "as-needed"], + }, + { + type: "object", + properties: { + requireForBlockBody: { + type: "boolean", + default: false, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpectedParens: + "Unexpected parentheses around single function argument.", + expectedParens: + "Expected parentheses around arrow function argument.", + + unexpectedParensInline: + "Unexpected parentheses around single function argument having a body with no curly braces.", + expectedParensBlock: + "Expected parentheses around arrow function argument having a body with curly braces.", + }, + }, + + create(context) { + const asNeeded = context.options[0] === "as-needed"; + const requireForBlockBody = + asNeeded && + context.options[1] && + context.options[1].requireForBlockBody === true; + + const sourceCode = context.sourceCode; + + /** + * Finds opening paren of parameters for the given arrow function, if it exists. + * It is assumed that the given arrow function has exactly one parameter. + * @param {ASTNode} node `ArrowFunctionExpression` node. + * @returns {Token|null} the opening paren, or `null` if the given arrow function doesn't have parens of parameters. + */ + function findOpeningParenOfParams(node) { + const tokenBeforeParams = sourceCode.getTokenBefore(node.params[0]); + + if ( + tokenBeforeParams && + astUtils.isOpeningParenToken(tokenBeforeParams) && + node.range[0] <= tokenBeforeParams.range[0] + ) { + return tokenBeforeParams; + } + + return null; + } + + /** + * Finds closing paren of parameters for the given arrow function. + * It is assumed that the given arrow function has parens of parameters and that it has exactly one parameter. + * @param {ASTNode} node `ArrowFunctionExpression` node. + * @returns {Token} the closing paren of parameters. + */ + function getClosingParenOfParams(node) { + return sourceCode.getTokenAfter( + node.params[0], + astUtils.isClosingParenToken, + ); + } + + /** + * Determines whether the given arrow function has comments inside parens of parameters. + * It is assumed that the given arrow function has parens of parameters. + * @param {ASTNode} node `ArrowFunctionExpression` node. + * @param {Token} openingParen Opening paren of parameters. + * @returns {boolean} `true` if the function has at least one comment inside of parens of parameters. + */ + function hasCommentsInParensOfParams(node, openingParen) { + return sourceCode.commentsExistBetween( + openingParen, + getClosingParenOfParams(node), + ); + } + + /** + * Determines whether the given arrow function has unexpected tokens before opening paren of parameters, + * in which case it will be assumed that the existing parens of parameters are necessary. + * Only tokens within the range of the arrow function (tokens that are part of the arrow function) are taken into account. + * Example: (a) => b + * @param {ASTNode} node `ArrowFunctionExpression` node. + * @param {Token} openingParen Opening paren of parameters. + * @returns {boolean} `true` if the function has at least one unexpected token. + */ + function hasUnexpectedTokensBeforeOpeningParen(node, openingParen) { + const expectedCount = node.async ? 1 : 0; + + return ( + sourceCode.getFirstToken(node, { skip: expectedCount }) !== + openingParen + ); + } + + return { + "ArrowFunctionExpression[params.length=1]"(node) { + const shouldHaveParens = + !asNeeded || (requireForBlockBody && hasBlockBody(node)); + const openingParen = findOpeningParenOfParams(node); + const hasParens = openingParen !== null; + const [param] = node.params; + + if (shouldHaveParens && !hasParens) { + context.report({ + node, + messageId: requireForBlockBody + ? "expectedParensBlock" + : "expectedParens", + loc: param.loc, + *fix(fixer) { + yield fixer.insertTextBefore(param, "("); + yield fixer.insertTextAfter(param, ")"); + }, + }); + } + + if ( + !shouldHaveParens && + hasParens && + param.type === "Identifier" && + !param.typeAnnotation && + !node.returnType && + !hasCommentsInParensOfParams(node, openingParen) && + !hasUnexpectedTokensBeforeOpeningParen(node, openingParen) + ) { + context.report({ + node, + messageId: requireForBlockBody + ? "unexpectedParensInline" + : "unexpectedParens", + loc: param.loc, + *fix(fixer) { + const tokenBeforeOpeningParen = + sourceCode.getTokenBefore(openingParen); + const closingParen = getClosingParenOfParams(node); + + if ( + tokenBeforeOpeningParen && + tokenBeforeOpeningParen.range[1] === + openingParen.range[0] && + !astUtils.canTokensBeAdjacent( + tokenBeforeOpeningParen, + sourceCode.getFirstToken(param), + ) + ) { + yield fixer.insertTextBefore(openingParen, " "); + } + + // remove parens, whitespace inside parens, and possible trailing comma + yield fixer.removeRange([ + openingParen.range[0], + param.range[0], + ]); + yield fixer.removeRange([ + param.range[1], + closingParen.range[1], + ]); + }, + }); + } + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/arrow-spacing.js b/tools/ui/node_modules/eslint/lib/rules/arrow-spacing.js new file mode 100644 index 0000000000000000000000000000000000000000..21b20531e667189622ed6f6cf4acd516e5f94be4 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/arrow-spacing.js @@ -0,0 +1,188 @@ +/** + * @fileoverview Rule to define spacing before/after arrow function's arrow. + * @author Jxck + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "arrow-spacing", + url: "https://eslint.style/rules/arrow-spacing", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Enforce consistent spacing before and after the arrow in arrow functions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/arrow-spacing", + }, + + fixable: "whitespace", + + schema: [ + { + type: "object", + properties: { + before: { + type: "boolean", + default: true, + }, + after: { + type: "boolean", + default: true, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + expectedBefore: "Missing space before =>.", + unexpectedBefore: "Unexpected space before =>.", + + expectedAfter: "Missing space after =>.", + unexpectedAfter: "Unexpected space after =>.", + }, + }, + + create(context) { + // merge rules with default + const rule = Object.assign({}, context.options[0]); + + rule.before = rule.before !== false; + rule.after = rule.after !== false; + + const sourceCode = context.sourceCode; + + /** + * Get tokens of arrow(`=>`) and before/after arrow. + * @param {ASTNode} node The arrow function node. + * @returns {Object} Tokens of arrow and before/after arrow. + */ + function getTokens(node) { + const arrow = sourceCode.getTokenBefore( + node.body, + astUtils.isArrowToken, + ); + + return { + before: sourceCode.getTokenBefore(arrow), + arrow, + after: sourceCode.getTokenAfter(arrow), + }; + } + + /** + * Count spaces before/after arrow(`=>`) token. + * @param {Object} tokens Tokens before/after arrow. + * @returns {Object} count of space before/after arrow. + */ + function countSpaces(tokens) { + const before = tokens.arrow.range[0] - tokens.before.range[1]; + const after = tokens.after.range[0] - tokens.arrow.range[1]; + + return { before, after }; + } + + /** + * Determines whether space(s) before after arrow(`=>`) is satisfy rule. + * if before/after value is `true`, there should be space(s). + * if before/after value is `false`, there should be no space. + * @param {ASTNode} node The arrow function node. + * @returns {void} + */ + function spaces(node) { + const tokens = getTokens(node); + const countSpace = countSpaces(tokens); + + if (rule.before) { + // should be space(s) before arrow + if (countSpace.before === 0) { + context.report({ + node: tokens.before, + messageId: "expectedBefore", + fix(fixer) { + return fixer.insertTextBefore(tokens.arrow, " "); + }, + }); + } + } else { + // should be no space before arrow + if (countSpace.before > 0) { + context.report({ + node: tokens.before, + messageId: "unexpectedBefore", + fix(fixer) { + return fixer.removeRange([ + tokens.before.range[1], + tokens.arrow.range[0], + ]); + }, + }); + } + } + + if (rule.after) { + // should be space(s) after arrow + if (countSpace.after === 0) { + context.report({ + node: tokens.after, + messageId: "expectedAfter", + fix(fixer) { + return fixer.insertTextAfter(tokens.arrow, " "); + }, + }); + } + } else { + // should be no space after arrow + if (countSpace.after > 0) { + context.report({ + node: tokens.after, + messageId: "unexpectedAfter", + fix(fixer) { + return fixer.removeRange([ + tokens.arrow.range[1], + tokens.after.range[0], + ]); + }, + }); + } + } + } + + return { + ArrowFunctionExpression: spaces, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/block-scoped-var.js b/tools/ui/node_modules/eslint/lib/rules/block-scoped-var.js new file mode 100644 index 0000000000000000000000000000000000000000..e79bec51f7f738c07c0db5620ccea90b0e5b8ede --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/block-scoped-var.js @@ -0,0 +1,137 @@ +/** + * @fileoverview Rule to check for "block scoped" variables by binding context + * @author Matt DuVall + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Enforce the use of variables within the scope they are defined", + recommended: false, + url: "https://eslint.org/docs/latest/rules/block-scoped-var", + }, + + schema: [], + + messages: { + outOfScope: + "'{{name}}' declared on line {{definitionLine}} column {{definitionColumn}} is used outside of binding context.", + }, + }, + + create(context) { + let stack = []; + const sourceCode = context.sourceCode; + + /** + * Makes a block scope. + * @param {ASTNode} node A node of a scope. + * @returns {void} + */ + function enterScope(node) { + stack.push(node.range); + } + + /** + * Pops the last block scope. + * @returns {void} + */ + function exitScope() { + stack.pop(); + } + + /** + * Reports a given reference. + * @param {eslint-scope.Reference} reference A reference to report. + * @param {eslint-scope.Definition} definition A definition for which to report reference. + * @returns {void} + */ + function report(reference, definition) { + const identifier = reference.identifier; + const definitionPosition = definition.name.loc.start; + + context.report({ + node: identifier, + messageId: "outOfScope", + data: { + name: identifier.name, + definitionLine: definitionPosition.line, + definitionColumn: definitionPosition.column + 1, + }, + }); + } + + /** + * Finds and reports references which are outside of valid scopes. + * @param {ASTNode} node A node to get variables. + * @returns {void} + */ + function checkForVariables(node) { + if (node.kind !== "var") { + return; + } + + // Defines a predicate to check whether or not a given reference is outside of valid scope. + const scopeRange = stack.at(-1); + + /** + * Check if a reference is out of scope + * @param {ASTNode} reference node to examine + * @returns {boolean} True is its outside the scope + * @private + */ + function isOutsideOfScope(reference) { + const idRange = reference.identifier.range; + + return idRange[0] < scopeRange[0] || idRange[1] > scopeRange[1]; + } + + // Gets declared variables, and checks its references. + const variables = sourceCode.getDeclaredVariables(node); + + for (let i = 0; i < variables.length; ++i) { + // Reports. + variables[i].references.filter(isOutsideOfScope).forEach(ref => + report( + ref, + variables[i].defs.find(def => def.parent === node), + ), + ); + } + } + + return { + Program(node) { + stack = [node.range]; + }, + + // Manages scopes. + BlockStatement: enterScope, + "BlockStatement:exit": exitScope, + ForStatement: enterScope, + "ForStatement:exit": exitScope, + ForInStatement: enterScope, + "ForInStatement:exit": exitScope, + ForOfStatement: enterScope, + "ForOfStatement:exit": exitScope, + SwitchStatement: enterScope, + "SwitchStatement:exit": exitScope, + CatchClause: enterScope, + "CatchClause:exit": exitScope, + StaticBlock: enterScope, + "StaticBlock:exit": exitScope, + + // Finds and reports references which are outside of valid scope. + VariableDeclaration: checkForVariables, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/block-spacing.js b/tools/ui/node_modules/eslint/lib/rules/block-spacing.js new file mode 100644 index 0000000000000000000000000000000000000000..009f0586e8870e019e6867cd36d847beb992a7c9 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/block-spacing.js @@ -0,0 +1,202 @@ +/** + * @fileoverview A rule to disallow or enforce spaces inside of single line blocks. + * @author Toru Nagashima + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +const util = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "block-spacing", + url: "https://eslint.style/rules/block-spacing", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Disallow or enforce spaces inside of blocks after opening block and before closing block", + recommended: false, + url: "https://eslint.org/docs/latest/rules/block-spacing", + }, + + fixable: "whitespace", + + schema: [{ enum: ["always", "never"] }], + + messages: { + missing: "Requires a space {{location}} '{{token}}'.", + extra: "Unexpected space(s) {{location}} '{{token}}'.", + }, + }, + + create(context) { + const always = context.options[0] !== "never", + messageId = always ? "missing" : "extra", + sourceCode = context.sourceCode; + + /** + * Gets the open brace token from a given node. + * @param {ASTNode} node A BlockStatement/StaticBlock/SwitchStatement node to get. + * @returns {Token} The token of the open brace. + */ + function getOpenBrace(node) { + if (node.type === "SwitchStatement") { + if (node.cases.length > 0) { + return sourceCode.getTokenBefore(node.cases[0]); + } + return sourceCode.getLastToken(node, 1); + } + + if (node.type === "StaticBlock") { + return sourceCode.getFirstToken(node, { skip: 1 }); // skip the `static` token + } + + // "BlockStatement" + return sourceCode.getFirstToken(node); + } + + /** + * Checks whether or not: + * - given tokens are on same line. + * - there is/isn't a space between given tokens. + * @param {Token} left A token to check. + * @param {Token} right The token which is next to `left`. + * @returns {boolean} + * When the option is `"always"`, `true` if there are one or more spaces between given tokens. + * When the option is `"never"`, `true` if there are not any spaces between given tokens. + * If given tokens are not on same line, it's always `true`. + */ + function isValid(left, right) { + return ( + !util.isTokenOnSameLine(left, right) || + sourceCode.isSpaceBetweenTokens(left, right) === always + ); + } + + /** + * Checks and reports invalid spacing style inside braces. + * @param {ASTNode} node A BlockStatement/StaticBlock/SwitchStatement node to check. + * @returns {void} + */ + function checkSpacingInsideBraces(node) { + // Gets braces and the first/last token of content. + const openBrace = getOpenBrace(node); + const closeBrace = sourceCode.getLastToken(node); + const firstToken = sourceCode.getTokenAfter(openBrace, { + includeComments: true, + }); + const lastToken = sourceCode.getTokenBefore(closeBrace, { + includeComments: true, + }); + + // Skip if the node is invalid or empty. + if ( + openBrace.type !== "Punctuator" || + openBrace.value !== "{" || + closeBrace.type !== "Punctuator" || + closeBrace.value !== "}" || + firstToken === closeBrace + ) { + return; + } + + // Skip line comments for option never + if (!always && firstToken.type === "Line") { + return; + } + + // Check. + if (!isValid(openBrace, firstToken)) { + let loc = openBrace.loc; + + if (messageId === "extra") { + loc = { + start: openBrace.loc.end, + end: firstToken.loc.start, + }; + } + + context.report({ + node, + loc, + messageId, + data: { + location: "after", + token: openBrace.value, + }, + fix(fixer) { + if (always) { + return fixer.insertTextBefore(firstToken, " "); + } + + return fixer.removeRange([ + openBrace.range[1], + firstToken.range[0], + ]); + }, + }); + } + if (!isValid(lastToken, closeBrace)) { + let loc = closeBrace.loc; + + if (messageId === "extra") { + loc = { + start: lastToken.loc.end, + end: closeBrace.loc.start, + }; + } + context.report({ + node, + loc, + messageId, + data: { + location: "before", + token: closeBrace.value, + }, + fix(fixer) { + if (always) { + return fixer.insertTextAfter(lastToken, " "); + } + + return fixer.removeRange([ + lastToken.range[1], + closeBrace.range[0], + ]); + }, + }); + } + } + + return { + BlockStatement: checkSpacingInsideBraces, + StaticBlock: checkSpacingInsideBraces, + SwitchStatement: checkSpacingInsideBraces, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/brace-style.js b/tools/ui/node_modules/eslint/lib/rules/brace-style.js new file mode 100644 index 0000000000000000000000000000000000000000..f4388400316ec3cd2bf5b49cbee6d4c69015b999 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/brace-style.js @@ -0,0 +1,278 @@ +/** + * @fileoverview Rule to flag block statements that do not use the one true brace style + * @author Ian Christian Myers + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "brace-style", + url: "https://eslint.style/rules/brace-style", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce consistent brace style for blocks", + recommended: false, + url: "https://eslint.org/docs/latest/rules/brace-style", + }, + + schema: [ + { + enum: ["1tbs", "stroustrup", "allman"], + }, + { + type: "object", + properties: { + allowSingleLine: { + type: "boolean", + default: false, + }, + }, + additionalProperties: false, + }, + ], + + fixable: "whitespace", + + messages: { + nextLineOpen: + "Opening curly brace does not appear on the same line as controlling statement.", + sameLineOpen: + "Opening curly brace appears on the same line as controlling statement.", + blockSameLine: + "Statement inside of curly braces should be on next line.", + nextLineClose: + "Closing curly brace does not appear on the same line as the subsequent block.", + singleLineClose: + "Closing curly brace should be on the same line as opening curly brace or on the line after the previous block.", + sameLineClose: + "Closing curly brace appears on the same line as the subsequent block.", + }, + }, + + create(context) { + const style = context.options[0] || "1tbs", + params = context.options[1] || {}, + sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Fixes a place where a newline unexpectedly appears + * @param {Token} firstToken The token before the unexpected newline + * @param {Token} secondToken The token after the unexpected newline + * @returns {Function} A fixer function to remove the newlines between the tokens + */ + function removeNewlineBetween(firstToken, secondToken) { + const textRange = [firstToken.range[1], secondToken.range[0]]; + const textBetween = sourceCode.text.slice( + textRange[0], + textRange[1], + ); + + // Don't do a fix if there is a comment between the tokens + if (textBetween.trim()) { + return null; + } + return fixer => fixer.replaceTextRange(textRange, " "); + } + + /** + * Validates a pair of curly brackets based on the user's config + * @param {Token} openingCurly The opening curly bracket + * @param {Token} closingCurly The closing curly bracket + * @returns {void} + */ + function validateCurlyPair(openingCurly, closingCurly) { + const tokenBeforeOpeningCurly = + sourceCode.getTokenBefore(openingCurly); + const tokenAfterOpeningCurly = + sourceCode.getTokenAfter(openingCurly); + const tokenBeforeClosingCurly = + sourceCode.getTokenBefore(closingCurly); + const singleLineException = + params.allowSingleLine && + astUtils.isTokenOnSameLine(openingCurly, closingCurly); + + if ( + style !== "allman" && + !astUtils.isTokenOnSameLine( + tokenBeforeOpeningCurly, + openingCurly, + ) + ) { + context.report({ + node: openingCurly, + messageId: "nextLineOpen", + fix: removeNewlineBetween( + tokenBeforeOpeningCurly, + openingCurly, + ), + }); + } + + if ( + style === "allman" && + astUtils.isTokenOnSameLine( + tokenBeforeOpeningCurly, + openingCurly, + ) && + !singleLineException + ) { + context.report({ + node: openingCurly, + messageId: "sameLineOpen", + fix: fixer => fixer.insertTextBefore(openingCurly, "\n"), + }); + } + + if ( + astUtils.isTokenOnSameLine( + openingCurly, + tokenAfterOpeningCurly, + ) && + tokenAfterOpeningCurly !== closingCurly && + !singleLineException + ) { + context.report({ + node: openingCurly, + messageId: "blockSameLine", + fix: fixer => fixer.insertTextAfter(openingCurly, "\n"), + }); + } + + if ( + tokenBeforeClosingCurly !== openingCurly && + !singleLineException && + astUtils.isTokenOnSameLine( + tokenBeforeClosingCurly, + closingCurly, + ) + ) { + context.report({ + node: closingCurly, + messageId: "singleLineClose", + fix: fixer => fixer.insertTextBefore(closingCurly, "\n"), + }); + } + } + + /** + * Validates the location of a token that appears before a keyword (e.g. a newline before `else`) + * @param {Token} curlyToken The closing curly token. This is assumed to precede a keyword token (such as `else` or `finally`). + * @returns {void} + */ + function validateCurlyBeforeKeyword(curlyToken) { + const keywordToken = sourceCode.getTokenAfter(curlyToken); + + if ( + style === "1tbs" && + !astUtils.isTokenOnSameLine(curlyToken, keywordToken) + ) { + context.report({ + node: curlyToken, + messageId: "nextLineClose", + fix: removeNewlineBetween(curlyToken, keywordToken), + }); + } + + if ( + style !== "1tbs" && + astUtils.isTokenOnSameLine(curlyToken, keywordToken) + ) { + context.report({ + node: curlyToken, + messageId: "sameLineClose", + fix: fixer => fixer.insertTextAfter(curlyToken, "\n"), + }); + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + BlockStatement(node) { + if (!astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type)) { + validateCurlyPair( + sourceCode.getFirstToken(node), + sourceCode.getLastToken(node), + ); + } + }, + StaticBlock(node) { + validateCurlyPair( + sourceCode.getFirstToken(node, { skip: 1 }), // skip the `static` token + sourceCode.getLastToken(node), + ); + }, + ClassBody(node) { + validateCurlyPair( + sourceCode.getFirstToken(node), + sourceCode.getLastToken(node), + ); + }, + SwitchStatement(node) { + const closingCurly = sourceCode.getLastToken(node); + const openingCurly = sourceCode.getTokenBefore( + node.cases.length ? node.cases[0] : closingCurly, + ); + + validateCurlyPair(openingCurly, closingCurly); + }, + IfStatement(node) { + if ( + node.consequent.type === "BlockStatement" && + node.alternate + ) { + // Handle the keyword after the `if` block (before `else`) + validateCurlyBeforeKeyword( + sourceCode.getLastToken(node.consequent), + ); + } + }, + TryStatement(node) { + // Handle the keyword after the `try` block (before `catch` or `finally`) + validateCurlyBeforeKeyword(sourceCode.getLastToken(node.block)); + + if (node.handler && node.finalizer) { + // Handle the keyword after the `catch` block (before `finally`) + validateCurlyBeforeKeyword( + sourceCode.getLastToken(node.handler.body), + ); + } + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/callback-return.js b/tools/ui/node_modules/eslint/lib/rules/callback-return.js new file mode 100644 index 0000000000000000000000000000000000000000..471ecf2618c8c44fd3d63bd0ed013343b3a7274f --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/callback-return.js @@ -0,0 +1,216 @@ +/** + * @fileoverview Enforce return after a callback. + * @author Jamund Ferguson + * @deprecated in ESLint v7.0.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Node.js rules were moved out of ESLint core.", + url: "https://eslint.org/docs/latest/use/migrating-to-7.0.0#deprecate-node-rules", + deprecatedSince: "7.0.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "eslint-plugin-n now maintains deprecated Node.js-related rules.", + plugin: { + name: "eslint-plugin-n", + url: "https://github.com/eslint-community/eslint-plugin-n", + }, + rule: { + name: "callback-return", + url: "https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/callback-return.md", + }, + }, + ], + }, + + type: "suggestion", + + docs: { + description: "Require `return` statements after callbacks", + recommended: false, + url: "https://eslint.org/docs/latest/rules/callback-return", + }, + + schema: [ + { + type: "array", + items: { type: "string" }, + }, + ], + + messages: { + missingReturn: "Expected return with your callback function.", + }, + }, + + create(context) { + const callbacks = context.options[0] || ["callback", "cb", "next"], + sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Find the closest parent matching a list of types. + * @param {ASTNode} node The node whose parents we are searching + * @param {Array} types The node types to match + * @returns {ASTNode} The matched node or undefined. + */ + function findClosestParentOfType(node, types) { + if (!node.parent) { + return null; + } + if (!types.includes(node.parent.type)) { + return findClosestParentOfType(node.parent, types); + } + return node.parent; + } + + /** + * Check to see if a node contains only identifiers + * @param {ASTNode} node The node to check + * @returns {boolean} Whether or not the node contains only identifiers + */ + function containsOnlyIdentifiers(node) { + if (node.type === "Identifier") { + return true; + } + + if (node.type === "MemberExpression") { + if (node.object.type === "Identifier") { + return true; + } + if (node.object.type === "MemberExpression") { + return containsOnlyIdentifiers(node.object); + } + } + + return false; + } + + /** + * Check to see if a CallExpression is in our callback list. + * @param {ASTNode} node The node to check against our callback names list. + * @returns {boolean} Whether or not this function matches our callback name. + */ + function isCallback(node) { + return ( + containsOnlyIdentifiers(node.callee) && + callbacks.includes(sourceCode.getText(node.callee)) + ); + } + + /** + * Determines whether or not the callback is part of a callback expression. + * @param {ASTNode} node The callback node + * @param {ASTNode} parentNode The expression node + * @returns {boolean} Whether or not this is part of a callback expression + */ + function isCallbackExpression(node, parentNode) { + // ensure the parent node exists and is an expression + if (!parentNode || parentNode.type !== "ExpressionStatement") { + return false; + } + + // cb() + if (parentNode.expression === node) { + return true; + } + + // special case for cb && cb() and similar + if ( + parentNode.expression.type === "BinaryExpression" || + parentNode.expression.type === "LogicalExpression" + ) { + if (parentNode.expression.right === node) { + return true; + } + } + + return false; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + CallExpression(node) { + // if we're not a callback we can return + if (!isCallback(node)) { + return; + } + + // find the closest block, return or loop + const closestBlock = + findClosestParentOfType(node, [ + "BlockStatement", + "ReturnStatement", + "ArrowFunctionExpression", + ]) || {}; + + // if our parent is a return we know we're ok + if (closestBlock.type === "ReturnStatement") { + return; + } + + // arrow functions don't always have blocks and implicitly return + if (closestBlock.type === "ArrowFunctionExpression") { + return; + } + + // block statements are part of functions and most if statements + if (closestBlock.type === "BlockStatement") { + // find the last item in the block + const lastItem = closestBlock.body.at(-1); + + // if the callback is the last thing in a block that might be ok + if (isCallbackExpression(node, lastItem)) { + const parentType = closestBlock.parent.type; + + // but only if the block is part of a function + if ( + parentType === "FunctionExpression" || + parentType === "FunctionDeclaration" || + parentType === "ArrowFunctionExpression" + ) { + return; + } + } + + // ending a block with a return is also ok + if (lastItem.type === "ReturnStatement") { + // but only if the callback is immediately before + if ( + isCallbackExpression(node, closestBlock.body.at(-2)) + ) { + return; + } + } + } + + // as long as you're the child of a function at this point you should be asked to return + if ( + findClosestParentOfType(node, [ + "FunctionDeclaration", + "FunctionExpression", + "ArrowFunctionExpression", + ]) + ) { + context.report({ node, messageId: "missingReturn" }); + } + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/camelcase.js b/tools/ui/node_modules/eslint/lib/rules/camelcase.js new file mode 100644 index 0000000000000000000000000000000000000000..dad6b120bbdc6d12ee664f074b975e9c4f8ef7db --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/camelcase.js @@ -0,0 +1,422 @@ +/** + * @fileoverview Rule to flag non-camelcased identifiers + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + allow: [], + ignoreDestructuring: false, + ignoreGlobals: false, + ignoreImports: false, + properties: "always", + }, + ], + + docs: { + description: "Enforce camelcase naming convention", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/camelcase", + }, + + schema: [ + { + type: "object", + properties: { + ignoreDestructuring: { + type: "boolean", + }, + ignoreImports: { + type: "boolean", + }, + ignoreGlobals: { + type: "boolean", + }, + properties: { + enum: ["always", "never"], + }, + allow: { + type: "array", + items: { + type: "string", + }, + minItems: 0, + uniqueItems: true, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + notCamelCase: "Identifier '{{name}}' is not in camel case.", + notCamelCasePrivate: "#{{name}} is not in camel case.", + }, + }, + + create(context) { + const [ + { + allow, + ignoreDestructuring, + ignoreGlobals, + ignoreImports, + properties, + }, + ] = context.options; + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + // contains reported nodes to avoid reporting twice on destructuring with shorthand notation + const reported = new Set(); + + /** + * Checks if a string contains an underscore and isn't all upper-case + * @param {string} name The string to check. + * @returns {boolean} if the string is underscored + * @private + */ + function isUnderscored(name) { + const nameBody = name.replace(/^_+|_+$/gu, ""); + + // if there's an underscore, it might be A_CONSTANT, which is okay + return ( + nameBody.includes("_") && nameBody !== nameBody.toUpperCase() + ); + } + + /** + * Checks if a string match the ignore list + * @param {string} name The string to check. + * @returns {boolean} if the string is ignored + * @private + */ + function isAllowed(name) { + return allow.some( + entry => name === entry || name.match(new RegExp(entry, "u")), + ); + } + + /** + * Checks if a given name is good or not. + * @param {string} name The name to check. + * @returns {boolean} `true` if the name is good. + * @private + */ + function isGoodName(name) { + return !isUnderscored(name) || isAllowed(name); + } + + /** + * Checks if a given identifier reference or member expression is an assignment + * target. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is an assignment target. + */ + function isAssignmentTarget(node) { + const parent = node.parent; + + switch (parent.type) { + case "AssignmentExpression": + case "AssignmentPattern": + return parent.left === node; + + case "Property": + return ( + parent.parent.type === "ObjectPattern" && + parent.value === node + ); + case "ArrayPattern": + case "RestElement": + return true; + + default: + return false; + } + } + + /** + * Checks if a given binding identifier uses the original name as-is. + * - If it's in object destructuring or object expression, the original name is its property name. + * - If it's in import declaration, the original name is its exported name. + * @param {ASTNode} node The `Identifier` node to check. + * @returns {boolean} `true` if the identifier uses the original name as-is. + */ + function equalsToOriginalName(node) { + const localName = node.name; + const valueNode = + node.parent.type === "AssignmentPattern" ? node.parent : node; + const parent = valueNode.parent; + + switch (parent.type) { + case "Property": + return ( + (parent.parent.type === "ObjectPattern" || + parent.parent.type === "ObjectExpression") && + parent.value === valueNode && + !parent.computed && + parent.key.type === "Identifier" && + parent.key.name === localName + ); + + case "ImportSpecifier": + return ( + parent.local === node && + astUtils.getModuleExportName(parent.imported) === + localName + ); + + default: + return false; + } + } + + /** + * Reports an AST node as a rule violation. + * @param {ASTNode} node The node to report. + * @returns {void} + * @private + */ + function report(node) { + if (reported.has(node.range[0])) { + return; + } + reported.add(node.range[0]); + + // Report it. + context.report({ + node, + messageId: + node.type === "PrivateIdentifier" + ? "notCamelCasePrivate" + : "notCamelCase", + data: { name: node.name }, + }); + } + + /** + * Reports an identifier reference or a binding identifier. + * @param {ASTNode} node The `Identifier` node to report. + * @returns {void} + */ + function reportReferenceId(node) { + /* + * For backward compatibility, if it's in callings then ignore it. + * Not sure why it is. + */ + if ( + node.parent.type === "CallExpression" || + node.parent.type === "NewExpression" + ) { + return; + } + + /* + * For backward compatibility, if it's a default value of + * destructuring/parameters then ignore it. + * Not sure why it is. + */ + if ( + node.parent.type === "AssignmentPattern" && + node.parent.right === node + ) { + return; + } + + /* + * The `ignoreDestructuring` flag skips the identifiers that uses + * the property name as-is. + */ + if (ignoreDestructuring && equalsToOriginalName(node)) { + return; + } + + /* + * Import attribute keys are always ignored + */ + if (astUtils.isImportAttributeKey(node)) { + return; + } + + report(node); + } + + return { + // Report camelcase of global variable references ------------------ + Program(node) { + const scope = sourceCode.getScope(node); + + if (!ignoreGlobals) { + // Defined globals in config files or directive comments. + for (const variable of scope.variables) { + if ( + variable.identifiers.length > 0 || + isGoodName(variable.name) + ) { + continue; + } + for (const reference of variable.references) { + /* + * For backward compatibility, this rule reports read-only + * references as well. + */ + reportReferenceId(reference.identifier); + } + } + } + + // Undefined globals. + for (const reference of scope.through) { + const id = reference.identifier; + + if ( + isGoodName(id.name) || + astUtils.isImportAttributeKey(id) + ) { + continue; + } + + /* + * For backward compatibility, this rule reports read-only + * references as well. + */ + reportReferenceId(id); + } + }, + + // Report camelcase of declared variables -------------------------- + [[ + "VariableDeclaration", + "FunctionDeclaration", + "FunctionExpression", + "ArrowFunctionExpression", + "ClassDeclaration", + "ClassExpression", + "CatchClause", + ]](node) { + for (const variable of sourceCode.getDeclaredVariables(node)) { + if (isGoodName(variable.name)) { + continue; + } + const id = variable.identifiers[0]; + + // Report declaration. + if (!(ignoreDestructuring && equalsToOriginalName(id))) { + report(id); + } + + /* + * For backward compatibility, report references as well. + * It looks unnecessary because declarations are reported. + */ + for (const reference of variable.references) { + if (reference.init) { + continue; // Skip the write references of initializers. + } + reportReferenceId(reference.identifier); + } + } + }, + + // Report camelcase in properties ---------------------------------- + [[ + "ObjectExpression > Property[computed!=true] > Identifier.key", + "MethodDefinition[computed!=true] > Identifier.key", + "PropertyDefinition[computed!=true] > Identifier.key", + "MethodDefinition > PrivateIdentifier.key", + "PropertyDefinition > PrivateIdentifier.key", + ]](node) { + if ( + properties === "never" || + astUtils.isImportAttributeKey(node) || + isGoodName(node.name) + ) { + return; + } + report(node); + }, + "MemberExpression[computed!=true] > Identifier.property"(node) { + if ( + properties === "never" || + !isAssignmentTarget(node.parent) || // ← ignore read-only references. + isGoodName(node.name) + ) { + return; + } + report(node); + }, + + // Report camelcase in import -------------------------------------- + ImportDeclaration(node) { + for (const variable of sourceCode.getDeclaredVariables(node)) { + if (isGoodName(variable.name)) { + continue; + } + const id = variable.identifiers[0]; + + // Report declaration. + if (!(ignoreImports && equalsToOriginalName(id))) { + report(id); + } + + /* + * For backward compatibility, report references as well. + * It looks unnecessary because declarations are reported. + */ + for (const reference of variable.references) { + reportReferenceId(reference.identifier); + } + } + }, + + // Report camelcase in re-export ----------------------------------- + [[ + "ExportAllDeclaration > Identifier.exported", + "ExportSpecifier > Identifier.exported", + ]](node) { + if (isGoodName(node.name)) { + return; + } + report(node); + }, + + // Report camelcase in labels -------------------------------------- + [[ + "LabeledStatement > Identifier.label", + + /* + * For backward compatibility, report references as well. + * It looks unnecessary because declarations are reported. + */ + "BreakStatement > Identifier.label", + "ContinueStatement > Identifier.label", + ]](node) { + if (isGoodName(node.name)) { + return; + } + report(node); + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/capitalized-comments.js b/tools/ui/node_modules/eslint/lib/rules/capitalized-comments.js new file mode 100644 index 0000000000000000000000000000000000000000..17c53fc8bde755783892bd2ad82c61988cc9f51d --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/capitalized-comments.js @@ -0,0 +1,325 @@ +/** + * @fileoverview enforce or disallow capitalization of the first letter of a comment + * @author Kevin Partington + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const DEFAULT_IGNORE_PATTERN = astUtils.COMMENTS_IGNORE_PATTERN, + WHITESPACE = /\s/gu, + MAYBE_URL = /^\s*[^:/?#\s]+:\/\/[^?#]/u, // TODO: Combine w/ max-len pattern? + LETTER_PATTERN = /\p{L}/u; + +/* + * Base schema body for defining the basic capitalization rule, ignorePattern, + * and ignoreInlineComments values. + * This can be used in a few different ways in the actual schema. + */ +const SCHEMA_BODY = { + type: "object", + properties: { + ignorePattern: { + type: "string", + }, + ignoreInlineComments: { + type: "boolean", + }, + ignoreConsecutiveComments: { + type: "boolean", + }, + }, + additionalProperties: false, +}; +const DEFAULTS = { + ignorePattern: "", + ignoreInlineComments: false, + ignoreConsecutiveComments: false, +}; + +/** + * Get normalized options for either block or line comments from the given + * user-provided options. + * - If the user-provided options is just a string, returns a normalized + * set of options using default values for all other options. + * - If the user-provided options is an object, then a normalized option + * set is returned. Options specified in overrides will take priority + * over options specified in the main options object, which will in + * turn take priority over the rule's defaults. + * @param {Object|string} rawOptions The user-provided options. + * @param {string} which Either "line" or "block". + * @returns {Object} The normalized options. + */ +function getNormalizedOptions(rawOptions, which) { + return Object.assign({}, DEFAULTS, rawOptions[which] || rawOptions); +} + +/** + * Get normalized options for block and line comments. + * @param {Object|string} rawOptions The user-provided options. + * @returns {Object} An object with "Line" and "Block" keys and corresponding + * normalized options objects. + */ +function getAllNormalizedOptions(rawOptions = {}) { + return { + Line: getNormalizedOptions(rawOptions, "line"), + Block: getNormalizedOptions(rawOptions, "block"), + }; +} + +/** + * Creates a regular expression for each ignorePattern defined in the rule + * options. + * + * This is done in order to avoid invoking the RegExp constructor repeatedly. + * @param {Object} normalizedOptions The normalized rule options. + * @returns {void} + */ +function createRegExpForIgnorePatterns(normalizedOptions) { + Object.keys(normalizedOptions).forEach(key => { + const ignorePatternStr = normalizedOptions[key].ignorePattern; + + if (ignorePatternStr) { + const regExp = RegExp(`^\\s*(?:${ignorePatternStr})`, "u"); + + normalizedOptions[key].ignorePatternRegExp = regExp; + } + }); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Enforce or disallow capitalization of the first letter of a comment", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/capitalized-comments", + }, + + fixable: "code", + + schema: [ + { enum: ["always", "never"] }, + { + oneOf: [ + SCHEMA_BODY, + { + type: "object", + properties: { + line: SCHEMA_BODY, + block: SCHEMA_BODY, + }, + additionalProperties: false, + }, + ], + }, + ], + + messages: { + unexpectedLowercaseComment: + "Comments should not begin with a lowercase character.", + unexpectedUppercaseComment: + "Comments should not begin with an uppercase character.", + }, + }, + + create(context) { + const capitalize = context.options[0] || "always", + normalizedOptions = getAllNormalizedOptions(context.options[1]), + sourceCode = context.sourceCode; + + createRegExpForIgnorePatterns(normalizedOptions); + + //---------------------------------------------------------------------- + // Helpers + //---------------------------------------------------------------------- + + /** + * Checks whether a comment is an inline comment. + * + * For the purpose of this rule, a comment is inline if: + * 1. The comment is preceded by a token on the same line; and + * 2. The command is followed by a token on the same line. + * + * Note that the comment itself need not be single-line! + * + * Also, it follows from this definition that only block comments can + * be considered as possibly inline. This is because line comments + * would consume any following tokens on the same line as the comment. + * @param {ASTNode} comment The comment node to check. + * @returns {boolean} True if the comment is an inline comment, false + * otherwise. + */ + function isInlineComment(comment) { + const previousToken = sourceCode.getTokenBefore(comment, { + includeComments: true, + }), + nextToken = sourceCode.getTokenAfter(comment, { + includeComments: true, + }); + + return Boolean( + previousToken && + nextToken && + comment.loc.start.line === previousToken.loc.end.line && + comment.loc.end.line === nextToken.loc.start.line, + ); + } + + /** + * Determine if a comment follows another comment. + * @param {ASTNode} comment The comment to check. + * @returns {boolean} True if the comment follows a valid comment. + */ + function isConsecutiveComment(comment) { + const previousTokenOrComment = sourceCode.getTokenBefore(comment, { + includeComments: true, + }); + + return Boolean( + previousTokenOrComment && + ["Block", "Line"].includes(previousTokenOrComment.type), + ); + } + + /** + * Check a comment to determine if it is valid for this rule. + * @param {ASTNode} comment The comment node to process. + * @param {Object} options The options for checking this comment. + * @returns {boolean} True if the comment is valid, false otherwise. + */ + function isCommentValid(comment, options) { + // 1. Check for default ignore pattern. + if (DEFAULT_IGNORE_PATTERN.test(comment.value)) { + return true; + } + + // 2. Check for custom ignore pattern. + const commentWithoutAsterisks = comment.value.replace(/\*/gu, ""); + + if ( + options.ignorePatternRegExp && + options.ignorePatternRegExp.test(commentWithoutAsterisks) + ) { + return true; + } + + // 3. Check for inline comments. + if (options.ignoreInlineComments && isInlineComment(comment)) { + return true; + } + + // 4. Is this a consecutive comment (and are we tolerating those)? + if ( + options.ignoreConsecutiveComments && + isConsecutiveComment(comment) + ) { + return true; + } + + // 5. Does the comment start with a possible URL? + if (MAYBE_URL.test(commentWithoutAsterisks)) { + return true; + } + + // 6. Is the initial word character a letter? + const commentWordCharsOnly = commentWithoutAsterisks.replace( + WHITESPACE, + "", + ); + + if (commentWordCharsOnly.length === 0) { + return true; + } + + // Get the first Unicode character (1 or 2 code units). + const [firstWordChar] = commentWordCharsOnly; + + if (!LETTER_PATTERN.test(firstWordChar)) { + return true; + } + + // 7. Check the case of the initial word character. + const isUppercase = + firstWordChar !== firstWordChar.toLocaleLowerCase(), + isLowercase = + firstWordChar !== firstWordChar.toLocaleUpperCase(); + + if (capitalize === "always" && isLowercase) { + return false; + } + if (capitalize === "never" && isUppercase) { + return false; + } + + return true; + } + + /** + * Process a comment to determine if it needs to be reported. + * @param {ASTNode} comment The comment node to process. + * @returns {void} + */ + function processComment(comment) { + const options = normalizedOptions[comment.type], + commentValid = isCommentValid(comment, options); + + if (!commentValid) { + const messageId = + capitalize === "always" + ? "unexpectedLowercaseComment" + : "unexpectedUppercaseComment"; + + context.report({ + node: null, // Intentionally using loc instead + loc: comment.loc, + messageId, + fix(fixer) { + const match = comment.value.match(LETTER_PATTERN); + const char = match[0]; + + // Offset match.index by 2 to account for the first 2 characters that start the comment (// or /*) + const charIndex = comment.range[0] + match.index + 2; + + return fixer.replaceTextRange( + [charIndex, charIndex + char.length], + capitalize === "always" + ? char.toLocaleUpperCase() + : char.toLocaleLowerCase(), + ); + }, + }); + } + } + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + + return { + Program() { + const comments = sourceCode.getAllComments(); + + comments + .filter(token => token.type !== "Shebang") + .forEach(processComment); + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/class-methods-use-this.js b/tools/ui/node_modules/eslint/lib/rules/class-methods-use-this.js new file mode 100644 index 0000000000000000000000000000000000000000..5ce4893d8d20157935acf3b034e6180cd701bd5a --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/class-methods-use-this.js @@ -0,0 +1,250 @@ +/** + * @fileoverview Rule to enforce that all class methods use 'this'. + * @author Patrick Williams + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + dialects: ["javascript", "typescript"], + language: "javascript", + type: "suggestion", + + defaultOptions: [ + { + enforceForClassFields: true, + exceptMethods: [], + ignoreOverrideMethods: false, + }, + ], + + docs: { + description: "Enforce that class methods utilize `this`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/class-methods-use-this", + }, + + schema: [ + { + type: "object", + properties: { + exceptMethods: { + type: "array", + items: { + type: "string", + }, + }, + enforceForClassFields: { + type: "boolean", + }, + ignoreOverrideMethods: { + type: "boolean", + }, + ignoreClassesWithImplements: { + enum: ["all", "public-fields"], + }, + }, + additionalProperties: false, + }, + ], + + messages: { + missingThis: "Expected 'this' to be used by class {{name}}.", + }, + }, + create(context) { + const [options] = context.options; + const { + enforceForClassFields, + ignoreOverrideMethods, + ignoreClassesWithImplements, + } = options; + const exceptMethods = new Set(options.exceptMethods); + + const stack = []; + + /** + * Push `this` used flag initialized with `false` onto the stack. + * @returns {void} + */ + function pushContext() { + stack.push(false); + } + + /** + * Pop `this` used flag from the stack. + * @returns {boolean | undefined} `this` used flag + */ + function popContext() { + return stack.pop(); + } + + /** + * Initializes the current context to false and pushes it onto the stack. + * These booleans represent whether 'this' has been used in the context. + * @returns {void} + * @private + */ + function enterFunction() { + pushContext(); + } + + /** + * Check if the node is an instance method + * @param {ASTNode} node node to check + * @returns {boolean} True if its an instance method + * @private + */ + function isInstanceMethod(node) { + switch (node.type) { + case "MethodDefinition": + return !node.static && node.kind !== "constructor"; + case "AccessorProperty": + case "PropertyDefinition": + return !node.static && enforceForClassFields; + default: + return false; + } + } + + /** + * Check if the node's parent class implements any interfaces + * @param {ASTNode} node node to check + * @returns {boolean} True if parent class implements interfaces + * @private + */ + function hasImplements(node) { + const classNode = node.parent.parent; + return ( + classNode?.type === "ClassDeclaration" && + classNode.implements?.length > 0 + ); + } + + /** + * Check if the node is an instance method not excluded by config + * @param {ASTNode} node node to check + * @returns {boolean} True if it is an instance method, and not excluded by config + * @private + */ + function isIncludedInstanceMethod(node) { + if (isInstanceMethod(node)) { + if (node.computed) { + return true; + } + + if (ignoreOverrideMethods && node.override) { + return false; + } + + if (ignoreClassesWithImplements) { + const implementsInterfaces = hasImplements(node); + if (implementsInterfaces) { + if ( + ignoreClassesWithImplements === "all" || + (ignoreClassesWithImplements === "public-fields" && + node.key.type !== "PrivateIdentifier" && + (!node.accessibility || + node.accessibility === "public")) + ) { + return false; + } + } + } + + const hashIfNeeded = + node.key.type === "PrivateIdentifier" ? "#" : ""; + const name = + node.key.type === "Literal" + ? astUtils.getStaticStringValue(node.key) + : node.key.name || ""; + + return !exceptMethods.has(hashIfNeeded + name); + } + return false; + } + + /** + * Checks if we are leaving a function that is a method, and reports if 'this' has not been used. + * Static methods and the constructor are exempt. + * Then pops the context off the stack. + * @param {ASTNode} node A function node that was entered. + * @returns {void} + * @private + */ + function exitFunction(node) { + const methodUsesThis = popContext(); + + if (isIncludedInstanceMethod(node.parent) && !methodUsesThis) { + context.report({ + node, + loc: astUtils.getFunctionHeadLoc(node, context.sourceCode), + messageId: "missingThis", + data: { + name: astUtils.getFunctionNameWithKind(node), + }, + }); + } + } + + /** + * Mark the current context as having used 'this'. + * @returns {void} + * @private + */ + function markThisUsed() { + if (stack.length) { + stack[stack.length - 1] = true; + } + } + + return { + FunctionDeclaration: enterFunction, + "FunctionDeclaration:exit": exitFunction, + FunctionExpression: enterFunction, + "FunctionExpression:exit": exitFunction, + + /* + * Class field value are implicit functions. + */ + "AccessorProperty > *.key:exit": pushContext, + "AccessorProperty:exit": popContext, + "PropertyDefinition > *.key:exit": pushContext, + "PropertyDefinition:exit": popContext, + + /* + * Class static blocks are implicit functions. They aren't required to use `this`, + * but we have to push context so that it captures any use of `this` in the static block + * separately from enclosing contexts, because static blocks have their own `this` and it + * shouldn't count as used `this` in enclosing contexts. + */ + StaticBlock: pushContext, + "StaticBlock:exit": popContext, + + ThisExpression: markThisUsed, + Super: markThisUsed, + ...(enforceForClassFields && { + "AccessorProperty > ArrowFunctionExpression.value": + enterFunction, + "AccessorProperty > ArrowFunctionExpression.value:exit": + exitFunction, + "PropertyDefinition > ArrowFunctionExpression.value": + enterFunction, + "PropertyDefinition > ArrowFunctionExpression.value:exit": + exitFunction, + }), + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/comma-dangle.js b/tools/ui/node_modules/eslint/lib/rules/comma-dangle.js new file mode 100644 index 0000000000000000000000000000000000000000..121ada3ce759e5b14f34dbf3a61dee82faa99796 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/comma-dangle.js @@ -0,0 +1,424 @@ +/** + * @fileoverview Rule to forbid or enforce dangling commas. + * @author Ian Christian Myers + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const DEFAULT_OPTIONS = Object.freeze({ + arrays: "never", + objects: "never", + imports: "never", + exports: "never", + functions: "never", +}); + +/** + * Checks whether or not a trailing comma is allowed in a given node. + * If the `lastItem` is `RestElement` or `RestProperty`, it disallows trailing commas. + * @param {ASTNode} lastItem The node of the last element in the given node. + * @returns {boolean} `true` if a trailing comma is allowed. + */ +function isTrailingCommaAllowed(lastItem) { + return !( + lastItem.type === "RestElement" || + lastItem.type === "RestProperty" || + lastItem.type === "ExperimentalRestProperty" + ); +} + +/** + * Normalize option value. + * @param {string|Object|undefined} optionValue The 1st option value to normalize. + * @param {number} ecmaVersion The normalized ECMAScript version. + * @returns {Object} The normalized option value. + */ +function normalizeOptions(optionValue, ecmaVersion) { + if (typeof optionValue === "string") { + return { + arrays: optionValue, + objects: optionValue, + imports: optionValue, + exports: optionValue, + functions: ecmaVersion < 2017 ? "ignore" : optionValue, + }; + } + if (typeof optionValue === "object" && optionValue !== null) { + return { + arrays: optionValue.arrays || DEFAULT_OPTIONS.arrays, + objects: optionValue.objects || DEFAULT_OPTIONS.objects, + imports: optionValue.imports || DEFAULT_OPTIONS.imports, + exports: optionValue.exports || DEFAULT_OPTIONS.exports, + functions: optionValue.functions || DEFAULT_OPTIONS.functions, + }; + } + + return DEFAULT_OPTIONS; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "comma-dangle", + url: "https://eslint.style/rules/comma-dangle", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Require or disallow trailing commas", + recommended: false, + url: "https://eslint.org/docs/latest/rules/comma-dangle", + }, + + fixable: "code", + + schema: { + definitions: { + value: { + enum: [ + "always-multiline", + "always", + "never", + "only-multiline", + ], + }, + valueWithIgnore: { + enum: [ + "always-multiline", + "always", + "ignore", + "never", + "only-multiline", + ], + }, + }, + type: "array", + items: [ + { + oneOf: [ + { + $ref: "#/definitions/value", + }, + { + type: "object", + properties: { + arrays: { + $ref: "#/definitions/valueWithIgnore", + }, + objects: { + $ref: "#/definitions/valueWithIgnore", + }, + imports: { + $ref: "#/definitions/valueWithIgnore", + }, + exports: { + $ref: "#/definitions/valueWithIgnore", + }, + functions: { + $ref: "#/definitions/valueWithIgnore", + }, + }, + additionalProperties: false, + }, + ], + }, + ], + additionalItems: false, + }, + + messages: { + unexpected: "Unexpected trailing comma.", + missing: "Missing trailing comma.", + }, + }, + + create(context) { + const options = normalizeOptions( + context.options[0], + context.languageOptions.ecmaVersion, + ); + + const sourceCode = context.sourceCode; + + /** + * Gets the last item of the given node. + * @param {ASTNode} node The node to get. + * @returns {ASTNode|null} The last node or null. + */ + function getLastItem(node) { + /** + * Returns the last element of an array + * @param {any[]} array The input array + * @returns {any} The last element + */ + function last(array) { + return array.at(-1); + } + + switch (node.type) { + case "ObjectExpression": + case "ObjectPattern": + return last(node.properties); + case "ArrayExpression": + case "ArrayPattern": + return last(node.elements); + case "ImportDeclaration": + case "ExportNamedDeclaration": + return last(node.specifiers); + case "FunctionDeclaration": + case "FunctionExpression": + case "ArrowFunctionExpression": + return last(node.params); + case "CallExpression": + case "NewExpression": + return last(node.arguments); + default: + return null; + } + } + + /** + * Gets the trailing comma token of the given node. + * If the trailing comma does not exist, this returns the token which is + * the insertion point of the trailing comma token. + * @param {ASTNode} node The node to get. + * @param {ASTNode} lastItem The last item of the node. + * @returns {Token} The trailing comma token or the insertion point. + */ + function getTrailingToken(node, lastItem) { + switch (node.type) { + case "ObjectExpression": + case "ArrayExpression": + case "CallExpression": + case "NewExpression": + return sourceCode.getLastToken(node, 1); + default: { + const nextToken = sourceCode.getTokenAfter(lastItem); + + if (astUtils.isCommaToken(nextToken)) { + return nextToken; + } + return sourceCode.getLastToken(lastItem); + } + } + } + + /** + * Checks whether or not a given node is multiline. + * This rule handles a given node as multiline when the closing parenthesis + * and the last element are not on the same line. + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is multiline. + */ + function isMultiline(node) { + const lastItem = getLastItem(node); + + if (!lastItem) { + return false; + } + + const penultimateToken = getTrailingToken(node, lastItem); + const lastToken = sourceCode.getTokenAfter(penultimateToken); + + return lastToken.loc.end.line !== penultimateToken.loc.end.line; + } + + /** + * Reports a trailing comma if it exists. + * @param {ASTNode} node A node to check. Its type is one of + * ObjectExpression, ObjectPattern, ArrayExpression, ArrayPattern, + * ImportDeclaration, and ExportNamedDeclaration. + * @returns {void} + */ + function forbidTrailingComma(node) { + const lastItem = getLastItem(node); + + if ( + !lastItem || + (node.type === "ImportDeclaration" && + lastItem.type !== "ImportSpecifier") + ) { + return; + } + + const trailingToken = getTrailingToken(node, lastItem); + + if (astUtils.isCommaToken(trailingToken)) { + context.report({ + node: lastItem, + loc: trailingToken.loc, + messageId: "unexpected", + *fix(fixer) { + yield fixer.remove(trailingToken); + + /* + * Extend the range of the fix to include surrounding tokens to ensure + * that the element after which the comma is removed stays _last_. + * This intentionally makes conflicts in fix ranges with rules that may be + * adding or removing elements in the same autofix pass. + * https://github.com/eslint/eslint/issues/15660 + */ + yield fixer.insertTextBefore( + sourceCode.getTokenBefore(trailingToken), + "", + ); + yield fixer.insertTextAfter( + sourceCode.getTokenAfter(trailingToken), + "", + ); + }, + }); + } + } + + /** + * Reports the last element of a given node if it does not have a trailing + * comma. + * + * If a given node is `ArrayPattern` which has `RestElement`, the trailing + * comma is disallowed, so report if it exists. + * @param {ASTNode} node A node to check. Its type is one of + * ObjectExpression, ObjectPattern, ArrayExpression, ArrayPattern, + * ImportDeclaration, and ExportNamedDeclaration. + * @returns {void} + */ + function forceTrailingComma(node) { + const lastItem = getLastItem(node); + + if ( + !lastItem || + (node.type === "ImportDeclaration" && + lastItem.type !== "ImportSpecifier") + ) { + return; + } + if (!isTrailingCommaAllowed(lastItem)) { + forbidTrailingComma(node); + return; + } + + const trailingToken = getTrailingToken(node, lastItem); + + if (trailingToken.value !== ",") { + context.report({ + node: lastItem, + loc: { + start: trailingToken.loc.end, + end: astUtils.getNextLocation( + sourceCode, + trailingToken.loc.end, + ), + }, + messageId: "missing", + *fix(fixer) { + yield fixer.insertTextAfter(trailingToken, ","); + + /* + * Extend the range of the fix to include surrounding tokens to ensure + * that the element after which the comma is inserted stays _last_. + * This intentionally makes conflicts in fix ranges with rules that may be + * adding or removing elements in the same autofix pass. + * https://github.com/eslint/eslint/issues/15660 + */ + yield fixer.insertTextBefore(trailingToken, ""); + yield fixer.insertTextAfter( + sourceCode.getTokenAfter(trailingToken), + "", + ); + }, + }); + } + } + + /** + * If a given node is multiline, reports the last element of a given node + * when it does not have a trailing comma. + * Otherwise, reports a trailing comma if it exists. + * @param {ASTNode} node A node to check. Its type is one of + * ObjectExpression, ObjectPattern, ArrayExpression, ArrayPattern, + * ImportDeclaration, and ExportNamedDeclaration. + * @returns {void} + */ + function forceTrailingCommaIfMultiline(node) { + if (isMultiline(node)) { + forceTrailingComma(node); + } else { + forbidTrailingComma(node); + } + } + + /** + * Only if a given node is not multiline, reports the last element of a given node + * when it does not have a trailing comma. + * Otherwise, reports a trailing comma if it exists. + * @param {ASTNode} node A node to check. Its type is one of + * ObjectExpression, ObjectPattern, ArrayExpression, ArrayPattern, + * ImportDeclaration, and ExportNamedDeclaration. + * @returns {void} + */ + function allowTrailingCommaIfMultiline(node) { + if (!isMultiline(node)) { + forbidTrailingComma(node); + } + } + + const predicate = { + always: forceTrailingComma, + "always-multiline": forceTrailingCommaIfMultiline, + "only-multiline": allowTrailingCommaIfMultiline, + never: forbidTrailingComma, + ignore() {}, + }; + + return { + ObjectExpression: predicate[options.objects], + ObjectPattern: predicate[options.objects], + + ArrayExpression: predicate[options.arrays], + ArrayPattern: predicate[options.arrays], + + ImportDeclaration: predicate[options.imports], + + ExportNamedDeclaration: predicate[options.exports], + + FunctionDeclaration: predicate[options.functions], + FunctionExpression: predicate[options.functions], + ArrowFunctionExpression: predicate[options.functions], + CallExpression: predicate[options.functions], + NewExpression: predicate[options.functions], + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/comma-spacing.js b/tools/ui/node_modules/eslint/lib/rules/comma-spacing.js new file mode 100644 index 0000000000000000000000000000000000000000..5216519122541824dd5be44a8f98f34f6e15100c --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/comma-spacing.js @@ -0,0 +1,208 @@ +/** + * @fileoverview Comma spacing - validates spacing before and after comma + * @author Vignesh Anand aka vegetableman. + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "comma-spacing", + url: "https://eslint.style/rules/comma-spacing", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce consistent spacing before and after commas", + recommended: false, + url: "https://eslint.org/docs/latest/rules/comma-spacing", + }, + + fixable: "whitespace", + + schema: [ + { + type: "object", + properties: { + before: { + type: "boolean", + default: false, + }, + after: { + type: "boolean", + default: true, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + missing: "A space is required {{loc}} ','.", + unexpected: "There should be no space {{loc}} ','.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const tokensAndComments = sourceCode.tokensAndComments; + + const options = { + before: context.options[0] ? context.options[0].before : false, + after: context.options[0] ? context.options[0].after : true, + }; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + // list of comma tokens to ignore for the check of leading whitespace + const commaTokensToIgnore = []; + + /** + * Reports a spacing error with an appropriate message. + * @param {ASTNode} node The binary expression node to report. + * @param {string} loc Is the error "before" or "after" the comma? + * @param {ASTNode} otherNode The node at the left or right of `node` + * @returns {void} + * @private + */ + function report(node, loc, otherNode) { + context.report({ + node, + fix(fixer) { + if (options[loc]) { + if (loc === "before") { + return fixer.insertTextBefore(node, " "); + } + return fixer.insertTextAfter(node, " "); + } + let start, end; + const newText = ""; + + if (loc === "before") { + start = otherNode.range[1]; + end = node.range[0]; + } else { + start = node.range[1]; + end = otherNode.range[0]; + } + + return fixer.replaceTextRange([start, end], newText); + }, + messageId: options[loc] ? "missing" : "unexpected", + data: { + loc, + }, + }); + } + + /** + * Adds null elements of the given ArrayExpression or ArrayPattern node to the ignore list. + * @param {ASTNode} node An ArrayExpression or ArrayPattern node. + * @returns {void} + */ + function addNullElementsToIgnoreList(node) { + let previousToken = sourceCode.getFirstToken(node); + + node.elements.forEach(element => { + let token; + + if (element === null) { + token = sourceCode.getTokenAfter(previousToken); + + if (astUtils.isCommaToken(token)) { + commaTokensToIgnore.push(token); + } + } else { + token = sourceCode.getTokenAfter(element); + } + + previousToken = token; + }); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + "Program:exit"() { + tokensAndComments.forEach((token, i) => { + if (!astUtils.isCommaToken(token)) { + return; + } + + const previousToken = tokensAndComments[i - 1]; + const nextToken = tokensAndComments[i + 1]; + + if ( + previousToken && + !astUtils.isCommaToken(previousToken) && // ignore spacing between two commas + /* + * `commaTokensToIgnore` are ending commas of `null` elements (array holes/elisions). + * In addition to spacing between two commas, this can also ignore: + * + * - Spacing after `[` (controlled by array-bracket-spacing) + * Example: [ , ] + * ^ + * - Spacing after a comment (for backwards compatibility, this was possibly unintentional) + * Example: [a, /* * / ,] + * ^ + */ + !commaTokensToIgnore.includes(token) && + astUtils.isTokenOnSameLine(previousToken, token) && + options.before !== + sourceCode.isSpaceBetweenTokens( + previousToken, + token, + ) + ) { + report(token, "before", previousToken); + } + + if ( + nextToken && + !astUtils.isCommaToken(nextToken) && // ignore spacing between two commas + !astUtils.isClosingParenToken(nextToken) && // controlled by space-in-parens + !astUtils.isClosingBracketToken(nextToken) && // controlled by array-bracket-spacing + !astUtils.isClosingBraceToken(nextToken) && // controlled by object-curly-spacing + !(!options.after && nextToken.type === "Line") && // special case, allow space before line comment + astUtils.isTokenOnSameLine(token, nextToken) && + options.after !== + sourceCode.isSpaceBetweenTokens(token, nextToken) + ) { + report(token, "after", nextToken); + } + }); + }, + ArrayExpression: addNullElementsToIgnoreList, + ArrayPattern: addNullElementsToIgnoreList, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/comma-style.js b/tools/ui/node_modules/eslint/lib/rules/comma-style.js new file mode 100644 index 0000000000000000000000000000000000000000..6c8e765691a9eba5f56eb7c1e02933bce6e8701c --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/comma-style.js @@ -0,0 +1,391 @@ +/** + * @fileoverview Comma style - enforces comma styles of two types: last and first + * @author Vignesh Anand aka vegetableman + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "comma-style", + url: "https://eslint.style/rules/comma-style", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce consistent comma style", + recommended: false, + url: "https://eslint.org/docs/latest/rules/comma-style", + }, + + fixable: "code", + + schema: [ + { + enum: ["first", "last"], + }, + { + type: "object", + properties: { + exceptions: { + type: "object", + additionalProperties: { + type: "boolean", + }, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpectedLineBeforeAndAfterComma: + "Bad line breaking before and after ','.", + expectedCommaFirst: "',' should be placed first.", + expectedCommaLast: "',' should be placed last.", + }, + }, + + create(context) { + const style = context.options[0] || "last", + sourceCode = context.sourceCode; + const exceptions = { + ArrayPattern: true, + ArrowFunctionExpression: true, + CallExpression: true, + FunctionDeclaration: true, + FunctionExpression: true, + ImportDeclaration: true, + ObjectPattern: true, + NewExpression: true, + }; + + if ( + context.options.length === 2 && + Object.hasOwn(context.options[1], "exceptions") + ) { + const keys = Object.keys(context.options[1].exceptions); + + for (let i = 0; i < keys.length; i++) { + exceptions[keys[i]] = context.options[1].exceptions[keys[i]]; + } + } + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Modified text based on the style + * @param {string} styleType Style type + * @param {string} text Source code text + * @returns {string} modified text + * @private + */ + function getReplacedText(styleType, text) { + switch (styleType) { + case "between": + return `,${text.replace(astUtils.LINEBREAK_MATCHER, "")}`; + + case "first": + return `${text},`; + + case "last": + return `,${text}`; + + default: + return ""; + } + } + + /** + * Determines the fixer function for a given style. + * @param {string} styleType comma style + * @param {ASTNode} previousItemToken The token to check. + * @param {ASTNode} commaToken The token to check. + * @param {ASTNode} currentItemToken The token to check. + * @returns {Function} Fixer function + * @private + */ + function getFixerFunction( + styleType, + previousItemToken, + commaToken, + currentItemToken, + ) { + const text = + sourceCode.text.slice( + previousItemToken.range[1], + commaToken.range[0], + ) + + sourceCode.text.slice( + commaToken.range[1], + currentItemToken.range[0], + ); + const range = [ + previousItemToken.range[1], + currentItemToken.range[0], + ]; + + return function (fixer) { + return fixer.replaceTextRange( + range, + getReplacedText(styleType, text), + ); + }; + } + + /** + * Validates the spacing around single items in lists. + * @param {Token} previousItemToken The last token from the previous item. + * @param {Token} commaToken The token representing the comma. + * @param {Token} currentItemToken The first token of the current item. + * @param {Token} reportItem The item to use when reporting an error. + * @returns {void} + * @private + */ + function validateCommaItemSpacing( + previousItemToken, + commaToken, + currentItemToken, + reportItem, + ) { + // if single line + if ( + astUtils.isTokenOnSameLine(commaToken, currentItemToken) && + astUtils.isTokenOnSameLine(previousItemToken, commaToken) + ) { + // do nothing. + } else if ( + !astUtils.isTokenOnSameLine(commaToken, currentItemToken) && + !astUtils.isTokenOnSameLine(previousItemToken, commaToken) + ) { + const comment = sourceCode.getCommentsAfter(commaToken)[0]; + const styleType = + comment && + comment.type === "Block" && + astUtils.isTokenOnSameLine(commaToken, comment) + ? style + : "between"; + + // lone comma + context.report({ + node: reportItem, + loc: commaToken.loc, + messageId: "unexpectedLineBeforeAndAfterComma", + fix: getFixerFunction( + styleType, + previousItemToken, + commaToken, + currentItemToken, + ), + }); + } else if ( + style === "first" && + !astUtils.isTokenOnSameLine(commaToken, currentItemToken) + ) { + context.report({ + node: reportItem, + loc: commaToken.loc, + messageId: "expectedCommaFirst", + fix: getFixerFunction( + style, + previousItemToken, + commaToken, + currentItemToken, + ), + }); + } else if ( + style === "last" && + astUtils.isTokenOnSameLine(commaToken, currentItemToken) + ) { + context.report({ + node: reportItem, + loc: commaToken.loc, + messageId: "expectedCommaLast", + fix: getFixerFunction( + style, + previousItemToken, + commaToken, + currentItemToken, + ), + }); + } + } + + /** + * Checks the comma placement with regards to a declaration/property/element + * @param {ASTNode} node The binary expression node to check + * @param {string} property The property of the node containing child nodes. + * @private + * @returns {void} + */ + function validateComma(node, property) { + const items = node[property], + arrayLiteral = + node.type === "ArrayExpression" || + node.type === "ArrayPattern"; + + if (items.length > 1 || arrayLiteral) { + // seed as opening [ + let previousItemToken = sourceCode.getFirstToken(node); + + items.forEach(item => { + const commaToken = item + ? sourceCode.getTokenBefore(item) + : previousItemToken, + currentItemToken = item + ? sourceCode.getFirstToken(item) + : sourceCode.getTokenAfter(commaToken), + reportItem = item || currentItemToken; + + /* + * This works by comparing three token locations: + * - previousItemToken is the last token of the previous item + * - commaToken is the location of the comma before the current item + * - currentItemToken is the first token of the current item + * + * These values get switched around if item is undefined. + * previousItemToken will refer to the last token not belonging + * to the current item, which could be a comma or an opening + * square bracket. currentItemToken could be a comma. + * + * All comparisons are done based on these tokens directly, so + * they are always valid regardless of an undefined item. + */ + if (astUtils.isCommaToken(commaToken)) { + validateCommaItemSpacing( + previousItemToken, + commaToken, + currentItemToken, + reportItem, + ); + } + + if (item) { + const tokenAfterItem = sourceCode.getTokenAfter( + item, + astUtils.isNotClosingParenToken, + ); + + previousItemToken = tokenAfterItem + ? sourceCode.getTokenBefore(tokenAfterItem) + : sourceCode.ast.tokens.at(-1); + } else { + previousItemToken = currentItemToken; + } + }); + + /* + * Special case for array literals that have empty last items, such + * as [ 1, 2, ]. These arrays only have two items show up in the + * AST, so we need to look at the token to verify that there's no + * dangling comma. + */ + if (arrayLiteral) { + const lastToken = sourceCode.getLastToken(node), + nextToLastToken = sourceCode.getTokenBefore(lastToken); + + if (astUtils.isCommaToken(nextToLastToken)) { + validateCommaItemSpacing( + sourceCode.getTokenBefore(nextToLastToken), + nextToLastToken, + lastToken, + lastToken, + ); + } + } + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + const nodes = {}; + + if (!exceptions.VariableDeclaration) { + nodes.VariableDeclaration = function (node) { + validateComma(node, "declarations"); + }; + } + if (!exceptions.ObjectExpression) { + nodes.ObjectExpression = function (node) { + validateComma(node, "properties"); + }; + } + if (!exceptions.ObjectPattern) { + nodes.ObjectPattern = function (node) { + validateComma(node, "properties"); + }; + } + if (!exceptions.ArrayExpression) { + nodes.ArrayExpression = function (node) { + validateComma(node, "elements"); + }; + } + if (!exceptions.ArrayPattern) { + nodes.ArrayPattern = function (node) { + validateComma(node, "elements"); + }; + } + if (!exceptions.FunctionDeclaration) { + nodes.FunctionDeclaration = function (node) { + validateComma(node, "params"); + }; + } + if (!exceptions.FunctionExpression) { + nodes.FunctionExpression = function (node) { + validateComma(node, "params"); + }; + } + if (!exceptions.ArrowFunctionExpression) { + nodes.ArrowFunctionExpression = function (node) { + validateComma(node, "params"); + }; + } + if (!exceptions.CallExpression) { + nodes.CallExpression = function (node) { + validateComma(node, "arguments"); + }; + } + if (!exceptions.ImportDeclaration) { + nodes.ImportDeclaration = function (node) { + validateComma(node, "specifiers"); + }; + } + if (!exceptions.NewExpression) { + nodes.NewExpression = function (node) { + validateComma(node, "arguments"); + }; + } + + return nodes; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/complexity.js b/tools/ui/node_modules/eslint/lib/rules/complexity.js new file mode 100644 index 0000000000000000000000000000000000000000..23a018b9768f94f1d988e813dd83ce0d2ed45591 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/complexity.js @@ -0,0 +1,201 @@ +/** + * @fileoverview Counts the cyclomatic complexity of each function of the script. See http://en.wikipedia.org/wiki/Cyclomatic_complexity. + * Counts the number of if, conditional, for, while, try, switch/case, + * @author Patrick Brosset + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const { upperCaseFirst } = require("../shared/string-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const THRESHOLD_DEFAULT = 20; + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [THRESHOLD_DEFAULT], + + docs: { + description: + "Enforce a maximum cyclomatic complexity allowed in a program", + recommended: false, + url: "https://eslint.org/docs/latest/rules/complexity", + }, + + schema: [ + { + oneOf: [ + { + type: "integer", + minimum: 0, + }, + { + type: "object", + properties: { + maximum: { + type: "integer", + minimum: 0, + }, + max: { + type: "integer", + minimum: 0, + }, + variant: { + enum: ["classic", "modified"], + }, + }, + additionalProperties: false, + }, + ], + }, + ], + + messages: { + complex: + "{{name}} has a complexity of {{complexity}}. Maximum allowed is {{max}}.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const option = context.options[0]; + let threshold = THRESHOLD_DEFAULT; + let VARIANT = "classic"; + + if (typeof option === "object") { + if ( + Object.hasOwn(option, "maximum") || + Object.hasOwn(option, "max") + ) { + threshold = option.maximum || option.max; + } + + if (Object.hasOwn(option, "variant")) { + VARIANT = option.variant; + } + } else if (typeof option === "number") { + threshold = option; + } + + const IS_MODIFIED_COMPLEXITY = VARIANT === "modified"; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + // Using a stack to store complexity per code path + const complexities = []; + + /** + * Increase the complexity of the code path in context + * @returns {void} + * @private + */ + function increaseComplexity() { + complexities[complexities.length - 1]++; + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + onCodePathStart() { + // The initial complexity is 1, representing one execution path in the CodePath + complexities.push(1); + }, + + // Each branching in the code adds 1 to the complexity + CatchClause: increaseComplexity, + ConditionalExpression: increaseComplexity, + LogicalExpression: increaseComplexity, + ForStatement: increaseComplexity, + ForInStatement: increaseComplexity, + ForOfStatement: increaseComplexity, + IfStatement: increaseComplexity, + WhileStatement: increaseComplexity, + DoWhileStatement: increaseComplexity, + AssignmentPattern: increaseComplexity, + + // Avoid `default` + "SwitchCase[test]": () => + IS_MODIFIED_COMPLEXITY || increaseComplexity(), + SwitchStatement: () => + IS_MODIFIED_COMPLEXITY && increaseComplexity(), + + // Logical assignment operators have short-circuiting behavior + AssignmentExpression(node) { + if (astUtils.isLogicalAssignmentOperator(node.operator)) { + increaseComplexity(); + } + }, + + MemberExpression(node) { + if (node.optional === true) { + increaseComplexity(); + } + }, + + CallExpression(node) { + if (node.optional === true) { + increaseComplexity(); + } + }, + + onCodePathEnd(codePath, node) { + const complexity = complexities.pop(); + + /* + * This rule only evaluates complexity of functions, so "program" is excluded. + * Class field initializers and class static blocks are implicit functions. Therefore, + * they shouldn't contribute to the enclosing function's complexity, but their + * own complexity should be evaluated. + */ + if ( + codePath.origin !== "function" && + codePath.origin !== "class-field-initializer" && + codePath.origin !== "class-static-block" + ) { + return; + } + + if (complexity > threshold) { + let name; + let loc = node.loc; + + if (codePath.origin === "class-field-initializer") { + name = "class field initializer"; + } else if (codePath.origin === "class-static-block") { + name = "class static block"; + loc = sourceCode.getFirstToken(node).loc; + } else { + name = astUtils.getFunctionNameWithKind(node); + loc = astUtils.getFunctionHeadLoc(node, sourceCode); + } + + context.report({ + node, + loc, + messageId: "complex", + data: { + name: upperCaseFirst(name), + complexity, + max: threshold, + }, + }); + } + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/computed-property-spacing.js b/tools/ui/node_modules/eslint/lib/rules/computed-property-spacing.js new file mode 100644 index 0000000000000000000000000000000000000000..8712626463fde0cb51c0c9a528a4578ba5b53ddc --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/computed-property-spacing.js @@ -0,0 +1,251 @@ +/** + * @fileoverview Disallows or enforces spaces inside computed properties. + * @author Jamund Ferguson + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "computed-property-spacing", + url: "https://eslint.style/rules/computed-property-spacing", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Enforce consistent spacing inside computed property brackets", + recommended: false, + url: "https://eslint.org/docs/latest/rules/computed-property-spacing", + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["always", "never"], + }, + { + type: "object", + properties: { + enforceForClassMembers: { + type: "boolean", + default: true, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + unexpectedSpaceBefore: + "There should be no space before '{{tokenValue}}'.", + unexpectedSpaceAfter: + "There should be no space after '{{tokenValue}}'.", + + missingSpaceBefore: "A space is required before '{{tokenValue}}'.", + missingSpaceAfter: "A space is required after '{{tokenValue}}'.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const propertyNameMustBeSpaced = context.options[0] === "always"; // default is "never" + const enforceForClassMembers = + !context.options[1] || context.options[1].enforceForClassMembers; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Reports that there shouldn't be a space after the first token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @param {Token} tokenAfter The token after `token`. + * @returns {void} + */ + function reportNoBeginningSpace(node, token, tokenAfter) { + context.report({ + node, + loc: { start: token.loc.end, end: tokenAfter.loc.start }, + messageId: "unexpectedSpaceAfter", + data: { + tokenValue: token.value, + }, + fix(fixer) { + return fixer.removeRange([ + token.range[1], + tokenAfter.range[0], + ]); + }, + }); + } + + /** + * Reports that there shouldn't be a space before the last token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @param {Token} tokenBefore The token before `token`. + * @returns {void} + */ + function reportNoEndingSpace(node, token, tokenBefore) { + context.report({ + node, + loc: { start: tokenBefore.loc.end, end: token.loc.start }, + messageId: "unexpectedSpaceBefore", + data: { + tokenValue: token.value, + }, + fix(fixer) { + return fixer.removeRange([ + tokenBefore.range[1], + token.range[0], + ]); + }, + }); + } + + /** + * Reports that there should be a space after the first token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportRequiredBeginningSpace(node, token) { + context.report({ + node, + loc: token.loc, + messageId: "missingSpaceAfter", + data: { + tokenValue: token.value, + }, + fix(fixer) { + return fixer.insertTextAfter(token, " "); + }, + }); + } + + /** + * Reports that there should be a space before the last token + * @param {ASTNode} node The node to report in the event of an error. + * @param {Token} token The token to use for the report. + * @returns {void} + */ + function reportRequiredEndingSpace(node, token) { + context.report({ + node, + loc: token.loc, + messageId: "missingSpaceBefore", + data: { + tokenValue: token.value, + }, + fix(fixer) { + return fixer.insertTextBefore(token, " "); + }, + }); + } + + /** + * Returns a function that checks the spacing of a node on the property name + * that was passed in. + * @param {string} propertyName The property on the node to check for spacing + * @returns {Function} A function that will check spacing on a node + */ + function checkSpacing(propertyName) { + return function (node) { + if (!node.computed) { + return; + } + + const property = node[propertyName]; + + const before = sourceCode.getTokenBefore( + property, + astUtils.isOpeningBracketToken, + ), + first = sourceCode.getTokenAfter(before, { + includeComments: true, + }), + after = sourceCode.getTokenAfter( + property, + astUtils.isClosingBracketToken, + ), + last = sourceCode.getTokenBefore(after, { + includeComments: true, + }); + + if (astUtils.isTokenOnSameLine(before, first)) { + if (propertyNameMustBeSpaced) { + if ( + !sourceCode.isSpaceBetweenTokens(before, first) && + astUtils.isTokenOnSameLine(before, first) + ) { + reportRequiredBeginningSpace(node, before); + } + } else { + if (sourceCode.isSpaceBetweenTokens(before, first)) { + reportNoBeginningSpace(node, before, first); + } + } + } + + if (astUtils.isTokenOnSameLine(last, after)) { + if (propertyNameMustBeSpaced) { + if ( + !sourceCode.isSpaceBetweenTokens(last, after) && + astUtils.isTokenOnSameLine(last, after) + ) { + reportRequiredEndingSpace(node, after); + } + } else { + if (sourceCode.isSpaceBetweenTokens(last, after)) { + reportNoEndingSpace(node, after, last); + } + } + } + }; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + const listeners = { + Property: checkSpacing("key"), + MemberExpression: checkSpacing("property"), + }; + + if (enforceForClassMembers) { + listeners.MethodDefinition = listeners.PropertyDefinition = + listeners.Property; + } + + return listeners; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/consistent-return.js b/tools/ui/node_modules/eslint/lib/rules/consistent-return.js new file mode 100644 index 0000000000000000000000000000000000000000..6407739b73bb07b88693346658069128cdec97a2 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/consistent-return.js @@ -0,0 +1,221 @@ +/** + * @fileoverview Rule to flag consistent return values + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const { upperCaseFirst } = require("../shared/string-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks all segments in a set and returns true if all are unreachable. + * @param {Set} segments The segments to check. + * @returns {boolean} True if all segments are unreachable; false otherwise. + */ +function areAllSegmentsUnreachable(segments) { + for (const segment of segments) { + if (segment.reachable) { + return false; + } + } + + return true; +} + +/** + * Checks whether a given node is a `constructor` method in an ES6 class + * @param {ASTNode} node A node to check + * @returns {boolean} `true` if the node is a `constructor` method + */ +function isClassConstructor(node) { + return ( + node.type === "FunctionExpression" && + node.parent && + node.parent.type === "MethodDefinition" && + node.parent.kind === "constructor" + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Require `return` statements to either always or never specify values", + recommended: false, + url: "https://eslint.org/docs/latest/rules/consistent-return", + }, + + schema: [ + { + type: "object", + properties: { + treatUndefinedAsUnspecified: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + defaultOptions: [{ treatUndefinedAsUnspecified: false }], + + messages: { + missingReturn: "Expected to return a value at the end of {{name}}.", + missingReturnValue: "{{name}} expected a return value.", + unexpectedReturnValue: "{{name}} expected no return value.", + }, + }, + + create(context) { + const [{ treatUndefinedAsUnspecified }] = context.options; + let funcInfo = null; + + /** + * Checks whether of not the implicit returning is consistent if the last + * code path segment is reachable. + * @param {ASTNode} node A program/function node to check. + * @returns {void} + */ + function checkLastSegment(node) { + let loc, name; + + /* + * Skip if it expected no return value or unreachable. + * When unreachable, all paths are returned or thrown. + */ + if ( + !funcInfo.hasReturnValue || + areAllSegmentsUnreachable(funcInfo.currentSegments) || + astUtils.isES5Constructor(node) || + isClassConstructor(node) + ) { + return; + } + + // Adjust a location and a message. + if (node.type === "Program") { + // The head of program. + loc = { line: 1, column: 0 }; + name = "program"; + } else if (node.type === "ArrowFunctionExpression") { + // `=>` token + loc = context.sourceCode.getTokenBefore( + node.body, + astUtils.isArrowToken, + ).loc; + } else if ( + node.parent.type === "MethodDefinition" || + (node.parent.type === "Property" && node.parent.method) + ) { + // Method name. + loc = node.parent.key.loc; + } else { + // Function name or `function` keyword. + loc = (node.id || context.sourceCode.getFirstToken(node)).loc; + } + + if (!name) { + name = astUtils.getFunctionNameWithKind(node); + } + + // Reports. + context.report({ + node, + loc, + messageId: "missingReturn", + data: { name }, + }); + } + + return { + // Initializes/Disposes state of each code path. + onCodePathStart(codePath, node) { + funcInfo = { + upper: funcInfo, + codePath, + hasReturn: false, + hasReturnValue: false, + messageId: "", + node, + currentSegments: new Set(), + }; + }, + onCodePathEnd() { + funcInfo = funcInfo.upper; + }, + + onUnreachableCodePathSegmentStart(segment) { + funcInfo.currentSegments.add(segment); + }, + + onUnreachableCodePathSegmentEnd(segment) { + funcInfo.currentSegments.delete(segment); + }, + + onCodePathSegmentStart(segment) { + funcInfo.currentSegments.add(segment); + }, + + onCodePathSegmentEnd(segment) { + funcInfo.currentSegments.delete(segment); + }, + + // Reports a given return statement if it's inconsistent. + ReturnStatement(node) { + const argument = node.argument; + let hasReturnValue = Boolean(argument); + + if (treatUndefinedAsUnspecified && hasReturnValue) { + hasReturnValue = + !astUtils.isSpecificId(argument, "undefined") && + argument.operator !== "void"; + } + + if (!funcInfo.hasReturn) { + funcInfo.hasReturn = true; + funcInfo.hasReturnValue = hasReturnValue; + funcInfo.messageId = hasReturnValue + ? "missingReturnValue" + : "unexpectedReturnValue"; + funcInfo.data = { + name: + funcInfo.node.type === "Program" + ? "Program" + : upperCaseFirst( + astUtils.getFunctionNameWithKind( + funcInfo.node, + ), + ), + }; + } else if (funcInfo.hasReturnValue !== hasReturnValue) { + context.report({ + node, + messageId: funcInfo.messageId, + data: funcInfo.data, + }); + } + }, + + // Reports a given program/function if the implicit returning is not consistent. + "Program:exit": checkLastSegment, + "FunctionDeclaration:exit": checkLastSegment, + "FunctionExpression:exit": checkLastSegment, + "ArrowFunctionExpression:exit": checkLastSegment, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/consistent-this.js b/tools/ui/node_modules/eslint/lib/rules/consistent-this.js new file mode 100644 index 0000000000000000000000000000000000000000..8e9372d299ff6916442e9a6e9d7685afceb29bea --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/consistent-this.js @@ -0,0 +1,179 @@ +/** + * @fileoverview Rule to enforce consistent naming of "this" context variables + * @author Raphael Pigulla + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Enforce consistent naming when capturing the current execution context", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/consistent-this", + }, + + schema: { + type: "array", + items: { + type: "string", + minLength: 1, + }, + uniqueItems: true, + }, + + defaultOptions: ["that"], + + messages: { + aliasNotAssignedToThis: + "Designated alias '{{name}}' is not assigned to 'this'.", + unexpectedAlias: "Unexpected alias '{{name}}' for 'this'.", + }, + }, + + create(context) { + const aliases = context.options; + const sourceCode = context.sourceCode; + + /** + * Reports that a variable declarator or assignment expression is assigning + * a non-'this' value to the specified alias. + * @param {ASTNode} node The assigning node. + * @param {string} name the name of the alias that was incorrectly used. + * @returns {void} + */ + function reportBadAssignment(node, name) { + context.report({ + node, + messageId: "aliasNotAssignedToThis", + data: { name }, + }); + } + + /** + * Checks that an assignment to an identifier only assigns 'this' to the + * appropriate alias, and the alias is only assigned to 'this'. + * @param {ASTNode} node The assigning node. + * @param {Identifier} name The name of the variable assigned to. + * @param {Expression} value The value of the assignment. + * @returns {void} + */ + function checkAssignment(node, name, value) { + const isThis = value.type === "ThisExpression"; + + if (aliases.includes(name)) { + if (!isThis || (node.operator && node.operator !== "=")) { + reportBadAssignment(node, name); + } + } else if (isThis) { + context.report({ + node, + messageId: "unexpectedAlias", + data: { name }, + }); + } + } + + /** + * Ensures that a variable declaration of the alias in a program or function + * is assigned to the correct value. + * @param {string} alias alias the check the assignment of. + * @param {Object} scope scope of the current code we are checking. + * @private + * @returns {void} + */ + function checkWasAssigned(alias, scope) { + const variable = scope.set.get(alias); + + if (!variable) { + return; + } + + if ( + variable.defs.some( + def => + def.node.type === "VariableDeclarator" && + def.node.init !== null, + ) + ) { + return; + } + + /* + * The alias has been declared and not assigned: check it was + * assigned later in the same scope. + */ + if ( + !variable.references.some(reference => { + const write = reference.writeExpr; + + return ( + reference.from === scope && + write && + write.type === "ThisExpression" && + write.parent.operator === "=" + ); + }) + ) { + variable.defs + .map(def => def.node) + .forEach(node => { + reportBadAssignment(node, alias); + }); + } + } + + /** + * Check each alias to ensure that is was assigned to the correct value. + * @param {ASTNode} node The node that represents the scope to check. + * @returns {void} + */ + function ensureWasAssigned(node) { + const scope = sourceCode.getScope(node); + + // if this is program scope we also need to check module scope + const extraScope = + node.type === "Program" && node.sourceType === "module" + ? scope.childScopes[0] + : null; + + aliases.forEach(alias => { + checkWasAssigned(alias, scope); + + if (extraScope) { + checkWasAssigned(alias, extraScope); + } + }); + } + + return { + "Program:exit": ensureWasAssigned, + "FunctionExpression:exit": ensureWasAssigned, + "FunctionDeclaration:exit": ensureWasAssigned, + + VariableDeclarator(node) { + const id = node.id; + const isDestructuring = + id.type === "ArrayPattern" || id.type === "ObjectPattern"; + + if (node.init !== null && !isDestructuring) { + checkAssignment(node, id.name, node.init); + } + }, + + AssignmentExpression(node) { + if (node.left.type === "Identifier") { + checkAssignment(node, node.left.name, node.right); + } + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/constructor-super.js b/tools/ui/node_modules/eslint/lib/rules/constructor-super.js new file mode 100644 index 0000000000000000000000000000000000000000..2262677d3112bf011ceecdf43f548709bfc75bad --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/constructor-super.js @@ -0,0 +1,453 @@ +/** + * @fileoverview A rule to verify `super()` callings in constructor. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not a given node is a constructor. + * @param {ASTNode} node A node to check. This node type is one of + * `Program`, `FunctionDeclaration`, `FunctionExpression`, and + * `ArrowFunctionExpression`. + * @returns {boolean} `true` if the node is a constructor. + */ +function isConstructorFunction(node) { + return ( + node.type === "FunctionExpression" && + node.parent.type === "MethodDefinition" && + node.parent.kind === "constructor" + ); +} + +/** + * Checks whether a given node can be a constructor or not. + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node can be a constructor. + */ +function isPossibleConstructor(node) { + if (!node) { + return false; + } + + switch (node.type) { + case "ClassExpression": + case "FunctionExpression": + case "ThisExpression": + case "MemberExpression": + case "CallExpression": + case "NewExpression": + case "ChainExpression": + case "YieldExpression": + case "TaggedTemplateExpression": + case "MetaProperty": + return true; + + case "Identifier": + return node.name !== "undefined"; + + case "AssignmentExpression": + if (["=", "&&="].includes(node.operator)) { + return isPossibleConstructor(node.right); + } + + if (["||=", "??="].includes(node.operator)) { + return ( + isPossibleConstructor(node.left) || + isPossibleConstructor(node.right) + ); + } + + /** + * All other assignment operators are mathematical assignment operators (arithmetic or bitwise). + * An assignment expression with a mathematical operator can either evaluate to a primitive value, + * or throw, depending on the operands. Thus, it cannot evaluate to a constructor function. + */ + return false; + + case "LogicalExpression": + /* + * If the && operator short-circuits, the left side was falsy and therefore not a constructor, and if + * it doesn't short-circuit, it takes the value from the right side, so the right side must always be a + * possible constructor. A future improvement could verify that the left side could be truthy by + * excluding falsy literals. + */ + if (node.operator === "&&") { + return isPossibleConstructor(node.right); + } + + return ( + isPossibleConstructor(node.left) || + isPossibleConstructor(node.right) + ); + + case "ConditionalExpression": + return ( + isPossibleConstructor(node.alternate) || + isPossibleConstructor(node.consequent) + ); + + case "SequenceExpression": { + const lastExpression = node.expressions.at(-1); + + return isPossibleConstructor(lastExpression); + } + + default: + return false; + } +} + +/** + * A class to store information about a code path segment. + */ +class SegmentInfo { + /** + * Indicates if super() is called in all code paths. + * @type {boolean} + */ + calledInEveryPaths = false; + + /** + * Indicates if super() is called in any code paths. + * @type {boolean} + */ + calledInSomePaths = false; + + /** + * The nodes which have been validated and don't need to be reconsidered. + * @type {ASTNode[]} + */ + validNodes = []; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: "Require `super()` calls in constructors", + recommended: true, + url: "https://eslint.org/docs/latest/rules/constructor-super", + }, + + schema: [], + + messages: { + missingSome: "Lacked a call of 'super()' in some code paths.", + missingAll: "Expected to call 'super()'.", + + duplicate: "Unexpected duplicate 'super()'.", + badSuper: + "Unexpected 'super()' because 'super' is not a constructor.", + }, + }, + + create(context) { + /* + * {{hasExtends: boolean, scope: Scope, codePath: CodePath}[]} + * Information for each constructor. + * - upper: Information of the upper constructor. + * - hasExtends: A flag which shows whether own class has a valid `extends` + * part. + * - scope: The scope of own class. + * - codePath: The code path object of the constructor. + */ + let funcInfo = null; + + /** + * @type {Record} + */ + const segInfoMap = Object.create(null); + + /** + * Gets the flag which shows `super()` is called in some paths. + * @param {CodePathSegment} segment A code path segment to get. + * @returns {boolean} The flag which shows `super()` is called in some paths + */ + function isCalledInSomePath(segment) { + return ( + segment.reachable && segInfoMap[segment.id].calledInSomePaths + ); + } + + /** + * Determines if a segment has been seen in the traversal. + * @param {CodePathSegment} segment A code path segment to check. + * @returns {boolean} `true` if the segment has been seen. + */ + function hasSegmentBeenSeen(segment) { + return !!segInfoMap[segment.id]; + } + + /** + * Gets the flag which shows `super()` is called in all paths. + * @param {CodePathSegment} segment A code path segment to get. + * @returns {boolean} The flag which shows `super()` is called in all paths. + */ + function isCalledInEveryPath(segment) { + return ( + segment.reachable && segInfoMap[segment.id].calledInEveryPaths + ); + } + + return { + /** + * Stacks a constructor information. + * @param {CodePath} codePath A code path which was started. + * @param {ASTNode} node The current node. + * @returns {void} + */ + onCodePathStart(codePath, node) { + if (isConstructorFunction(node)) { + // Class > ClassBody > MethodDefinition > FunctionExpression + const classNode = node.parent.parent.parent; + const superClass = classNode.superClass; + + funcInfo = { + upper: funcInfo, + isConstructor: true, + hasExtends: Boolean(superClass), + superIsConstructor: isPossibleConstructor(superClass), + codePath, + currentSegments: new Set(), + }; + } else { + funcInfo = { + upper: funcInfo, + isConstructor: false, + hasExtends: false, + superIsConstructor: false, + codePath, + currentSegments: new Set(), + }; + } + }, + + /** + * Pops a constructor information. + * And reports if `super()` lacked. + * @param {CodePath} codePath A code path which was ended. + * @param {ASTNode} node The current node. + * @returns {void} + */ + onCodePathEnd(codePath, node) { + const hasExtends = funcInfo.hasExtends; + + // Pop. + funcInfo = funcInfo.upper; + + if (!hasExtends) { + return; + } + + // Reports if `super()` lacked. + const returnedSegments = codePath.returnedSegments; + const calledInEveryPaths = + returnedSegments.every(isCalledInEveryPath); + const calledInSomePaths = + returnedSegments.some(isCalledInSomePath); + + if (!calledInEveryPaths) { + context.report({ + messageId: calledInSomePaths + ? "missingSome" + : "missingAll", + node: node.parent, + }); + } + }, + + /** + * Initialize information of a given code path segment. + * @param {CodePathSegment} segment A code path segment to initialize. + * @param {CodePathSegment} node Node that starts the segment. + * @returns {void} + */ + onCodePathSegmentStart(segment, node) { + funcInfo.currentSegments.add(segment); + + if (!(funcInfo.isConstructor && funcInfo.hasExtends)) { + return; + } + + // Initialize info. + const info = (segInfoMap[segment.id] = new SegmentInfo()); + + const seenPrevSegments = + segment.prevSegments.filter(hasSegmentBeenSeen); + + // When there are previous segments, aggregates these. + if (seenPrevSegments.length > 0) { + info.calledInSomePaths = + seenPrevSegments.some(isCalledInSomePath); + info.calledInEveryPaths = + seenPrevSegments.every(isCalledInEveryPath); + } + + /* + * ForStatement > *.update segments are a special case as they are created in advance, + * without seen previous segments. Since they logically don't affect `calledInEveryPaths` + * calculations, and they can never be a lone previous segment of another one, we'll set + * their `calledInEveryPaths` to `true` to effectively ignore them in those calculations. + * . + */ + if ( + node.parent && + node.parent.type === "ForStatement" && + node.parent.update === node + ) { + info.calledInEveryPaths = true; + } + }, + + onUnreachableCodePathSegmentStart(segment) { + funcInfo.currentSegments.add(segment); + }, + + onUnreachableCodePathSegmentEnd(segment) { + funcInfo.currentSegments.delete(segment); + }, + + onCodePathSegmentEnd(segment) { + funcInfo.currentSegments.delete(segment); + }, + + /** + * Update information of the code path segment when a code path was + * looped. + * @param {CodePathSegment} fromSegment The code path segment of the + * end of a loop. + * @param {CodePathSegment} toSegment A code path segment of the head + * of a loop. + * @returns {void} + */ + onCodePathSegmentLoop(fromSegment, toSegment) { + if (!(funcInfo.isConstructor && funcInfo.hasExtends)) { + return; + } + + funcInfo.codePath.traverseSegments( + { first: toSegment, last: fromSegment }, + (segment, controller) => { + const info = segInfoMap[segment.id]; + + // skip segments after the loop + if (!info) { + controller.skip(); + return; + } + + const seenPrevSegments = + segment.prevSegments.filter(hasSegmentBeenSeen); + const calledInSomePreviousPaths = + seenPrevSegments.some(isCalledInSomePath); + const calledInEveryPreviousPaths = + seenPrevSegments.every(isCalledInEveryPath); + + info.calledInSomePaths ||= calledInSomePreviousPaths; + info.calledInEveryPaths ||= calledInEveryPreviousPaths; + + // If flags become true anew, reports the valid nodes. + if (calledInSomePreviousPaths) { + const nodes = info.validNodes; + + info.validNodes = []; + + for (let i = 0; i < nodes.length; ++i) { + const node = nodes[i]; + + context.report({ + messageId: "duplicate", + node, + }); + } + } + }, + ); + }, + + /** + * Checks for a call of `super()`. + * @param {ASTNode} node A CallExpression node to check. + * @returns {void} + */ + "CallExpression:exit"(node) { + if (!(funcInfo.isConstructor && funcInfo.hasExtends)) { + return; + } + + // Skips except `super()`. + if (node.callee.type !== "Super") { + return; + } + + // Reports if needed. + const segments = funcInfo.currentSegments; + let duplicate = false; + let info = null; + + for (const segment of segments) { + if (segment.reachable) { + info = segInfoMap[segment.id]; + + duplicate = duplicate || info.calledInSomePaths; + info.calledInSomePaths = info.calledInEveryPaths = true; + } + } + + if (info) { + if (duplicate) { + context.report({ + messageId: "duplicate", + node, + }); + } else if (!funcInfo.superIsConstructor) { + context.report({ + messageId: "badSuper", + node, + }); + } else { + info.validNodes.push(node); + } + } + }, + + /** + * Set the mark to the returned path as `super()` was called. + * @param {ASTNode} node A ReturnStatement node to check. + * @returns {void} + */ + ReturnStatement(node) { + if (!(funcInfo.isConstructor && funcInfo.hasExtends)) { + return; + } + + // Skips if no argument. + if (!node.argument) { + return; + } + + // Returning argument is a substitute of 'super()'. + const segments = funcInfo.currentSegments; + + for (const segment of segments) { + if (segment.reachable) { + const info = segInfoMap[segment.id]; + + info.calledInSomePaths = info.calledInEveryPaths = true; + } + } + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/curly.js b/tools/ui/node_modules/eslint/lib/rules/curly.js new file mode 100644 index 0000000000000000000000000000000000000000..fd4438d31a9421b6c2b87f9e1960a3d78fa1ab02 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/curly.js @@ -0,0 +1,425 @@ +/** + * @fileoverview Rule to flag statements without curly braces + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Enforce consistent brace style for all control statements", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/curly", + }, + + schema: { + anyOf: [ + { + type: "array", + items: [ + { + enum: ["all"], + }, + ], + minItems: 0, + maxItems: 1, + }, + { + type: "array", + items: [ + { + enum: ["multi", "multi-line", "multi-or-nest"], + }, + { + enum: ["consistent"], + }, + ], + minItems: 0, + maxItems: 2, + }, + ], + }, + + defaultOptions: ["all"], + + fixable: "code", + + messages: { + missingCurlyAfter: "Expected { after '{{name}}'.", + missingCurlyAfterCondition: + "Expected { after '{{name}}' condition.", + unexpectedCurlyAfter: "Unnecessary { after '{{name}}'.", + unexpectedCurlyAfterCondition: + "Unnecessary { after '{{name}}' condition.", + }, + }, + + create(context) { + const multiOnly = context.options[0] === "multi"; + const multiLine = context.options[0] === "multi-line"; + const multiOrNest = context.options[0] === "multi-or-nest"; + const consistent = context.options[1] === "consistent"; + + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Determines if a given node is a one-liner that's on the same line as it's preceding code. + * @param {ASTNode} node The node to check. + * @returns {boolean} True if the node is a one-liner that's on the same line as it's preceding code. + * @private + */ + function isCollapsedOneLiner(node) { + const before = sourceCode.getTokenBefore(node); + const last = sourceCode.getLastToken(node); + const lastExcludingSemicolon = astUtils.isSemicolonToken(last) + ? sourceCode.getTokenBefore(last) + : last; + + return ( + before.loc.start.line === lastExcludingSemicolon.loc.end.line + ); + } + + /** + * Determines if a given node is a one-liner. + * @param {ASTNode} node The node to check. + * @returns {boolean} True if the node is a one-liner. + * @private + */ + function isOneLiner(node) { + if (node.type === "EmptyStatement") { + return true; + } + + const first = sourceCode.getFirstToken(node); + const last = sourceCode.getLastToken(node); + const lastExcludingSemicolon = astUtils.isSemicolonToken(last) + ? sourceCode.getTokenBefore(last) + : last; + + return first.loc.start.line === lastExcludingSemicolon.loc.end.line; + } + + /** + * Determines if a semicolon needs to be inserted after removing a set of curly brackets, in order to avoid a SyntaxError. + * @param {Token} closingBracket The } token + * @returns {boolean} `true` if a semicolon needs to be inserted after the last statement in the block. + */ + function needsSemicolon(closingBracket) { + const tokenBefore = sourceCode.getTokenBefore(closingBracket); + const tokenAfter = sourceCode.getTokenAfter(closingBracket); + const lastBlockNode = sourceCode.getNodeByRangeIndex( + tokenBefore.range[0], + ); + + if (astUtils.isSemicolonToken(tokenBefore)) { + // If the last statement already has a semicolon, don't add another one. + return false; + } + + if (!tokenAfter) { + // If there are no statements after this block, there is no need to add a semicolon. + return false; + } + + if ( + lastBlockNode.type === "BlockStatement" && + lastBlockNode.parent.type !== "FunctionExpression" && + lastBlockNode.parent.type !== "ArrowFunctionExpression" + ) { + /* + * If the last node surrounded by curly brackets is a BlockStatement (other than a FunctionExpression or an ArrowFunctionExpression), + * don't insert a semicolon. Otherwise, the semicolon would be parsed as a separate statement, which would cause + * a SyntaxError if it was followed by `else`. + */ + return false; + } + + if (tokenBefore.loc.end.line === tokenAfter.loc.start.line) { + // If the next token is on the same line, insert a semicolon. + return true; + } + + if (/^[([/`+-]/u.test(tokenAfter.value)) { + // If the next token starts with a character that would disrupt ASI, insert a semicolon. + return true; + } + + if ( + tokenBefore.type === "Punctuator" && + (tokenBefore.value === "++" || tokenBefore.value === "--") + ) { + // If the last token is ++ or --, insert a semicolon to avoid disrupting ASI. + return true; + } + + // Otherwise, do not insert a semicolon. + return false; + } + + /** + * Prepares to check the body of a node to see if it's a block statement. + * @param {ASTNode} node The node to report if there's a problem. + * @param {ASTNode} body The body node to check for blocks. + * @param {string} name The name to report if there's a problem. + * @param {{ condition: boolean }} opts Options to pass to the report functions + * @returns {Object} a prepared check object, with "actual", "expected", "check" properties. + * "actual" will be `true` or `false` whether the body is already a block statement. + * "expected" will be `true` or `false` if the body should be a block statement or not, or + * `null` if it doesn't matter, depending on the rule options. It can be modified to change + * the final behavior of "check". + * "check" will be a function reporting appropriate problems depending on the other + * properties. + */ + function prepareCheck(node, body, name, opts) { + const hasBlock = body.type === "BlockStatement"; + let expected = null; + + if ( + hasBlock && + (body.body.length !== 1 || + astUtils.areBracesNecessary(body, sourceCode)) + ) { + expected = true; + } else if (multiOnly) { + expected = false; + } else if (multiLine) { + if (!isCollapsedOneLiner(body)) { + expected = true; + } + + // otherwise, the body is allowed to have braces or not to have braces + } else if (multiOrNest) { + if (hasBlock) { + const statement = body.body[0]; + const leadingCommentsInBlock = + sourceCode.getCommentsBefore(statement); + + expected = + !isOneLiner(statement) || + leadingCommentsInBlock.length > 0; + } else { + expected = !isOneLiner(body); + } + } else { + // default "all" + expected = true; + } + + return { + actual: hasBlock, + expected, + check() { + if ( + this.expected !== null && + this.expected !== this.actual + ) { + if (this.expected) { + context.report({ + node, + loc: body.loc, + messageId: + opts && opts.condition + ? "missingCurlyAfterCondition" + : "missingCurlyAfter", + data: { + name, + }, + fix: fixer => + fixer.replaceText( + body, + `{${sourceCode.getText(body)}}`, + ), + }); + } else { + context.report({ + node, + loc: body.loc, + messageId: + opts && opts.condition + ? "unexpectedCurlyAfterCondition" + : "unexpectedCurlyAfter", + data: { + name, + }, + fix(fixer) { + /* + * `do while` expressions sometimes need a space to be inserted after `do`. + * e.g. `do{foo()} while (bar)` should be corrected to `do foo() while (bar)` + */ + const needsPrecedingSpace = + node.type === "DoWhileStatement" && + sourceCode.getTokenBefore(body) + .range[1] === body.range[0] && + !astUtils.canTokensBeAdjacent( + "do", + sourceCode.getFirstToken(body, { + skip: 1, + }), + ); + + const openingBracket = + sourceCode.getFirstToken(body); + const closingBracket = + sourceCode.getLastToken(body); + const lastTokenInBlock = + sourceCode.getTokenBefore( + closingBracket, + ); + + if (needsSemicolon(closingBracket)) { + /* + * If removing braces would cause a SyntaxError due to multiple statements on the same line (or + * change the semantics of the code due to ASI), don't perform a fix. + */ + return null; + } + + const resultingBodyText = + sourceCode + .getText() + .slice( + openingBracket.range[1], + lastTokenInBlock.range[0], + ) + + sourceCode.getText(lastTokenInBlock) + + sourceCode + .getText() + .slice( + lastTokenInBlock.range[1], + closingBracket.range[0], + ); + + return fixer.replaceText( + body, + (needsPrecedingSpace ? " " : "") + + resultingBodyText, + ); + }, + }); + } + } + }, + }; + } + + /** + * Prepares to check the bodies of a "if", "else if" and "else" chain. + * @param {ASTNode} node The first IfStatement node of the chain. + * @returns {Object[]} prepared checks for each body of the chain. See `prepareCheck` for more + * information. + */ + function prepareIfChecks(node) { + const preparedChecks = []; + + for ( + let currentNode = node; + currentNode; + currentNode = currentNode.alternate + ) { + preparedChecks.push( + prepareCheck(currentNode, currentNode.consequent, "if", { + condition: true, + }), + ); + if ( + currentNode.alternate && + currentNode.alternate.type !== "IfStatement" + ) { + preparedChecks.push( + prepareCheck( + currentNode, + currentNode.alternate, + "else", + ), + ); + break; + } + } + + if (consistent) { + /* + * If any node should have or already have braces, make sure they + * all have braces. + * If all nodes shouldn't have braces, make sure they don't. + */ + const expected = preparedChecks.some(preparedCheck => { + if (preparedCheck.expected !== null) { + return preparedCheck.expected; + } + return preparedCheck.actual; + }); + + preparedChecks.forEach(preparedCheck => { + preparedCheck.expected = expected; + }); + } + + return preparedChecks; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + IfStatement(node) { + const parent = node.parent; + const isElseIf = + parent.type === "IfStatement" && parent.alternate === node; + + if (!isElseIf) { + // This is a top `if`, check the whole `if-else-if` chain + prepareIfChecks(node).forEach(preparedCheck => { + preparedCheck.check(); + }); + } + + // Skip `else if`, it's already checked (when the top `if` was visited) + }, + + WhileStatement(node) { + prepareCheck(node, node.body, "while", { + condition: true, + }).check(); + }, + + DoWhileStatement(node) { + prepareCheck(node, node.body, "do").check(); + }, + + ForStatement(node) { + prepareCheck(node, node.body, "for", { + condition: true, + }).check(); + }, + + ForInStatement(node) { + prepareCheck(node, node.body, "for-in").check(); + }, + + ForOfStatement(node) { + prepareCheck(node, node.body, "for-of").check(); + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/default-case-last.js b/tools/ui/node_modules/eslint/lib/rules/default-case-last.js new file mode 100644 index 0000000000000000000000000000000000000000..1c6170b48241607d8c39f93a68aa9548faf2647f --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/default-case-last.js @@ -0,0 +1,51 @@ +/** + * @fileoverview Rule to enforce `default` clauses in `switch` statements to be last + * @author Milos Djermanovic + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Enforce `default` clauses in `switch` statements to be last", + recommended: false, + url: "https://eslint.org/docs/latest/rules/default-case-last", + }, + + schema: [], + + messages: { + notLast: "Default clause should be the last clause.", + }, + }, + + create(context) { + return { + SwitchStatement(node) { + const cases = node.cases, + indexOfDefault = cases.findIndex(c => c.test === null); + + if ( + indexOfDefault !== -1 && + indexOfDefault !== cases.length - 1 + ) { + const defaultClause = cases[indexOfDefault]; + + context.report({ + node: defaultClause, + messageId: "notLast", + }); + } + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/default-case.js b/tools/ui/node_modules/eslint/lib/rules/default-case.js new file mode 100644 index 0000000000000000000000000000000000000000..23e2f6efa192f56ad65c38fc81ec655ada3bf7fc --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/default-case.js @@ -0,0 +1,103 @@ +/** + * @fileoverview require default case in switch statements + * @author Aliaksei Shytkin + */ +"use strict"; + +const DEFAULT_COMMENT_PATTERN = /^no default$/iu; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [{}], + + docs: { + description: "Require `default` cases in `switch` statements", + recommended: false, + url: "https://eslint.org/docs/latest/rules/default-case", + }, + + schema: [ + { + type: "object", + properties: { + commentPattern: { + type: "string", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + missingDefaultCase: "Expected a default case.", + }, + }, + + create(context) { + const [options] = context.options; + const commentPattern = options.commentPattern + ? new RegExp(options.commentPattern, "u") + : DEFAULT_COMMENT_PATTERN; + + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Shortcut to get last element of array + * @param {*[]} collection Array + * @returns {any} Last element + */ + function last(collection) { + return collection.at(-1); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + SwitchStatement(node) { + if (!node.cases.length) { + /* + * skip check of empty switch because there is no easy way + * to extract comments inside it now + */ + return; + } + + const hasDefault = node.cases.some(v => v.test === null); + + if (!hasDefault) { + let comment; + + const lastCase = last(node.cases); + const comments = sourceCode.getCommentsAfter(lastCase); + + if (comments.length) { + comment = last(comments); + } + + if ( + !comment || + !commentPattern.test(comment.value.trim()) + ) { + context.report({ + node, + messageId: "missingDefaultCase", + }); + } + } + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/default-param-last.js b/tools/ui/node_modules/eslint/lib/rules/default-param-last.js new file mode 100644 index 0000000000000000000000000000000000000000..101b89ff85048305e695070afd2c16a75ae7d28e --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/default-param-last.js @@ -0,0 +1,78 @@ +/** + * @fileoverview enforce default parameters to be last + * @author Chiawen Chen + */ + +"use strict"; + +/** + * Checks if node is required: i.e. does not have a default value or ? optional indicator. + * @param {ASTNode} node the node to be evaluated + * @returns {boolean} true if the node is required, false if not. + */ +function isRequiredParameter(node) { + return !( + node.type === "AssignmentPattern" || + node.type === "RestElement" || + node.optional + ); +} + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + dialects: ["javascript", "typescript"], + language: "javascript", + type: "suggestion", + + docs: { + description: "Enforce default parameters to be last", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/default-param-last", + }, + + schema: [], + + messages: { + shouldBeLast: "Default parameters should be last.", + }, + }, + + create(context) { + /** + * Handler for function contexts. + * @param {ASTNode} node function node + * @returns {void} + */ + function handleFunction(node) { + let hasSeenRequiredParameter = false; + + for (let i = node.params.length - 1; i >= 0; i -= 1) { + const current = node.params[i]; + const param = + current.type === "TSParameterProperty" + ? current.parameter + : current; + + if (isRequiredParameter(param)) { + hasSeenRequiredParameter = true; + continue; + } + + if (hasSeenRequiredParameter) { + context.report({ + node: current, + messageId: "shouldBeLast", + }); + } + } + } + + return { + FunctionDeclaration: handleFunction, + FunctionExpression: handleFunction, + ArrowFunctionExpression: handleFunction, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/dot-location.js b/tools/ui/node_modules/eslint/lib/rules/dot-location.js new file mode 100644 index 0000000000000000000000000000000000000000..9025a1fe2f1a3570ce6fdc6a5a564d7fbd493bee --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/dot-location.js @@ -0,0 +1,138 @@ +/** + * @fileoverview Validates newlines before and after dots + * @author Greg Cochard + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "dot-location", + url: "https://eslint.style/rules/dot-location", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce consistent newlines before and after dots", + recommended: false, + url: "https://eslint.org/docs/latest/rules/dot-location", + }, + + schema: [ + { + enum: ["object", "property"], + }, + ], + + fixable: "code", + + messages: { + expectedDotAfterObject: + "Expected dot to be on same line as object.", + expectedDotBeforeProperty: + "Expected dot to be on same line as property.", + }, + }, + + create(context) { + const config = context.options[0]; + + // default to onObject if no preference is passed + const onObject = config === "object" || !config; + + const sourceCode = context.sourceCode; + + /** + * Reports if the dot between object and property is on the correct location. + * @param {ASTNode} node The `MemberExpression` node. + * @returns {void} + */ + function checkDotLocation(node) { + const property = node.property; + const dotToken = sourceCode.getTokenBefore(property); + + if (onObject) { + // `obj` expression can be parenthesized, but those paren tokens are not a part of the `obj` node. + const tokenBeforeDot = sourceCode.getTokenBefore(dotToken); + + if (!astUtils.isTokenOnSameLine(tokenBeforeDot, dotToken)) { + context.report({ + node, + loc: dotToken.loc, + messageId: "expectedDotAfterObject", + *fix(fixer) { + if ( + dotToken.value.startsWith(".") && + astUtils.isDecimalIntegerNumericToken( + tokenBeforeDot, + ) + ) { + yield fixer.insertTextAfter( + tokenBeforeDot, + ` ${dotToken.value}`, + ); + } else { + yield fixer.insertTextAfter( + tokenBeforeDot, + dotToken.value, + ); + } + yield fixer.remove(dotToken); + }, + }); + } + } else if (!astUtils.isTokenOnSameLine(dotToken, property)) { + context.report({ + node, + loc: dotToken.loc, + messageId: "expectedDotBeforeProperty", + *fix(fixer) { + yield fixer.remove(dotToken); + yield fixer.insertTextBefore(property, dotToken.value); + }, + }); + } + } + + /** + * Checks the spacing of the dot within a member expression. + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function checkNode(node) { + if (!node.computed) { + checkDotLocation(node); + } + } + + return { + MemberExpression: checkNode, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/dot-notation.js b/tools/ui/node_modules/eslint/lib/rules/dot-notation.js new file mode 100644 index 0000000000000000000000000000000000000000..d6e4d05ce41efe04e9a20bd5bb37a19faa0e2fc9 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/dot-notation.js @@ -0,0 +1,216 @@ +/** + * @fileoverview Rule to warn about using dot notation instead of square bracket notation when possible. + * @author Josh Perez + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const keywords = require("./utils/keywords"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const validIdentifier = /^[a-zA-Z_$][\w$]*$/u; + +// `null` literal must be handled separately. +const literalTypesToCheck = new Set(["string", "boolean"]); + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + allowKeywords: true, + allowPattern: "", + }, + ], + + docs: { + description: "Enforce dot notation whenever possible", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/dot-notation", + }, + + schema: [ + { + type: "object", + properties: { + allowKeywords: { + type: "boolean", + }, + allowPattern: { + type: "string", + }, + }, + additionalProperties: false, + }, + ], + + fixable: "code", + + messages: { + useDot: "[{{key}}] is better written in dot notation.", + useBrackets: ".{{key}} is a syntax error.", + }, + }, + + create(context) { + const [options] = context.options; + const allowKeywords = options.allowKeywords; + const sourceCode = context.sourceCode; + + let allowPattern; + + if (options.allowPattern) { + allowPattern = new RegExp(options.allowPattern, "u"); + } + + /** + * Check if the property is valid dot notation + * @param {ASTNode} node The dot notation node + * @param {string} value Value which is to be checked + * @returns {void} + */ + function checkComputedProperty(node, value) { + if ( + validIdentifier.test(value) && + (allowKeywords || !keywords.includes(String(value))) && + !(allowPattern && allowPattern.test(value)) + ) { + const formattedValue = + node.property.type === "Literal" + ? JSON.stringify(value) + : `\`${value}\``; + + context.report({ + node: node.property, + messageId: "useDot", + data: { + key: formattedValue, + }, + *fix(fixer) { + const leftBracket = sourceCode.getTokenAfter( + node.object, + astUtils.isOpeningBracketToken, + ); + const rightBracket = sourceCode.getLastToken(node); + const nextToken = sourceCode.getTokenAfter(node); + + // Don't perform any fixes if there are comments inside the brackets. + if ( + sourceCode.commentsExistBetween( + leftBracket, + rightBracket, + ) + ) { + return; + } + + // Replace the brackets by an identifier. + if (!node.optional) { + yield fixer.insertTextBefore( + leftBracket, + astUtils.isDecimalInteger(node.object) + ? " ." + : ".", + ); + } + yield fixer.replaceTextRange( + [leftBracket.range[0], rightBracket.range[1]], + value, + ); + + // Insert a space after the property if it will be connected to the next token. + if ( + nextToken && + rightBracket.range[1] === nextToken.range[0] && + !astUtils.canTokensBeAdjacent( + String(value), + nextToken, + ) + ) { + yield fixer.insertTextAfter(node, " "); + } + }, + }); + } + } + + return { + MemberExpression(node) { + if ( + node.computed && + node.property.type === "Literal" && + (literalTypesToCheck.has(typeof node.property.value) || + astUtils.isNullLiteral(node.property)) + ) { + checkComputedProperty(node, node.property.value); + } + if ( + node.computed && + astUtils.isStaticTemplateLiteral(node.property) + ) { + checkComputedProperty( + node, + node.property.quasis[0].value.cooked, + ); + } + if ( + !allowKeywords && + !node.computed && + node.property.type === "Identifier" && + keywords.includes(String(node.property.name)) + ) { + context.report({ + node: node.property, + messageId: "useBrackets", + data: { + key: node.property.name, + }, + *fix(fixer) { + const dotToken = sourceCode.getTokenBefore( + node.property, + ); + + // A statement that starts with `let[` is parsed as a destructuring variable declaration, not a MemberExpression. + if ( + node.object.type === "Identifier" && + node.object.name === "let" && + !node.optional + ) { + return; + } + + // Don't perform any fixes if there are comments between the dot and the property name. + if ( + sourceCode.commentsExistBetween( + dotToken, + node.property, + ) + ) { + return; + } + + // Replace the identifier to brackets. + if (!node.optional) { + yield fixer.remove(dotToken); + } + yield fixer.replaceText( + node.property, + `["${node.property.name}"]`, + ); + }, + }); + } + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/eol-last.js b/tools/ui/node_modules/eslint/lib/rules/eol-last.js new file mode 100644 index 0000000000000000000000000000000000000000..4943784687d2c089fd92695ce1ab665e0f92902a --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/eol-last.js @@ -0,0 +1,135 @@ +/** + * @fileoverview Require or disallow newline at the end of files + * @author Nodeca Team + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "eol-last", + url: "https://eslint.style/rules/eol-last", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Require or disallow newline at the end of files", + recommended: false, + url: "https://eslint.org/docs/latest/rules/eol-last", + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["always", "never", "unix", "windows"], + }, + ], + + messages: { + missing: "Newline required at end of file but not found.", + unexpected: "Newline not allowed at end of file.", + }, + }, + create(context) { + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + Program: function checkBadEOF(node) { + const sourceCode = context.sourceCode, + src = sourceCode.getText(), + lastLine = sourceCode.lines.at(-1), + location = { + column: lastLine.length, + line: sourceCode.lines.length, + }, + LF = "\n", + CRLF = `\r${LF}`, + endsWithNewline = src.endsWith(LF); + + /* + * Empty source is always valid: No content in file so we don't + * need to lint for a newline on the last line of content. + */ + if (!src.length) { + return; + } + + let mode = context.options[0] || "always", + appendCRLF = false; + + if (mode === "unix") { + // `"unix"` should behave exactly as `"always"` + mode = "always"; + } + if (mode === "windows") { + // `"windows"` should behave exactly as `"always"`, but append CRLF in the fixer for backwards compatibility + mode = "always"; + appendCRLF = true; + } + if (mode === "always" && !endsWithNewline) { + // File is not newline-terminated, but should be + context.report({ + node, + loc: location, + messageId: "missing", + fix(fixer) { + return fixer.insertTextAfterRange( + [0, src.length], + appendCRLF ? CRLF : LF, + ); + }, + }); + } else if (mode === "never" && endsWithNewline) { + const secondLastLine = sourceCode.lines.at(-2); + + // File is newline-terminated, but shouldn't be + context.report({ + node, + loc: { + start: { + line: sourceCode.lines.length - 1, + column: secondLastLine.length, + }, + end: { line: sourceCode.lines.length, column: 0 }, + }, + messageId: "unexpected", + fix(fixer) { + const finalEOLs = /(?:\r?\n)+$/u, + match = finalEOLs.exec(sourceCode.text), + start = match.index, + end = sourceCode.text.length; + + return fixer.replaceTextRange([start, end], ""); + }, + }); + } + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/eqeqeq.js b/tools/ui/node_modules/eslint/lib/rules/eqeqeq.js new file mode 100644 index 0000000000000000000000000000000000000000..cfe5bd4cff69d091aeb602305bbf4dec2ee324c0 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/eqeqeq.js @@ -0,0 +1,210 @@ +/** + * @fileoverview Rule to flag statements that use != and == instead of !== and === + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + hasSuggestions: true, + + docs: { + description: "Require the use of `===` and `!==`", + recommended: false, + url: "https://eslint.org/docs/latest/rules/eqeqeq", + }, + + schema: { + anyOf: [ + { + type: "array", + items: [ + { + enum: ["always"], + }, + { + type: "object", + properties: { + null: { + enum: ["always", "never", "ignore"], + }, + }, + additionalProperties: false, + }, + ], + additionalItems: false, + }, + { + type: "array", + items: [ + { + enum: ["smart", "allow-null"], + }, + ], + additionalItems: false, + }, + ], + }, + + fixable: "code", + + messages: { + unexpected: + "Expected '{{expectedOperator}}' and instead saw '{{actualOperator}}'.", + replaceOperator: + "Use '{{expectedOperator}}' instead of '{{actualOperator}}'.", + }, + }, + + create(context) { + const config = context.options[0] || "always"; + const options = context.options[1] || {}; + const sourceCode = context.sourceCode; + + const nullOption = + config === "always" ? options.null || "always" : "ignore"; + const enforceRuleForNull = nullOption === "always"; + const enforceInverseRuleForNull = nullOption === "never"; + + /** + * Checks if an expression is a typeof expression + * @param {ASTNode} node The node to check + * @returns {boolean} if the node is a typeof expression + */ + function isTypeOf(node) { + return ( + node.type === "UnaryExpression" && node.operator === "typeof" + ); + } + + /** + * Checks if either operand of a binary expression is a typeof operation + * @param {ASTNode} node The node to check + * @returns {boolean} if one of the operands is typeof + * @private + */ + function isTypeOfBinary(node) { + return isTypeOf(node.left) || isTypeOf(node.right); + } + + /** + * Checks if operands are literals of the same type (via typeof) + * @param {ASTNode} node The node to check + * @returns {boolean} if operands are of same type + * @private + */ + function areLiteralsAndSameType(node) { + return ( + node.left.type === "Literal" && + node.right.type === "Literal" && + typeof node.left.value === typeof node.right.value + ); + } + + /** + * Checks if one of the operands is a literal null + * @param {ASTNode} node The node to check + * @returns {boolean} if operands are null + * @private + */ + function isNullCheck(node) { + return ( + astUtils.isNullLiteral(node.right) || + astUtils.isNullLiteral(node.left) + ); + } + + /** + * Reports a message for this rule. + * @param {ASTNode} node The binary expression node that was checked + * @param {string} expectedOperator The operator that was expected (either '==', '!=', '===', or '!==') + * @returns {void} + * @private + */ + function report(node, expectedOperator) { + const operatorToken = sourceCode.getFirstTokenBetween( + node.left, + node.right, + token => token.value === node.operator, + ); + + const commonReportParams = { + node, + loc: operatorToken.loc, + messageId: "unexpected", + data: { expectedOperator, actualOperator: node.operator }, + }; + + if (isTypeOfBinary(node) || areLiteralsAndSameType(node)) { + context.report({ + ...commonReportParams, + fix(fixer) { + return fixer.replaceText( + operatorToken, + expectedOperator, + ); + }, + }); + } else { + context.report({ + ...commonReportParams, + suggest: [ + { + messageId: "replaceOperator", + data: { + expectedOperator, + actualOperator: node.operator, + }, + fix: fixer => + fixer.replaceText( + operatorToken, + expectedOperator, + ), + }, + ], + }); + } + } + + return { + BinaryExpression(node) { + const isNull = isNullCheck(node); + + if (node.operator !== "==" && node.operator !== "!=") { + if (enforceInverseRuleForNull && isNull) { + report(node, node.operator.slice(0, -1)); + } + return; + } + + if ( + config === "smart" && + (isTypeOfBinary(node) || + areLiteralsAndSameType(node) || + isNull) + ) { + return; + } + + if (!enforceRuleForNull && isNull) { + return; + } + + report(node, `${node.operator}=`); + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/for-direction.js b/tools/ui/node_modules/eslint/lib/rules/for-direction.js new file mode 100644 index 0000000000000000000000000000000000000000..7cf14b99631899ee0e19e8c91a609db50146c27a --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/for-direction.js @@ -0,0 +1,168 @@ +/** + * @fileoverview enforce `for` loop update clause moving the counter in the right direction.(for-direction) + * @author Aladdin-ADD + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { getStaticValue } = require("@eslint-community/eslint-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + docs: { + description: + "Enforce `for` loop update clause moving the counter in the right direction", + recommended: true, + url: "https://eslint.org/docs/latest/rules/for-direction", + }, + + fixable: null, + schema: [], + + messages: { + incorrectDirection: + "The update clause in this loop moves the variable in the wrong direction.", + }, + }, + + create(context) { + const { sourceCode } = context; + + /** + * report an error. + * @param {ASTNode} node the node to report. + * @returns {void} + */ + function report(node) { + context.report({ + loc: { + start: node.loc.start, + end: sourceCode.getTokenBefore(node.body).loc.end, + }, + messageId: "incorrectDirection", + }); + } + + /** + * check the right side of the assignment + * @param {ASTNode} update UpdateExpression to check + * @param {number} dir expected direction that could either be turned around or invalidated + * @returns {number} return dir, the negated dir, or zero if the counter does not change or the direction is not clear + */ + function getRightDirection(update, dir) { + const staticValue = getStaticValue( + update.right, + sourceCode.getScope(update), + ); + + if ( + staticValue && + ["bigint", "boolean", "number"].includes( + typeof staticValue.value, + ) + ) { + const sign = Math.sign(Number(staticValue.value)) || 0; // convert NaN to 0 + + return dir * sign; + } + return 0; + } + + /** + * check UpdateExpression add/sub the counter + * @param {ASTNode} update UpdateExpression to check + * @param {string} counter variable name to check + * @returns {number} if add return 1, if sub return -1, if nochange, return 0 + */ + function getUpdateDirection(update, counter) { + if ( + update.argument.type === "Identifier" && + update.argument.name === counter + ) { + if (update.operator === "++") { + return 1; + } + if (update.operator === "--") { + return -1; + } + } + return 0; + } + + /** + * check AssignmentExpression add/sub the counter + * @param {ASTNode} update AssignmentExpression to check + * @param {string} counter variable name to check + * @returns {number} if add return 1, if sub return -1, if nochange, return 0 + */ + function getAssignmentDirection(update, counter) { + if (update.left.name === counter) { + if (update.operator === "+=") { + return getRightDirection(update, 1); + } + if (update.operator === "-=") { + return getRightDirection(update, -1); + } + } + return 0; + } + + return { + ForStatement(node) { + if ( + node.test && + node.test.type === "BinaryExpression" && + node.update + ) { + for (const counterPosition of ["left", "right"]) { + if (node.test[counterPosition].type !== "Identifier") { + continue; + } + + const counter = node.test[counterPosition].name; + const operator = node.test.operator; + const update = node.update; + + let wrongDirection; + + if (operator === "<" || operator === "<=") { + wrongDirection = + counterPosition === "left" ? -1 : 1; + } else if (operator === ">" || operator === ">=") { + wrongDirection = + counterPosition === "left" ? 1 : -1; + } else { + return; + } + + if (update.type === "UpdateExpression") { + if ( + getUpdateDirection(update, counter) === + wrongDirection + ) { + report(node); + } + } else if ( + update.type === "AssignmentExpression" && + getAssignmentDirection(update, counter) === + wrongDirection + ) { + report(node); + } + } + } + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/func-call-spacing.js b/tools/ui/node_modules/eslint/lib/rules/func-call-spacing.js new file mode 100644 index 0000000000000000000000000000000000000000..1195d3f49dbbaca96b598536fb6e46037152d06d --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/func-call-spacing.js @@ -0,0 +1,281 @@ +/** + * @fileoverview Rule to control spacing within function calls + * @author Matt DuVall + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "function-call-spacing", + url: "https://eslint.style/rules/function-call-spacing", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Require or disallow spacing between function identifiers and their invocations", + recommended: false, + url: "https://eslint.org/docs/latest/rules/func-call-spacing", + }, + + fixable: "whitespace", + + schema: { + anyOf: [ + { + type: "array", + items: [ + { + enum: ["never"], + }, + ], + minItems: 0, + maxItems: 1, + }, + { + type: "array", + items: [ + { + enum: ["always"], + }, + { + type: "object", + properties: { + allowNewlines: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + minItems: 0, + maxItems: 2, + }, + ], + }, + + messages: { + unexpectedWhitespace: + "Unexpected whitespace between function name and paren.", + unexpectedNewline: + "Unexpected newline between function name and paren.", + missing: "Missing space between function name and paren.", + }, + }, + + create(context) { + const never = context.options[0] !== "always"; + const allowNewlines = + !never && context.options[1] && context.options[1].allowNewlines; + const sourceCode = context.sourceCode; + const text = sourceCode.getText(); + + /** + * Check if open space is present in a function name + * @param {ASTNode} node node to evaluate + * @param {Token} leftToken The last token of the callee. This may be the closing parenthesis that encloses the callee. + * @param {Token} rightToken The first token of the arguments. this is the opening parenthesis that encloses the arguments. + * @returns {void} + * @private + */ + function checkSpacing(node, leftToken, rightToken) { + const textBetweenTokens = text + .slice(leftToken.range[1], rightToken.range[0]) + .replace(/\/\*.*?\*\//gu, ""); + const hasWhitespace = /\s/u.test(textBetweenTokens); + const hasNewline = + hasWhitespace && + astUtils.LINEBREAK_MATCHER.test(textBetweenTokens); + + /* + * never allowNewlines hasWhitespace hasNewline message + * F F F F Missing space between function name and paren. + * F F F T (Invalid `!hasWhitespace && hasNewline`) + * F F T T Unexpected newline between function name and paren. + * F F T F (OK) + * F T T F (OK) + * F T T T (OK) + * F T F T (Invalid `!hasWhitespace && hasNewline`) + * F T F F Missing space between function name and paren. + * T T F F (Invalid `never && allowNewlines`) + * T T F T (Invalid `!hasWhitespace && hasNewline`) + * T T T T (Invalid `never && allowNewlines`) + * T T T F (Invalid `never && allowNewlines`) + * T F T F Unexpected space between function name and paren. + * T F T T Unexpected space between function name and paren. + * T F F T (Invalid `!hasWhitespace && hasNewline`) + * T F F F (OK) + * + * T T Unexpected space between function name and paren. + * F F Missing space between function name and paren. + * F F T Unexpected newline between function name and paren. + */ + + if (never && hasWhitespace) { + context.report({ + node, + loc: { + start: leftToken.loc.end, + end: { + line: rightToken.loc.start.line, + column: rightToken.loc.start.column - 1, + }, + }, + messageId: "unexpectedWhitespace", + fix(fixer) { + // Don't remove comments. + if ( + sourceCode.commentsExistBetween( + leftToken, + rightToken, + ) + ) { + return null; + } + + // If `?.` exists, it doesn't hide no-unexpected-multiline errors + if (node.optional) { + return fixer.replaceTextRange( + [leftToken.range[1], rightToken.range[0]], + "?.", + ); + } + + /* + * Only autofix if there is no newline + * https://github.com/eslint/eslint/issues/7787 + */ + if (hasNewline) { + return null; + } + return fixer.removeRange([ + leftToken.range[1], + rightToken.range[0], + ]); + }, + }); + } else if (!never && !hasWhitespace) { + context.report({ + node, + loc: { + start: { + line: leftToken.loc.end.line, + column: leftToken.loc.end.column - 1, + }, + end: rightToken.loc.start, + }, + messageId: "missing", + fix(fixer) { + if (node.optional) { + return null; // Not sure if inserting a space to either before/after `?.` token. + } + return fixer.insertTextBefore(rightToken, " "); + }, + }); + } else if (!never && !allowNewlines && hasNewline) { + context.report({ + node, + loc: { + start: leftToken.loc.end, + end: rightToken.loc.start, + }, + messageId: "unexpectedNewline", + fix(fixer) { + /* + * Only autofix if there is no newline + * https://github.com/eslint/eslint/issues/7787 + * But if `?.` exists, it doesn't hide no-unexpected-multiline errors + */ + if (!node.optional) { + return null; + } + + // Don't remove comments. + if ( + sourceCode.commentsExistBetween( + leftToken, + rightToken, + ) + ) { + return null; + } + + const range = [leftToken.range[1], rightToken.range[0]]; + const qdToken = sourceCode.getTokenAfter(leftToken); + + if (qdToken.range[0] === leftToken.range[1]) { + return fixer.replaceTextRange(range, "?. "); + } + if (qdToken.range[1] === rightToken.range[0]) { + return fixer.replaceTextRange(range, " ?."); + } + return fixer.replaceTextRange(range, " ?. "); + }, + }); + } + } + + return { + "CallExpression, NewExpression"(node) { + const lastToken = sourceCode.getLastToken(node); + const lastCalleeToken = sourceCode.getLastToken(node.callee); + const parenToken = sourceCode.getFirstTokenBetween( + lastCalleeToken, + lastToken, + astUtils.isOpeningParenToken, + ); + const prevToken = + parenToken && + sourceCode.getTokenBefore( + parenToken, + astUtils.isNotQuestionDotToken, + ); + + // Parens in NewExpression are optional + if (!(parenToken && parenToken.range[1] < node.range[1])) { + return; + } + + checkSpacing(node, prevToken, parenToken); + }, + + ImportExpression(node) { + const leftToken = sourceCode.getFirstToken(node); + const rightToken = sourceCode.getTokenAfter(leftToken); + + checkSpacing(node, leftToken, rightToken); + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/func-name-matching.js b/tools/ui/node_modules/eslint/lib/rules/func-name-matching.js new file mode 100644 index 0000000000000000000000000000000000000000..4643bfbc4f987fafb469e96c01e9b75b8f49859d --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/func-name-matching.js @@ -0,0 +1,338 @@ +/** + * @fileoverview Rule to require function names to match the name of the variable or property to which they are assigned. + * @author Annie Zhang, Pavel Strashkin + */ + +"use strict"; + +//-------------------------------------------------------------------------- +// Requirements +//-------------------------------------------------------------------------- + +const astUtils = require("./utils/ast-utils"); +const esutils = require("esutils"); + +//-------------------------------------------------------------------------- +// Helpers +//-------------------------------------------------------------------------- + +/** + * Determines if a pattern is `module.exports` or `module["exports"]` + * @param {ASTNode} pattern The left side of the AssignmentExpression + * @returns {boolean} True if the pattern is `module.exports` or `module["exports"]` + */ +function isModuleExports(pattern) { + if ( + pattern.type === "MemberExpression" && + pattern.object.type === "Identifier" && + pattern.object.name === "module" + ) { + // module.exports + if ( + pattern.property.type === "Identifier" && + pattern.property.name === "exports" + ) { + return true; + } + + // module["exports"] + if ( + pattern.property.type === "Literal" && + pattern.property.value === "exports" + ) { + return true; + } + } + return false; +} + +/** + * Determines if a string name is a valid identifier + * @param {string} name The string to be checked + * @param {number} ecmaVersion The ECMAScript version if specified in the parserOptions config + * @returns {boolean} True if the string is a valid identifier + */ +function isIdentifier(name, ecmaVersion) { + if (ecmaVersion >= 2015) { + return esutils.keyword.isIdentifierES6(name); + } + return esutils.keyword.isIdentifierES5(name); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const alwaysOrNever = { enum: ["always", "never"] }; +const optionsObject = { + type: "object", + properties: { + considerPropertyDescriptor: { + type: "boolean", + }, + includeCommonJSModuleExports: { + type: "boolean", + }, + }, + additionalProperties: false, +}; + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: + "Require function names to match the name of the variable or property to which they are assigned", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/func-name-matching", + }, + + schema: { + anyOf: [ + { + type: "array", + additionalItems: false, + items: [alwaysOrNever, optionsObject], + }, + { + type: "array", + additionalItems: false, + items: [optionsObject], + }, + ], + }, + + messages: { + matchProperty: + "Function name `{{funcName}}` should match property name `{{name}}`.", + matchVariable: + "Function name `{{funcName}}` should match variable name `{{name}}`.", + notMatchProperty: + "Function name `{{funcName}}` should not match property name `{{name}}`.", + notMatchVariable: + "Function name `{{funcName}}` should not match variable name `{{name}}`.", + }, + }, + + create(context) { + const options = + (typeof context.options[0] === "object" + ? context.options[0] + : context.options[1]) || {}; + const nameMatches = + typeof context.options[0] === "string" + ? context.options[0] + : "always"; + const considerPropertyDescriptor = options.considerPropertyDescriptor; + const includeModuleExports = options.includeCommonJSModuleExports; + const ecmaVersion = context.languageOptions.ecmaVersion; + + /** + * Check whether node is a certain CallExpression. + * @param {string} objName object name + * @param {string} funcName function name + * @param {ASTNode} node The node to check + * @returns {boolean} `true` if node matches CallExpression + */ + function isPropertyCall(objName, funcName, node) { + if (!node) { + return false; + } + return ( + node.type === "CallExpression" && + astUtils.isSpecificMemberAccess(node.callee, objName, funcName) + ); + } + + /** + * Compares identifiers based on the nameMatches option + * @param {string} x the first identifier + * @param {string} y the second identifier + * @returns {boolean} whether the two identifiers should warn. + */ + function shouldWarn(x, y) { + return ( + (nameMatches === "always" && x !== y) || + (nameMatches === "never" && x === y) + ); + } + + /** + * Reports + * @param {ASTNode} node The node to report + * @param {string} name The variable or property name + * @param {string} funcName The function name + * @param {boolean} isProp True if the reported node is a property assignment + * @returns {void} + */ + function report(node, name, funcName, isProp) { + let messageId; + + if (nameMatches === "always" && isProp) { + messageId = "matchProperty"; + } else if (nameMatches === "always") { + messageId = "matchVariable"; + } else if (isProp) { + messageId = "notMatchProperty"; + } else { + messageId = "notMatchVariable"; + } + context.report({ + node, + messageId, + data: { + name, + funcName, + }, + }); + } + + /** + * Determines whether a given node is a string literal + * @param {ASTNode} node The node to check + * @returns {boolean} `true` if the node is a string literal + */ + function isStringLiteral(node) { + return node.type === "Literal" && typeof node.value === "string"; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + VariableDeclarator(node) { + if ( + !node.init || + node.init.type !== "FunctionExpression" || + node.id.type !== "Identifier" + ) { + return; + } + if ( + node.init.id && + shouldWarn(node.id.name, node.init.id.name) + ) { + report(node, node.id.name, node.init.id.name, false); + } + }, + + AssignmentExpression(node) { + if ( + node.right.type !== "FunctionExpression" || + (node.left.computed && + node.left.property.type !== "Literal") || + (!includeModuleExports && isModuleExports(node.left)) || + (node.left.type !== "Identifier" && + node.left.type !== "MemberExpression") + ) { + return; + } + + const isProp = node.left.type === "MemberExpression"; + const name = isProp + ? astUtils.getStaticPropertyName(node.left) + : node.left.name; + + if ( + node.right.id && + name && + isIdentifier(name) && + shouldWarn(name, node.right.id.name) + ) { + report(node, name, node.right.id.name, isProp); + } + }, + + "Property, PropertyDefinition[value]"(node) { + if ( + !(node.value.type === "FunctionExpression" && node.value.id) + ) { + return; + } + + if (node.key.type === "Identifier" && !node.computed) { + const functionName = node.value.id.name; + let propertyName = node.key.name; + + if ( + considerPropertyDescriptor && + propertyName === "value" && + node.parent.type === "ObjectExpression" + ) { + if ( + isPropertyCall( + "Object", + "defineProperty", + node.parent.parent, + ) || + isPropertyCall( + "Reflect", + "defineProperty", + node.parent.parent, + ) + ) { + const property = node.parent.parent.arguments[1]; + + if ( + isStringLiteral(property) && + shouldWarn(property.value, functionName) + ) { + report( + node, + property.value, + functionName, + true, + ); + } + } else if ( + isPropertyCall( + "Object", + "defineProperties", + node.parent.parent.parent.parent, + ) + ) { + propertyName = node.parent.parent.key.name; + if ( + !node.parent.parent.computed && + shouldWarn(propertyName, functionName) + ) { + report(node, propertyName, functionName, true); + } + } else if ( + isPropertyCall( + "Object", + "create", + node.parent.parent.parent.parent, + ) + ) { + propertyName = node.parent.parent.key.name; + if ( + !node.parent.parent.computed && + shouldWarn(propertyName, functionName) + ) { + report(node, propertyName, functionName, true); + } + } else if (shouldWarn(propertyName, functionName)) { + report(node, propertyName, functionName, true); + } + } else if (shouldWarn(propertyName, functionName)) { + report(node, propertyName, functionName, true); + } + return; + } + + if ( + isStringLiteral(node.key) && + isIdentifier(node.key.value, ecmaVersion) && + shouldWarn(node.key.value, node.value.id.name) + ) { + report(node, node.key.value, node.value.id.name, true); + } + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/func-names.js b/tools/ui/node_modules/eslint/lib/rules/func-names.js new file mode 100644 index 0000000000000000000000000000000000000000..bef70e32ad98d8b05b1e660d0a1efc09cb16772e --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/func-names.js @@ -0,0 +1,192 @@ +/** + * @fileoverview Rule to warn when a function expression does not have a name. + * @author Kyle T. Nunery + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +/** + * Checks whether or not a given variable is a function name. + * @param {eslint-scope.Variable} variable A variable to check. + * @returns {boolean} `true` if the variable is a function name. + */ +function isFunctionName(variable) { + return variable && variable.defs[0].type === "FunctionName"; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: ["always", {}], + + docs: { + description: "Require or disallow named `function` expressions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/func-names", + }, + + schema: { + definitions: { + value: { + enum: ["always", "as-needed", "never"], + }, + }, + items: [ + { + $ref: "#/definitions/value", + }, + { + type: "object", + properties: { + generators: { + $ref: "#/definitions/value", + }, + }, + additionalProperties: false, + }, + ], + }, + + messages: { + unnamed: "Unexpected unnamed {{name}}.", + named: "Unexpected named {{name}}.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + /** + * Returns the config option for the given node. + * @param {ASTNode} node A node to get the config for. + * @returns {string} The config option. + */ + function getConfigForNode(node) { + if (node.generator && context.options[1].generators) { + return context.options[1].generators; + } + + return context.options[0]; + } + + /** + * Determines whether the current FunctionExpression node is a get, set, or + * shorthand method in an object literal or a class. + * @param {ASTNode} node A node to check. + * @returns {boolean} True if the node is a get, set, or shorthand method. + */ + function isObjectOrClassMethod(node) { + const parent = node.parent; + + return ( + parent.type === "MethodDefinition" || + (parent.type === "Property" && + (parent.method || + parent.kind === "get" || + parent.kind === "set")) + ); + } + + /** + * Determines whether the current FunctionExpression node has a name that would be + * inferred from context in a conforming ES6 environment. + * @param {ASTNode} node A node to check. + * @returns {boolean} True if the node would have a name assigned automatically. + */ + function hasInferredName(node) { + const parent = node.parent; + + return ( + isObjectOrClassMethod(node) || + (parent.type === "VariableDeclarator" && + parent.id.type === "Identifier" && + parent.init === node) || + (parent.type === "Property" && parent.value === node) || + (parent.type === "PropertyDefinition" && + parent.value === node) || + (parent.type === "AssignmentExpression" && + parent.left.type === "Identifier" && + parent.right === node) || + (parent.type === "AssignmentPattern" && + parent.left.type === "Identifier" && + parent.right === node) + ); + } + + /** + * Reports that an unnamed function should be named + * @param {ASTNode} node The node to report in the event of an error. + * @returns {void} + */ + function reportUnexpectedUnnamedFunction(node) { + context.report({ + node, + messageId: "unnamed", + loc: astUtils.getFunctionHeadLoc(node, sourceCode), + data: { name: astUtils.getFunctionNameWithKind(node) }, + }); + } + + /** + * Reports that a named function should be unnamed + * @param {ASTNode} node The node to report in the event of an error. + * @returns {void} + */ + function reportUnexpectedNamedFunction(node) { + context.report({ + node, + messageId: "named", + loc: astUtils.getFunctionHeadLoc(node, sourceCode), + data: { name: astUtils.getFunctionNameWithKind(node) }, + }); + } + + /** + * The listener for function nodes. + * @param {ASTNode} node function node + * @returns {void} + */ + function handleFunction(node) { + // Skip recursive functions. + const nameVar = sourceCode.getDeclaredVariables(node)[0]; + + if (isFunctionName(nameVar) && nameVar.references.length > 0) { + return; + } + + const hasName = Boolean(node.id && node.id.name); + const config = getConfigForNode(node); + + if (config === "never") { + if (hasName && node.type !== "FunctionDeclaration") { + reportUnexpectedNamedFunction(node); + } + } else if (config === "as-needed") { + if (!hasName && !hasInferredName(node)) { + reportUnexpectedUnnamedFunction(node); + } + } else { + if (!hasName && !isObjectOrClassMethod(node)) { + reportUnexpectedUnnamedFunction(node); + } + } + } + + return { + "FunctionExpression:exit": handleFunction, + "ExportDefaultDeclaration > FunctionDeclaration": handleFunction, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/func-style.js b/tools/ui/node_modules/eslint/lib/rules/func-style.js new file mode 100644 index 0000000000000000000000000000000000000000..dcd4ae9f73662a752ec752cb601c56ffb5ffaf64 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/func-style.js @@ -0,0 +1,221 @@ +/** + * @fileoverview Rule to enforce a particular function style + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + dialects: ["javascript", "typescript"], + language: "javascript", + type: "suggestion", + + defaultOptions: [ + "expression", + { + allowArrowFunctions: false, + allowTypeAnnotation: false, + overrides: {}, + }, + ], + + docs: { + description: + "Enforce the consistent use of either `function` declarations or expressions assigned to variables", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/func-style", + }, + + schema: [ + { + enum: ["declaration", "expression"], + }, + { + type: "object", + properties: { + allowArrowFunctions: { + type: "boolean", + }, + allowTypeAnnotation: { + type: "boolean", + }, + overrides: { + type: "object", + properties: { + namedExports: { + enum: ["declaration", "expression", "ignore"], + }, + }, + additionalProperties: false, + }, + }, + additionalProperties: false, + }, + ], + + messages: { + expression: "Expected a function expression.", + declaration: "Expected a function declaration.", + }, + }, + + create(context) { + const [style, { allowArrowFunctions, allowTypeAnnotation, overrides }] = + context.options; + const enforceDeclarations = style === "declaration"; + const { namedExports: exportFunctionStyle } = overrides; + const stack = []; + + /** + * Checks if a function declaration is part of an overloaded function + * @param {ASTNode} node The function declaration node to check + * @returns {boolean} True if the function is overloaded + */ + function isOverloadedFunction(node) { + const functionName = node.id.name; + + if (node.parent.type === "ExportNamedDeclaration") { + return node.parent.parent.body.some( + member => + member.type === "ExportNamedDeclaration" && + member.declaration?.type === "TSDeclareFunction" && + member.declaration.id.name === functionName, + ); + } + + if (node.parent.type === "SwitchCase") { + return node.parent.parent.cases.some(switchCase => + switchCase.consequent.some( + member => + member.type === "TSDeclareFunction" && + member.id.name === functionName, + ), + ); + } + + return ( + Array.isArray(node.parent.body) && + node.parent.body.some( + member => + member.type === "TSDeclareFunction" && + member.id.name === functionName, + ) + ); + } + + const nodesToCheck = { + FunctionDeclaration(node) { + stack.push(false); + + if ( + !enforceDeclarations && + node.parent.type !== "ExportDefaultDeclaration" && + (typeof exportFunctionStyle === "undefined" || + node.parent.type !== "ExportNamedDeclaration") && + !isOverloadedFunction(node) + ) { + context.report({ node, messageId: "expression" }); + } + + if ( + node.parent.type === "ExportNamedDeclaration" && + exportFunctionStyle === "expression" && + !isOverloadedFunction(node) + ) { + context.report({ node, messageId: "expression" }); + } + }, + "FunctionDeclaration:exit"() { + stack.pop(); + }, + + FunctionExpression(node) { + stack.push(false); + + if ( + enforceDeclarations && + node.parent.type === "VariableDeclarator" && + (typeof exportFunctionStyle === "undefined" || + node.parent.parent.parent.type !== + "ExportNamedDeclaration") && + !(allowTypeAnnotation && node.parent.id.typeAnnotation) + ) { + context.report({ + node: node.parent, + messageId: "declaration", + }); + } + + if ( + node.parent.type === "VariableDeclarator" && + node.parent.parent.parent.type === + "ExportNamedDeclaration" && + exportFunctionStyle === "declaration" && + !(allowTypeAnnotation && node.parent.id.typeAnnotation) + ) { + context.report({ + node: node.parent, + messageId: "declaration", + }); + } + }, + "FunctionExpression:exit"() { + stack.pop(); + }, + + "ThisExpression, Super"() { + if (stack.length > 0) { + stack[stack.length - 1] = true; + } + }, + }; + + if (!allowArrowFunctions) { + nodesToCheck.ArrowFunctionExpression = function () { + stack.push(false); + }; + + nodesToCheck["ArrowFunctionExpression:exit"] = function (node) { + const hasThisOrSuperExpr = stack.pop(); + + if ( + !hasThisOrSuperExpr && + node.parent.type === "VariableDeclarator" + ) { + if ( + enforceDeclarations && + (typeof exportFunctionStyle === "undefined" || + node.parent.parent.parent.type !== + "ExportNamedDeclaration") && + !(allowTypeAnnotation && node.parent.id.typeAnnotation) + ) { + context.report({ + node: node.parent, + messageId: "declaration", + }); + } + + if ( + node.parent.parent.parent.type === + "ExportNamedDeclaration" && + exportFunctionStyle === "declaration" && + !(allowTypeAnnotation && node.parent.id.typeAnnotation) + ) { + context.report({ + node: node.parent, + messageId: "declaration", + }); + } + } + }; + } + + return nodesToCheck; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/function-call-argument-newline.js b/tools/ui/node_modules/eslint/lib/rules/function-call-argument-newline.js new file mode 100644 index 0000000000000000000000000000000000000000..0ad1ca1d0284b27a5c655f0de7fa0d6f482ed845 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/function-call-argument-newline.js @@ -0,0 +1,166 @@ +/** + * @fileoverview Rule to enforce line breaks between arguments of a function call + * @author Alexey Gonchar + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "function-call-argument-newline", + url: "https://eslint.style/rules/function-call-argument-newline", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Enforce line breaks between arguments of a function call", + recommended: false, + url: "https://eslint.org/docs/latest/rules/function-call-argument-newline", + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["always", "never", "consistent"], + }, + ], + + messages: { + unexpectedLineBreak: "There should be no line break here.", + missingLineBreak: + "There should be a line break after this argument.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + const checkers = { + unexpected: { + messageId: "unexpectedLineBreak", + check: (prevToken, currentToken) => + prevToken.loc.end.line !== currentToken.loc.start.line, + createFix: (token, tokenBefore) => fixer => + fixer.replaceTextRange( + [tokenBefore.range[1], token.range[0]], + " ", + ), + }, + missing: { + messageId: "missingLineBreak", + check: (prevToken, currentToken) => + prevToken.loc.end.line === currentToken.loc.start.line, + createFix: (token, tokenBefore) => fixer => + fixer.replaceTextRange( + [tokenBefore.range[1], token.range[0]], + "\n", + ), + }, + }; + + /** + * Check all arguments for line breaks in the CallExpression + * @param {CallExpression} node node to evaluate + * @param {{ messageId: string, check: Function }} checker selected checker + * @returns {void} + * @private + */ + function checkArguments(node, checker) { + for (let i = 1; i < node.arguments.length; i++) { + const prevArgToken = sourceCode.getLastToken( + node.arguments[i - 1], + ); + const currentArgToken = sourceCode.getFirstToken( + node.arguments[i], + ); + + if (checker.check(prevArgToken, currentArgToken)) { + const tokenBefore = sourceCode.getTokenBefore( + currentArgToken, + { includeComments: true }, + ); + + const hasLineCommentBefore = tokenBefore.type === "Line"; + + context.report({ + node, + loc: { + start: tokenBefore.loc.end, + end: currentArgToken.loc.start, + }, + messageId: checker.messageId, + fix: hasLineCommentBefore + ? null + : checker.createFix(currentArgToken, tokenBefore), + }); + } + } + } + + /** + * Check if open space is present in a function name + * @param {CallExpression} node node to evaluate + * @returns {void} + * @private + */ + function check(node) { + if (node.arguments.length < 2) { + return; + } + + const option = context.options[0] || "always"; + + if (option === "never") { + checkArguments(node, checkers.unexpected); + } else if (option === "always") { + checkArguments(node, checkers.missing); + } else if (option === "consistent") { + const firstArgToken = sourceCode.getLastToken( + node.arguments[0], + ); + const secondArgToken = sourceCode.getFirstToken( + node.arguments[1], + ); + + if ( + firstArgToken.loc.end.line === secondArgToken.loc.start.line + ) { + checkArguments(node, checkers.unexpected); + } else { + checkArguments(node, checkers.missing); + } + } + } + + return { + CallExpression: check, + NewExpression: check, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/function-paren-newline.js b/tools/ui/node_modules/eslint/lib/rules/function-paren-newline.js new file mode 100644 index 0000000000000000000000000000000000000000..17e5e9cf85c7d0dddace239e14bf6f87881df86d --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/function-paren-newline.js @@ -0,0 +1,368 @@ +/** + * @fileoverview enforce consistent line breaks inside function parentheses + * @author Teddy Katz + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "function-paren-newline", + url: "https://eslint.style/rules/function-paren-newline", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Enforce consistent line breaks inside function parentheses", + recommended: false, + url: "https://eslint.org/docs/latest/rules/function-paren-newline", + }, + + fixable: "whitespace", + + schema: [ + { + oneOf: [ + { + enum: [ + "always", + "never", + "consistent", + "multiline", + "multiline-arguments", + ], + }, + { + type: "object", + properties: { + minItems: { + type: "integer", + minimum: 0, + }, + }, + additionalProperties: false, + }, + ], + }, + ], + + messages: { + expectedBefore: "Expected newline before ')'.", + expectedAfter: "Expected newline after '('.", + expectedBetween: "Expected newline between arguments/params.", + unexpectedBefore: "Unexpected newline before ')'.", + unexpectedAfter: "Unexpected newline after '('.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const rawOption = context.options[0] || "multiline"; + const multilineOption = rawOption === "multiline"; + const multilineArgumentsOption = rawOption === "multiline-arguments"; + const consistentOption = rawOption === "consistent"; + let minItems; + + if (typeof rawOption === "object") { + minItems = rawOption.minItems; + } else if (rawOption === "always") { + minItems = 0; + } else if (rawOption === "never") { + minItems = Infinity; + } else { + minItems = null; + } + + //---------------------------------------------------------------------- + // Helpers + //---------------------------------------------------------------------- + + /** + * Determines whether there should be newlines inside function parens + * @param {ASTNode[]} elements The arguments or parameters in the list + * @param {boolean} hasLeftNewline `true` if the left paren has a newline in the current code. + * @returns {boolean} `true` if there should be newlines inside the function parens + */ + function shouldHaveNewlines(elements, hasLeftNewline) { + if (multilineArgumentsOption && elements.length === 1) { + return hasLeftNewline; + } + if (multilineOption || multilineArgumentsOption) { + return elements.some( + (element, index) => + index !== elements.length - 1 && + element.loc.end.line !== + elements[index + 1].loc.start.line, + ); + } + if (consistentOption) { + return hasLeftNewline; + } + return elements.length >= minItems; + } + + /** + * Validates parens + * @param {Object} parens An object with keys `leftParen` for the left paren token, and `rightParen` for the right paren token + * @param {ASTNode[]} elements The arguments or parameters in the list + * @returns {void} + */ + function validateParens(parens, elements) { + const leftParen = parens.leftParen; + const rightParen = parens.rightParen; + const tokenAfterLeftParen = sourceCode.getTokenAfter(leftParen); + const tokenBeforeRightParen = sourceCode.getTokenBefore(rightParen); + const hasLeftNewline = !astUtils.isTokenOnSameLine( + leftParen, + tokenAfterLeftParen, + ); + const hasRightNewline = !astUtils.isTokenOnSameLine( + tokenBeforeRightParen, + rightParen, + ); + const needsNewlines = shouldHaveNewlines(elements, hasLeftNewline); + + if (hasLeftNewline && !needsNewlines) { + context.report({ + node: leftParen, + messageId: "unexpectedAfter", + fix(fixer) { + return sourceCode + .getText() + .slice( + leftParen.range[1], + tokenAfterLeftParen.range[0], + ) + .trim() + ? // If there is a comment between the ( and the first element, don't do a fix. + null + : fixer.removeRange([ + leftParen.range[1], + tokenAfterLeftParen.range[0], + ]); + }, + }); + } else if (!hasLeftNewline && needsNewlines) { + context.report({ + node: leftParen, + messageId: "expectedAfter", + fix: fixer => fixer.insertTextAfter(leftParen, "\n"), + }); + } + + if (hasRightNewline && !needsNewlines) { + context.report({ + node: rightParen, + messageId: "unexpectedBefore", + fix(fixer) { + return sourceCode + .getText() + .slice( + tokenBeforeRightParen.range[1], + rightParen.range[0], + ) + .trim() + ? // If there is a comment between the last element and the ), don't do a fix. + null + : fixer.removeRange([ + tokenBeforeRightParen.range[1], + rightParen.range[0], + ]); + }, + }); + } else if (!hasRightNewline && needsNewlines) { + context.report({ + node: rightParen, + messageId: "expectedBefore", + fix: fixer => fixer.insertTextBefore(rightParen, "\n"), + }); + } + } + + /** + * Validates a list of arguments or parameters + * @param {Object} parens An object with keys `leftParen` for the left paren token, and `rightParen` for the right paren token + * @param {ASTNode[]} elements The arguments or parameters in the list + * @returns {void} + */ + function validateArguments(parens, elements) { + const leftParen = parens.leftParen; + const tokenAfterLeftParen = sourceCode.getTokenAfter(leftParen); + const hasLeftNewline = !astUtils.isTokenOnSameLine( + leftParen, + tokenAfterLeftParen, + ); + const needsNewlines = shouldHaveNewlines(elements, hasLeftNewline); + + for (let i = 0; i <= elements.length - 2; i++) { + const currentElement = elements[i]; + const nextElement = elements[i + 1]; + const hasNewLine = + currentElement.loc.end.line !== nextElement.loc.start.line; + + if (!hasNewLine && needsNewlines) { + context.report({ + node: currentElement, + messageId: "expectedBetween", + fix: fixer => fixer.insertTextBefore(nextElement, "\n"), + }); + } + } + } + + /** + * Gets the left paren and right paren tokens of a node. + * @param {ASTNode} node The node with parens + * @throws {TypeError} Unexpected node type. + * @returns {Object} An object with keys `leftParen` for the left paren token, and `rightParen` for the right paren token. + * Can also return `null` if an expression has no parens (e.g. a NewExpression with no arguments, or an ArrowFunctionExpression + * with a single parameter) + */ + function getParenTokens(node) { + switch (node.type) { + case "NewExpression": + if ( + !node.arguments.length && + !( + astUtils.isOpeningParenToken( + sourceCode.getLastToken(node, { skip: 1 }), + ) && + astUtils.isClosingParenToken( + sourceCode.getLastToken(node), + ) && + node.callee.range[1] < node.range[1] + ) + ) { + // If the NewExpression does not have parens (e.g. `new Foo`), return null. + return null; + } + + // falls through + + case "CallExpression": + return { + leftParen: sourceCode.getTokenAfter( + node.callee, + astUtils.isOpeningParenToken, + ), + rightParen: sourceCode.getLastToken(node), + }; + + case "FunctionDeclaration": + case "FunctionExpression": { + const leftParen = sourceCode.getFirstToken( + node, + astUtils.isOpeningParenToken, + ); + const rightParen = node.params.length + ? sourceCode.getTokenAfter( + node.params.at(-1), + astUtils.isClosingParenToken, + ) + : sourceCode.getTokenAfter(leftParen); + + return { leftParen, rightParen }; + } + + case "ArrowFunctionExpression": { + const firstToken = sourceCode.getFirstToken(node, { + skip: node.async ? 1 : 0, + }); + + if (!astUtils.isOpeningParenToken(firstToken)) { + // If the ArrowFunctionExpression has a single param without parens, return null. + return null; + } + + const rightParen = node.params.length + ? sourceCode.getTokenAfter( + node.params.at(-1), + astUtils.isClosingParenToken, + ) + : sourceCode.getTokenAfter(firstToken); + + return { + leftParen: firstToken, + rightParen, + }; + } + + case "ImportExpression": { + const leftParen = sourceCode.getFirstToken(node, 1); + const rightParen = sourceCode.getLastToken(node); + + return { leftParen, rightParen }; + } + + default: + throw new TypeError( + `unexpected node with type ${node.type}`, + ); + } + } + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + + return { + [[ + "ArrowFunctionExpression", + "CallExpression", + "FunctionDeclaration", + "FunctionExpression", + "ImportExpression", + "NewExpression", + ]](node) { + const parens = getParenTokens(node); + let params; + + if (node.type === "ImportExpression") { + params = [node.source]; + } else if (astUtils.isFunction(node)) { + params = node.params; + } else { + params = node.arguments; + } + + if (parens) { + validateParens(parens, params); + + if (multilineArgumentsOption) { + validateArguments(parens, params); + } + } + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/generator-star-spacing.js b/tools/ui/node_modules/eslint/lib/rules/generator-star-spacing.js new file mode 100644 index 0000000000000000000000000000000000000000..1c980baf2c9e7fc3247d179f7cab8843bc47fdc4 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/generator-star-spacing.js @@ -0,0 +1,246 @@ +/** + * @fileoverview Rule to check the spacing around the * in generator functions. + * @author Jamund Ferguson + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const OVERRIDE_SCHEMA = { + oneOf: [ + { + enum: ["before", "after", "both", "neither"], + }, + { + type: "object", + properties: { + before: { type: "boolean" }, + after: { type: "boolean" }, + }, + additionalProperties: false, + }, + ], +}; + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "generator-star-spacing", + url: "https://eslint.style/rules/generator-star-spacing", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Enforce consistent spacing around `*` operators in generator functions", + recommended: false, + url: "https://eslint.org/docs/latest/rules/generator-star-spacing", + }, + + fixable: "whitespace", + + schema: [ + { + oneOf: [ + { + enum: ["before", "after", "both", "neither"], + }, + { + type: "object", + properties: { + before: { type: "boolean" }, + after: { type: "boolean" }, + named: OVERRIDE_SCHEMA, + anonymous: OVERRIDE_SCHEMA, + method: OVERRIDE_SCHEMA, + }, + additionalProperties: false, + }, + ], + }, + ], + + messages: { + missingBefore: "Missing space before *.", + missingAfter: "Missing space after *.", + unexpectedBefore: "Unexpected space before *.", + unexpectedAfter: "Unexpected space after *.", + }, + }, + + create(context) { + const optionDefinitions = { + before: { before: true, after: false }, + after: { before: false, after: true }, + both: { before: true, after: true }, + neither: { before: false, after: false }, + }; + + /** + * Returns resolved option definitions based on an option and defaults + * @param {any} option The option object or string value + * @param {Object} defaults The defaults to use if options are not present + * @returns {Object} the resolved object definition + */ + function optionToDefinition(option, defaults) { + if (!option) { + return defaults; + } + + return typeof option === "string" + ? optionDefinitions[option] + : Object.assign({}, defaults, option); + } + + const modes = (function (option) { + const defaults = optionToDefinition( + option, + optionDefinitions.before, + ); + + return { + named: optionToDefinition(option.named, defaults), + anonymous: optionToDefinition(option.anonymous, defaults), + method: optionToDefinition(option.method, defaults), + }; + })(context.options[0] || {}); + + const sourceCode = context.sourceCode; + + /** + * Checks if the given token is a star token or not. + * @param {Token} token The token to check. + * @returns {boolean} `true` if the token is a star token. + */ + function isStarToken(token) { + return token.value === "*" && token.type === "Punctuator"; + } + + /** + * Gets the generator star token of the given function node. + * @param {ASTNode} node The function node to get. + * @returns {Token} Found star token. + */ + function getStarToken(node) { + return sourceCode.getFirstToken( + node.parent.method || node.parent.type === "MethodDefinition" + ? node.parent + : node, + isStarToken, + ); + } + + /** + * capitalize a given string. + * @param {string} str the given string. + * @returns {string} the capitalized string. + */ + function capitalize(str) { + return str[0].toUpperCase() + str.slice(1); + } + + /** + * Checks the spacing between two tokens before or after the star token. + * @param {string} kind Either "named", "anonymous", or "method" + * @param {string} side Either "before" or "after". + * @param {Token} leftToken `function` keyword token if side is "before", or + * star token if side is "after". + * @param {Token} rightToken Star token if side is "before", or identifier + * token if side is "after". + * @returns {void} + */ + function checkSpacing(kind, side, leftToken, rightToken) { + if ( + !!(rightToken.range[0] - leftToken.range[1]) !== + modes[kind][side] + ) { + const after = leftToken.value === "*"; + const spaceRequired = modes[kind][side]; + const node = after ? leftToken : rightToken; + const messageId = `${spaceRequired ? "missing" : "unexpected"}${capitalize(side)}`; + + context.report({ + node, + messageId, + fix(fixer) { + if (spaceRequired) { + if (after) { + return fixer.insertTextAfter(node, " "); + } + return fixer.insertTextBefore(node, " "); + } + return fixer.removeRange([ + leftToken.range[1], + rightToken.range[0], + ]); + }, + }); + } + } + + /** + * Enforces the spacing around the star if node is a generator function. + * @param {ASTNode} node A function expression or declaration node. + * @returns {void} + */ + function checkFunction(node) { + if (!node.generator) { + return; + } + + const starToken = getStarToken(node); + const prevToken = sourceCode.getTokenBefore(starToken); + const nextToken = sourceCode.getTokenAfter(starToken); + + let kind = "named"; + + if ( + node.parent.type === "MethodDefinition" || + (node.parent.type === "Property" && node.parent.method) + ) { + kind = "method"; + } else if (!node.id) { + kind = "anonymous"; + } + + // Only check before when preceded by `function`|`static` keyword + if ( + !( + kind === "method" && + starToken === sourceCode.getFirstToken(node.parent) + ) + ) { + checkSpacing(kind, "before", prevToken, starToken); + } + + checkSpacing(kind, "after", starToken, nextToken); + } + + return { + FunctionDeclaration: checkFunction, + FunctionExpression: checkFunction, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/getter-return.js b/tools/ui/node_modules/eslint/lib/rules/getter-return.js new file mode 100644 index 0000000000000000000000000000000000000000..9915597d745298abdd8abb881439bffb13140eab --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/getter-return.js @@ -0,0 +1,242 @@ +/** + * @fileoverview Enforces that a return statement is present in property getters. + * @author Aladdin-ADD(hh_2013@foxmail.com) + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const TARGET_NODE_TYPE = /^(?:Arrow)?FunctionExpression$/u; + +/** + * Checks all segments in a set and returns true if any are reachable. + * @param {Set} segments The segments to check. + * @returns {boolean} True if any segment is reachable; false otherwise. + */ +function isAnySegmentReachable(segments) { + for (const segment of segments) { + if (segment.reachable) { + return true; + } + } + + return false; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "problem", + + defaultOptions: [ + { + allowImplicit: false, + }, + ], + + docs: { + description: "Enforce `return` statements in getters", + recommended: true, + url: "https://eslint.org/docs/latest/rules/getter-return", + }, + + fixable: null, + + schema: [ + { + type: "object", + properties: { + allowImplicit: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + expected: "Expected to return a value in {{name}}.", + expectedAlways: "Expected {{name}} to always return a value.", + }, + }, + + create(context) { + const [{ allowImplicit }] = context.options; + const sourceCode = context.sourceCode; + + let funcInfo = { + upper: null, + codePath: null, + hasReturn: false, + shouldCheck: false, + node: null, + currentSegments: [], + }; + + /** + * Checks whether or not the last code path segment is reachable. + * Then reports this function if the segment is reachable. + * + * If the last code path segment is reachable, there are paths which are not + * returned or thrown. + * @param {ASTNode} node A node to check. + * @returns {void} + */ + function checkLastSegment(node) { + if ( + funcInfo.shouldCheck && + isAnySegmentReachable(funcInfo.currentSegments) + ) { + context.report({ + node, + loc: astUtils.getFunctionHeadLoc(node, sourceCode), + messageId: funcInfo.hasReturn + ? "expectedAlways" + : "expected", + data: { + name: astUtils.getFunctionNameWithKind(funcInfo.node), + }, + }); + } + } + + /** + * Checks whether a node means a getter function. + * @param {ASTNode} node a node to check. + * @returns {boolean} if node means a getter, return true; else return false. + */ + function isGetter(node) { + const parent = node.parent; + + if ( + TARGET_NODE_TYPE.test(node.type) && + node.body.type === "BlockStatement" + ) { + if (parent.kind === "get") { + return true; + } + if ( + parent.type === "Property" && + astUtils.getStaticPropertyName(parent) === "get" && + parent.parent.type === "ObjectExpression" + ) { + // Object.defineProperty() or Reflect.defineProperty() + if (parent.parent.parent.type === "CallExpression") { + const callNode = parent.parent.parent.callee; + + if ( + astUtils.isSpecificMemberAccess( + callNode, + "Object", + "defineProperty", + ) || + astUtils.isSpecificMemberAccess( + callNode, + "Reflect", + "defineProperty", + ) + ) { + return true; + } + } + + // Object.defineProperties() or Object.create() + if ( + parent.parent.parent.type === "Property" && + parent.parent.parent.parent.type === + "ObjectExpression" && + parent.parent.parent.parent.parent.type === + "CallExpression" + ) { + const callNode = + parent.parent.parent.parent.parent.callee; + + return ( + astUtils.isSpecificMemberAccess( + callNode, + "Object", + "defineProperties", + ) || + astUtils.isSpecificMemberAccess( + callNode, + "Object", + "create", + ) + ); + } + } + } + return false; + } + return { + // Stacks this function's information. + onCodePathStart(codePath, node) { + funcInfo = { + upper: funcInfo, + codePath, + hasReturn: false, + shouldCheck: isGetter(node), + node, + currentSegments: new Set(), + }; + }, + + // Pops this function's information. + onCodePathEnd() { + funcInfo = funcInfo.upper; + }, + onUnreachableCodePathSegmentStart(segment) { + funcInfo.currentSegments.add(segment); + }, + + onUnreachableCodePathSegmentEnd(segment) { + funcInfo.currentSegments.delete(segment); + }, + + onCodePathSegmentStart(segment) { + funcInfo.currentSegments.add(segment); + }, + + onCodePathSegmentEnd(segment) { + funcInfo.currentSegments.delete(segment); + }, + + // Checks the return statement is valid. + ReturnStatement(node) { + if (funcInfo.shouldCheck) { + funcInfo.hasReturn = true; + + // if allowImplicit: false, should also check node.argument + if (!allowImplicit && !node.argument) { + context.report({ + node, + messageId: "expected", + data: { + name: astUtils.getFunctionNameWithKind( + funcInfo.node, + ), + }, + }); + } + } + }, + + // Reports a given function if the last path is reachable. + "FunctionExpression:exit": checkLastSegment, + "ArrowFunctionExpression:exit": checkLastSegment, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/global-require.js b/tools/ui/node_modules/eslint/lib/rules/global-require.js new file mode 100644 index 0000000000000000000000000000000000000000..44b31814b93cd4a92b0ce52dfa5495cadaf16bab --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/global-require.js @@ -0,0 +1,117 @@ +/** + * @fileoverview Rule for disallowing require() outside of the top-level module context + * @author Jamund Ferguson + * @deprecated in ESLint v7.0.0 + */ + +"use strict"; + +const ACCEPTABLE_PARENTS = new Set([ + "AssignmentExpression", + "VariableDeclarator", + "MemberExpression", + "ExpressionStatement", + "CallExpression", + "ConditionalExpression", + "Program", + "VariableDeclaration", + "ChainExpression", +]); + +/** + * Finds the eslint-scope reference in the given scope. + * @param {Object} scope The scope to search. + * @param {ASTNode} node The identifier node. + * @returns {Reference|null} Returns the found reference or null if none were found. + */ +function findReference(scope, node) { + const references = scope.references.filter( + reference => + reference.identifier.range[0] === node.range[0] && + reference.identifier.range[1] === node.range[1], + ); + + if (references.length === 1) { + return references[0]; + } + + /* c8 ignore next */ + return null; +} + +/** + * Checks if the given identifier node is shadowed in the given scope. + * @param {Object} scope The current scope. + * @param {ASTNode} node The identifier node to check. + * @returns {boolean} Whether or not the name is shadowed. + */ +function isShadowed(scope, node) { + const reference = findReference(scope, node); + + return ( + reference && reference.resolved && reference.resolved.defs.length > 0 + ); +} + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Node.js rules were moved out of ESLint core.", + url: "https://eslint.org/docs/latest/use/migrating-to-7.0.0#deprecate-node-rules", + deprecatedSince: "7.0.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "eslint-plugin-n now maintains deprecated Node.js-related rules.", + plugin: { + name: "eslint-plugin-n", + url: "https://github.com/eslint-community/eslint-plugin-n", + }, + rule: { + name: "global-require", + url: "https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/global-require.md", + }, + }, + ], + }, + + type: "suggestion", + + docs: { + description: + "Require `require()` calls to be placed at top-level module scope", + recommended: false, + url: "https://eslint.org/docs/latest/rules/global-require", + }, + + schema: [], + messages: { + unexpected: "Unexpected require().", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + return { + CallExpression(node) { + const currentScope = sourceCode.getScope(node); + + if ( + node.callee.name === "require" && + !isShadowed(currentScope, node.callee) + ) { + const isGoodRequire = sourceCode + .getAncestors(node) + .every(parent => ACCEPTABLE_PARENTS.has(parent.type)); + + if (!isGoodRequire) { + context.report({ node, messageId: "unexpected" }); + } + } + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/grouped-accessor-pairs.js b/tools/ui/node_modules/eslint/lib/rules/grouped-accessor-pairs.js new file mode 100644 index 0000000000000000000000000000000000000000..c4ac86dc481b77ab4efcb3b91f199d3895de4fb8 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/grouped-accessor-pairs.js @@ -0,0 +1,268 @@ +/** + * @fileoverview Rule to require grouped accessor pairs in object literals and classes + * @author Milos Djermanovic + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** + * Property name if it can be computed statically, otherwise the list of the tokens of the key node. + * @typedef {string|Token[]} Key + */ + +/** + * Accessor nodes with the same key. + * @typedef {Object} AccessorData + * @property {Key} key Accessor's key + * @property {ASTNode[]} getters List of getter nodes. + * @property {ASTNode[]} setters List of setter nodes. + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not the given lists represent the equal tokens in the same order. + * Tokens are compared by their properties, not by instance. + * @param {Token[]} left First list of tokens. + * @param {Token[]} right Second list of tokens. + * @returns {boolean} `true` if the lists have same tokens. + */ +function areEqualTokenLists(left, right) { + if (left.length !== right.length) { + return false; + } + + for (let i = 0; i < left.length; i++) { + const leftToken = left[i], + rightToken = right[i]; + + if ( + leftToken.type !== rightToken.type || + leftToken.value !== rightToken.value + ) { + return false; + } + } + + return true; +} + +/** + * Checks whether or not the given keys are equal. + * @param {Key} left First key. + * @param {Key} right Second key. + * @returns {boolean} `true` if the keys are equal. + */ +function areEqualKeys(left, right) { + if (typeof left === "string" && typeof right === "string") { + // Statically computed names. + return left === right; + } + if (Array.isArray(left) && Array.isArray(right)) { + // Token lists. + return areEqualTokenLists(left, right); + } + + return false; +} + +/** + * Checks whether or not a given node is of an accessor kind ('get' or 'set'). + * @param {ASTNode} node A node to check. + * @returns {boolean} `true` if the node is of an accessor kind. + */ +function isAccessorKind(node) { + return node.kind === "get" || node.kind === "set"; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + "anyOrder", + { + enforceForTSTypes: false, + }, + ], + + docs: { + description: + "Require grouped accessor pairs in object literals and classes", + recommended: false, + url: "https://eslint.org/docs/latest/rules/grouped-accessor-pairs", + }, + + schema: [ + { enum: ["anyOrder", "getBeforeSet", "setBeforeGet"] }, + { + type: "object", + properties: { + enforceForTSTypes: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + + messages: { + notGrouped: + "Accessor pair {{ formerName }} and {{ latterName }} should be grouped.", + invalidOrder: + "Expected {{ latterName }} to be before {{ formerName }}.", + }, + }, + + create(context) { + const [order, { enforceForTSTypes }] = context.options; + const { sourceCode } = context; + + /** + * Reports the given accessor pair. + * @param {string} messageId messageId to report. + * @param {ASTNode} formerNode getter/setter node that is defined before `latterNode`. + * @param {ASTNode} latterNode getter/setter node that is defined after `formerNode`. + * @returns {void} + * @private + */ + function report(messageId, formerNode, latterNode) { + context.report({ + node: latterNode, + messageId, + loc: astUtils.getFunctionHeadLoc( + latterNode.type !== "TSMethodSignature" + ? latterNode.value + : latterNode, + sourceCode, + ), + data: { + formerName: astUtils.getFunctionNameWithKind( + formerNode.type !== "TSMethodSignature" + ? formerNode.value + : formerNode, + ), + latterName: astUtils.getFunctionNameWithKind( + latterNode.type !== "TSMethodSignature" + ? latterNode.value + : latterNode, + ), + }, + }); + } + + /** + * Checks accessor pairs in the given list of nodes. + * @param {ASTNode[]} nodes The list to check. + * @param {Function} shouldCheck – Predicate that returns `true` if the node should be checked. + * @returns {void} + * @private + */ + function checkList(nodes, shouldCheck) { + const accessors = []; + let found = false; + + for (let i = 0; i < nodes.length; i++) { + const node = nodes[i]; + + if (shouldCheck(node) && isAccessorKind(node)) { + // Creates a new `AccessorData` object for the given getter or setter node. + const name = astUtils.getStaticPropertyName(node); + const key = + name !== null ? name : sourceCode.getTokens(node.key); + + // Merges the given `AccessorData` object into the given accessors list. + for (let j = 0; j < accessors.length; j++) { + const accessor = accessors[j]; + + if (areEqualKeys(accessor.key, key)) { + accessor.getters.push( + ...(node.kind === "get" ? [node] : []), + ); + accessor.setters.push( + ...(node.kind === "set" ? [node] : []), + ); + found = true; + break; + } + } + if (!found) { + accessors.push({ + key, + getters: node.kind === "get" ? [node] : [], + setters: node.kind === "set" ? [node] : [], + }); + } + found = false; + } + } + + for (const { getters, setters } of accessors) { + // Don't report accessor properties that have duplicate getters or setters. + if (getters.length === 1 && setters.length === 1) { + const [getter] = getters, + [setter] = setters, + getterIndex = nodes.indexOf(getter), + setterIndex = nodes.indexOf(setter), + formerNode = + getterIndex < setterIndex ? getter : setter, + latterNode = + getterIndex < setterIndex ? setter : getter; + + if (Math.abs(getterIndex - setterIndex) > 1) { + report("notGrouped", formerNode, latterNode); + } else if ( + (order === "getBeforeSet" && + getterIndex > setterIndex) || + (order === "setBeforeGet" && getterIndex < setterIndex) + ) { + report("invalidOrder", formerNode, latterNode); + } + } + } + } + + return { + ObjectExpression(node) { + checkList(node.properties, n => n.type === "Property"); + }, + ClassBody(node) { + checkList( + node.body, + n => n.type === "MethodDefinition" && !n.static, + ); + checkList( + node.body, + n => n.type === "MethodDefinition" && n.static, + ); + }, + "TSTypeLiteral, TSInterfaceBody"(node) { + if (enforceForTSTypes) { + checkList( + node.type === "TSTypeLiteral" + ? node.members + : node.body, + n => n.type === "TSMethodSignature", + ); + } + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/guard-for-in.js b/tools/ui/node_modules/eslint/lib/rules/guard-for-in.js new file mode 100644 index 0000000000000000000000000000000000000000..f648aa40164e8cfbaab3aeebdc85bfadf30efadc --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/guard-for-in.js @@ -0,0 +1,85 @@ +/** + * @fileoverview Rule to flag for-in loops without if statements inside + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + docs: { + description: "Require `for-in` loops to include an `if` statement", + recommended: false, + url: "https://eslint.org/docs/latest/rules/guard-for-in", + }, + + schema: [], + messages: { + wrap: "The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype.", + }, + }, + + create(context) { + return { + ForInStatement(node) { + const body = node.body; + + // empty statement + if (body.type === "EmptyStatement") { + return; + } + + // if statement + if (body.type === "IfStatement") { + return; + } + + // empty block + if (body.type === "BlockStatement" && body.body.length === 0) { + return; + } + + // block with just if statement + if ( + body.type === "BlockStatement" && + body.body.length === 1 && + body.body[0].type === "IfStatement" + ) { + return; + } + + // block that starts with if statement + if ( + body.type === "BlockStatement" && + body.body.length >= 1 && + body.body[0].type === "IfStatement" + ) { + const i = body.body[0]; + + // ... whose consequent is a continue + if (i.consequent.type === "ContinueStatement") { + return; + } + + // ... whose consequent is a block that contains only a continue + if ( + i.consequent.type === "BlockStatement" && + i.consequent.body.length === 1 && + i.consequent.body[0].type === "ContinueStatement" + ) { + return; + } + } + + context.report({ node, messageId: "wrap" }); + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/handle-callback-err.js b/tools/ui/node_modules/eslint/lib/rules/handle-callback-err.js new file mode 100644 index 0000000000000000000000000000000000000000..d9b0641a8cbd37f7696ea75c521260b2a7bc4adc --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/handle-callback-err.js @@ -0,0 +1,122 @@ +/** + * @fileoverview Ensure handling of errors when we know they exist. + * @author Jamund Ferguson + * @deprecated in ESLint v7.0.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Node.js rules were moved out of ESLint core.", + url: "https://eslint.org/docs/latest/use/migrating-to-7.0.0#deprecate-node-rules", + deprecatedSince: "7.0.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "eslint-plugin-n now maintains deprecated Node.js-related rules.", + plugin: { + name: "eslint-plugin-n", + url: "https://github.com/eslint-community/eslint-plugin-n", + }, + rule: { + name: "handle-callback-err", + url: "https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/handle-callback-err.md", + }, + }, + ], + }, + + type: "suggestion", + + docs: { + description: "Require error handling in callbacks", + recommended: false, + url: "https://eslint.org/docs/latest/rules/handle-callback-err", + }, + + schema: [ + { + type: "string", + }, + ], + messages: { + expected: "Expected error to be handled.", + }, + }, + + create(context) { + const errorArgument = context.options[0] || "err"; + const sourceCode = context.sourceCode; + + /** + * Checks if the given argument should be interpreted as a regexp pattern. + * @param {string} stringToCheck The string which should be checked. + * @returns {boolean} Whether or not the string should be interpreted as a pattern. + */ + function isPattern(stringToCheck) { + const firstChar = stringToCheck[0]; + + return firstChar === "^"; + } + + /** + * Checks if the given name matches the configured error argument. + * @param {string} name The name which should be compared. + * @returns {boolean} Whether or not the given name matches the configured error variable name. + */ + function matchesConfiguredErrorName(name) { + if (isPattern(errorArgument)) { + const regexp = new RegExp(errorArgument, "u"); + + return regexp.test(name); + } + return name === errorArgument; + } + + /** + * Get the parameters of a given function scope. + * @param {Object} scope The function scope. + * @returns {Array} All parameters of the given scope. + */ + function getParameters(scope) { + return scope.variables.filter( + variable => + variable.defs[0] && variable.defs[0].type === "Parameter", + ); + } + + /** + * Check to see if we're handling the error object properly. + * @param {ASTNode} node The AST node to check. + * @returns {void} + */ + function checkForError(node) { + const scope = sourceCode.getScope(node), + parameters = getParameters(scope), + firstParameter = parameters[0]; + + if ( + firstParameter && + matchesConfiguredErrorName(firstParameter.name) + ) { + if (firstParameter.references.length === 0) { + context.report({ node, messageId: "expected" }); + } + } + } + + return { + FunctionDeclaration: checkForError, + FunctionExpression: checkForError, + ArrowFunctionExpression: checkForError, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/id-blacklist.js b/tools/ui/node_modules/eslint/lib/rules/id-blacklist.js new file mode 100644 index 0000000000000000000000000000000000000000..6a84827cfe45942f27865c04c0c1ffb7d87bb531 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/id-blacklist.js @@ -0,0 +1,241 @@ +/** + * @fileoverview Rule that warns when identifier names that are + * specified in the configuration are used. + * @author Keith Cirkel (http://keithcirkel.co.uk) + * @deprecated in ESLint v7.5.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether the given node represents assignment target in a normal assignment or destructuring. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is assignment target. + */ +function isAssignmentTarget(node) { + const parent = node.parent; + + return ( + // normal assignment + (parent.type === "AssignmentExpression" && parent.left === node) || + // destructuring + parent.type === "ArrayPattern" || + parent.type === "RestElement" || + (parent.type === "Property" && + parent.value === node && + parent.parent.type === "ObjectPattern") || + (parent.type === "AssignmentPattern" && parent.left === node) + ); +} + +/** + * Checks whether the given node represents an imported name that is renamed in the same import/export specifier. + * + * Examples: + * import { a as b } from 'mod'; // node `a` is renamed import + * export { a as b } from 'mod'; // node `a` is renamed import + * @param {ASTNode} node `Identifier` node to check. + * @returns {boolean} `true` if the node is a renamed import. + */ +function isRenamedImport(node) { + const parent = node.parent; + + return ( + (parent.type === "ImportSpecifier" && + parent.imported !== parent.local && + parent.imported === node) || + (parent.type === "ExportSpecifier" && + parent.parent.source && // re-export + parent.local !== parent.exported && + parent.local === node) + ); +} + +/** + * Checks whether the given node is a renamed identifier node in an ObjectPattern destructuring. + * + * Examples: + * const { a : b } = foo; // node `a` is renamed node. + * @param {ASTNode} node `Identifier` node to check. + * @returns {boolean} `true` if the node is a renamed node in an ObjectPattern destructuring. + */ +function isRenamedInDestructuring(node) { + const parent = node.parent; + + return ( + !parent.computed && + parent.type === "Property" && + parent.parent.type === "ObjectPattern" && + parent.value !== node && + parent.key === node + ); +} + +/** + * Checks whether the given node represents shorthand definition of a property in an object literal. + * @param {ASTNode} node `Identifier` node to check. + * @returns {boolean} `true` if the node is a shorthand property definition. + */ +function isShorthandPropertyDefinition(node) { + const parent = node.parent; + + return ( + parent.type === "Property" && + parent.parent.type === "ObjectExpression" && + parent.shorthand + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "The rule was renamed.", + url: "https://eslint.org/blog/2020/07/eslint-v7.5.0-released/#deprecating-id-blacklist", + deprecatedSince: "7.5.0", + availableUntil: "11.0.0", + replacedBy: [ + { + rule: { + name: "id-denylist", + url: "https://eslint.org/docs/rules/id-denylist", + }, + }, + ], + }, + + type: "suggestion", + + docs: { + description: "Disallow specified identifiers", + recommended: false, + url: "https://eslint.org/docs/latest/rules/id-blacklist", + }, + + schema: { + type: "array", + items: { + type: "string", + }, + uniqueItems: true, + }, + messages: { + restricted: "Identifier '{{name}}' is restricted.", + }, + }, + + create(context) { + const denyList = new Set(context.options); + const reportedNodes = new Set(); + const sourceCode = context.sourceCode; + + let globalScope; + + /** + * Checks whether the given name is restricted. + * @param {string} name The name to check. + * @returns {boolean} `true` if the name is restricted. + * @private + */ + function isRestricted(name) { + return denyList.has(name); + } + + /** + * Checks whether the given node represents a reference to a global variable that is not declared in the source code. + * These identifiers will be allowed, as it is assumed that user has no control over the names of external global variables. + * @param {ASTNode} node `Identifier` node to check. + * @returns {boolean} `true` if the node is a reference to a global variable. + */ + function isReferenceToGlobalVariable(node) { + const variable = globalScope.set.get(node.name); + + return ( + variable && + variable.defs.length === 0 && + variable.references.some(ref => ref.identifier === node) + ); + } + + /** + * Determines whether the given node should be checked. + * @param {ASTNode} node `Identifier` node. + * @returns {boolean} `true` if the node should be checked. + */ + function shouldCheck(node) { + const parent = node.parent; + + /* + * Member access has special rules for checking property names. + * Read access to a property with a restricted name is allowed, because it can be on an object that user has no control over. + * Write access isn't allowed, because it potentially creates a new property with a restricted name. + */ + if ( + parent.type === "MemberExpression" && + parent.property === node && + !parent.computed + ) { + return isAssignmentTarget(parent); + } + + return ( + parent.type !== "CallExpression" && + parent.type !== "NewExpression" && + !isRenamedImport(node) && + !isRenamedInDestructuring(node) && + !( + isReferenceToGlobalVariable(node) && + !isShorthandPropertyDefinition(node) + ) + ); + } + + /** + * Reports an AST node as a rule violation. + * @param {ASTNode} node The node to report. + * @returns {void} + * @private + */ + function report(node) { + /* + * We used the range instead of the node because it's possible + * for the same identifier to be represented by two different + * nodes, with the most clear example being shorthand properties: + * { foo } + * In this case, "foo" is represented by one node for the name + * and one for the value. The only way to know they are the same + * is to look at the range. + */ + if (!reportedNodes.has(node.range.toString())) { + context.report({ + node, + messageId: "restricted", + data: { + name: node.name, + }, + }); + reportedNodes.add(node.range.toString()); + } + } + + return { + Program(node) { + globalScope = sourceCode.getScope(node); + }, + + Identifier(node) { + if (isRestricted(node.name) && shouldCheck(node)) { + report(node); + } + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/id-denylist.js b/tools/ui/node_modules/eslint/lib/rules/id-denylist.js new file mode 100644 index 0000000000000000000000000000000000000000..5b9a7f4a44c71642704c49c588420e33314346b3 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/id-denylist.js @@ -0,0 +1,223 @@ +/** + * @fileoverview Rule that warns when identifier names that are + * specified in the configuration are used. + * @author Keith Cirkel (http://keithcirkel.co.uk) + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether the given node represents assignment target in a normal assignment or destructuring. + * @param {ASTNode} node The node to check. + * @returns {boolean} `true` if the node is assignment target. + */ +function isAssignmentTarget(node) { + const parent = node.parent; + + return ( + // normal assignment + (parent.type === "AssignmentExpression" && parent.left === node) || + // destructuring + parent.type === "ArrayPattern" || + parent.type === "RestElement" || + (parent.type === "Property" && + parent.value === node && + parent.parent.type === "ObjectPattern") || + (parent.type === "AssignmentPattern" && parent.left === node) + ); +} + +/** + * Checks whether the given node represents an imported name that is renamed in the same import/export specifier. + * + * Examples: + * import { a as b } from 'mod'; // node `a` is renamed import + * export { a as b } from 'mod'; // node `a` is renamed import + * @param {ASTNode} node `Identifier` node to check. + * @returns {boolean} `true` if the node is a renamed import. + */ +function isRenamedImport(node) { + const parent = node.parent; + + return ( + (parent.type === "ImportSpecifier" && + parent.imported !== parent.local && + parent.imported === node) || + (parent.type === "ExportSpecifier" && + parent.parent.source && // re-export + parent.local !== parent.exported && + parent.local === node) + ); +} + +/** + * Checks whether the given node is an ObjectPattern destructuring. + * + * Examples: + * const { a : b } = foo; + * @param {ASTNode} node `Identifier` node to check. + * @returns {boolean} `true` if the node is in an ObjectPattern destructuring. + */ +function isPropertyNameInDestructuring(node) { + const parent = node.parent; + + return ( + !parent.computed && + parent.type === "Property" && + parent.parent.type === "ObjectPattern" && + parent.key === node + ); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [], + + docs: { + description: "Disallow specified identifiers", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/id-denylist", + }, + + schema: { + type: "array", + items: { + type: "string", + }, + uniqueItems: true, + }, + messages: { + restricted: "Identifier '{{name}}' is restricted.", + restrictedPrivate: "Identifier '#{{name}}' is restricted.", + }, + }, + + create(context) { + const denyList = new Set(context.options); + const reportedNodes = new Set(); + const sourceCode = context.sourceCode; + + let globalScope; + + /** + * Checks whether the given name is restricted. + * @param {string} name The name to check. + * @returns {boolean} `true` if the name is restricted. + * @private + */ + function isRestricted(name) { + return denyList.has(name); + } + + /** + * Checks whether the given node represents a reference to a global variable that is not declared in the source code. + * These identifiers will be allowed, as it is assumed that user has no control over the names of external global variables. + * @param {ASTNode} node `Identifier` node to check. + * @returns {boolean} `true` if the node is a reference to a global variable. + */ + function isReferenceToGlobalVariable(node) { + const variable = globalScope.set.get(node.name); + + return ( + variable && + variable.defs.length === 0 && + variable.references.some(ref => ref.identifier === node) + ); + } + + /** + * Determines whether the given node should be checked. + * @param {ASTNode} node `Identifier` node. + * @returns {boolean} `true` if the node should be checked. + */ + function shouldCheck(node) { + // Import attributes are defined by environments, so naming conventions shouldn't apply to them + if (astUtils.isImportAttributeKey(node)) { + return false; + } + + const parent = node.parent; + + /* + * Member access has special rules for checking property names. + * Read access to a property with a restricted name is allowed, because it can be on an object that user has no control over. + * Write access isn't allowed, because it potentially creates a new property with a restricted name. + */ + if ( + parent.type === "MemberExpression" && + parent.property === node && + !parent.computed + ) { + return isAssignmentTarget(parent); + } + + return ( + parent.type !== "CallExpression" && + parent.type !== "NewExpression" && + !isRenamedImport(node) && + !isPropertyNameInDestructuring(node) && + !isReferenceToGlobalVariable(node) + ); + } + + /** + * Reports an AST node as a rule violation. + * @param {ASTNode} node The node to report. + * @returns {void} + * @private + */ + function report(node) { + /* + * We used the range instead of the node because it's possible + * for the same identifier to be represented by two different + * nodes, with the most clear example being shorthand properties: + * { foo } + * In this case, "foo" is represented by one node for the name + * and one for the value. The only way to know they are the same + * is to look at the range. + */ + if (!reportedNodes.has(node.range.toString())) { + const isPrivate = node.type === "PrivateIdentifier"; + + context.report({ + node, + messageId: isPrivate ? "restrictedPrivate" : "restricted", + data: { + name: node.name, + }, + }); + reportedNodes.add(node.range.toString()); + } + } + + return { + Program(node) { + globalScope = sourceCode.getScope(node); + }, + + [["Identifier", "PrivateIdentifier"]](node) { + if (isRestricted(node.name) && shouldCheck(node)) { + report(node); + } + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/id-length.js b/tools/ui/node_modules/eslint/lib/rules/id-length.js new file mode 100644 index 0000000000000000000000000000000000000000..133b84194a5a3e1500e5601eb60c2012e67b6d32 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/id-length.js @@ -0,0 +1,217 @@ +/** + * @fileoverview Rule that warns when identifier names are shorter or longer + * than the values provided in configuration. + * @author Burak Yigit Kaya aka BYK + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { getGraphemeCount } = require("../shared/string-utils"); +const { + getModuleExportName, + isImportAttributeKey, +} = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + { + exceptionPatterns: [], + exceptions: [], + min: 2, + properties: "always", + }, + ], + + docs: { + description: "Enforce minimum and maximum identifier lengths", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/id-length", + }, + + schema: [ + { + type: "object", + properties: { + min: { + type: "integer", + }, + max: { + type: "integer", + }, + exceptions: { + type: "array", + uniqueItems: true, + items: { + type: "string", + }, + }, + exceptionPatterns: { + type: "array", + uniqueItems: true, + items: { + type: "string", + }, + }, + properties: { + enum: ["always", "never"], + }, + }, + additionalProperties: false, + }, + ], + messages: { + tooShort: "Identifier name '{{name}}' is too short (< {{min}}).", + tooShortPrivate: + "Identifier name '#{{name}}' is too short (< {{min}}).", + tooLong: "Identifier name '{{name}}' is too long (> {{max}}).", + tooLongPrivate: + "Identifier name #'{{name}}' is too long (> {{max}}).", + }, + }, + + create(context) { + const [options] = context.options; + const { max: maxLength = Infinity, min: minLength } = options; + const properties = options.properties !== "never"; + const exceptions = new Set(options.exceptions); + const exceptionPatterns = options.exceptionPatterns.map( + pattern => new RegExp(pattern, "u"), + ); + const reportedNodes = new Set(); + + /** + * Checks if a string matches the provided exception patterns + * @param {string} name The string to check. + * @returns {boolean} if the string is a match + * @private + */ + function matchesExceptionPattern(name) { + return exceptionPatterns.some(pattern => pattern.test(name)); + } + + const SUPPORTED_EXPRESSIONS = { + MemberExpression: + properties && + function (parent) { + return ( + !parent.computed && + // regular property assignment + ((parent.parent.left === parent && + parent.parent.type === "AssignmentExpression") || + // or the last identifier in an ObjectPattern destructuring + (parent.parent.type === "Property" && + parent.parent.value === parent && + parent.parent.parent.type === "ObjectPattern" && + parent.parent.parent.parent.left === + parent.parent.parent)) + ); + }, + AssignmentPattern(parent, node) { + return parent.left === node; + }, + VariableDeclarator(parent, node) { + return parent.id === node; + }, + Property(parent, node) { + if (parent.parent.type === "ObjectPattern") { + const isKeyAndValueSame = + parent.value.name === parent.key.name; + + return ( + (!isKeyAndValueSame && parent.value === node) || + (isKeyAndValueSame && parent.key === node && properties) + ); + } + return ( + properties && + !isImportAttributeKey(node) && + !parent.computed && + parent.key.name === node.name + ); + }, + ImportSpecifier(parent, node) { + return ( + parent.local === node && + getModuleExportName(parent.imported) !== + getModuleExportName(parent.local) + ); + }, + ImportDefaultSpecifier: true, + ImportNamespaceSpecifier: true, + RestElement: true, + FunctionExpression: true, + ArrowFunctionExpression: true, + ClassDeclaration: true, + FunctionDeclaration: true, + MethodDefinition: true, + PropertyDefinition: true, + CatchClause: true, + ArrayPattern: true, + }; + + return { + [["Identifier", "PrivateIdentifier"]](node) { + const name = node.name; + const parent = node.parent; + + const nameLength = getGraphemeCount(name); + + const isShort = nameLength < minLength; + const isLong = nameLength > maxLength; + + if ( + !(isShort || isLong) || + exceptions.has(name) || + matchesExceptionPattern(name) + ) { + return; // Nothing to report + } + + const isValidExpression = SUPPORTED_EXPRESSIONS[parent.type]; + + /* + * We used the range instead of the node because it's possible + * for the same identifier to be represented by two different + * nodes, with the most clear example being shorthand properties: + * { foo } + * In this case, "foo" is represented by one node for the name + * and one for the value. The only way to know they are the same + * is to look at the range. + */ + if ( + isValidExpression && + !reportedNodes.has(node.range.toString()) && + (isValidExpression === true || + isValidExpression(parent, node)) + ) { + reportedNodes.add(node.range.toString()); + + let messageId = isShort ? "tooShort" : "tooLong"; + + if (node.type === "PrivateIdentifier") { + messageId += "Private"; + } + + context.report({ + node, + messageId, + data: { name, min: minLength, max: maxLength }, + }); + } + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/id-match.js b/tools/ui/node_modules/eslint/lib/rules/id-match.js new file mode 100644 index 0000000000000000000000000000000000000000..2e70cc72dd51a267c39660f65897286b9c23555a --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/id-match.js @@ -0,0 +1,363 @@ +/** + * @fileoverview Rule to flag non-matching identifiers + * @author Matthieu Larcher + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + + defaultOptions: [ + "^.+$", + { + classFields: false, + ignoreDestructuring: false, + onlyDeclarations: false, + properties: false, + }, + ], + + docs: { + description: + "Require identifiers to match a specified regular expression", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/id-match", + }, + + schema: [ + { + type: "string", + }, + { + type: "object", + properties: { + properties: { + type: "boolean", + }, + classFields: { + type: "boolean", + }, + onlyDeclarations: { + type: "boolean", + }, + ignoreDestructuring: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + messages: { + notMatch: + "Identifier '{{name}}' does not match the pattern '{{pattern}}'.", + notMatchPrivate: + "Identifier '#{{name}}' does not match the pattern '{{pattern}}'.", + }, + }, + + create(context) { + //-------------------------------------------------------------------------- + // Options + //-------------------------------------------------------------------------- + const [ + pattern, + { + classFields: checkClassFields, + ignoreDestructuring, + onlyDeclarations, + properties: checkProperties, + }, + ] = context.options; + const regexp = new RegExp(pattern, "u"); + + const sourceCode = context.sourceCode; + let globalScope; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + // contains reported nodes to avoid reporting twice on destructuring with shorthand notation + const reportedNodes = new Set(); + const ALLOWED_PARENT_TYPES = new Set([ + "CallExpression", + "NewExpression", + ]); + const DECLARATION_TYPES = new Set([ + "FunctionDeclaration", + "VariableDeclarator", + ]); + const IMPORT_TYPES = new Set([ + "ImportSpecifier", + "ImportNamespaceSpecifier", + "ImportDefaultSpecifier", + ]); + + /** + * Checks whether the given node represents a reference to a global variable that is not declared in the source code. + * These identifiers will be allowed, as it is assumed that user has no control over the names of external global variables. + * @param {ASTNode} node `Identifier` node to check. + * @returns {boolean} `true` if the node is a reference to a global variable. + */ + function isReferenceToGlobalVariable(node) { + const variable = globalScope.set.get(node.name); + + return ( + variable && + variable.defs.length === 0 && + variable.references.some(ref => ref.identifier === node) + ); + } + + /** + * Checks if a string matches the provided pattern + * @param {string} name The string to check. + * @returns {boolean} if the string is a match + * @private + */ + function isInvalid(name) { + return !regexp.test(name); + } + + /** + * Checks if a parent of a node is an ObjectPattern. + * @param {ASTNode} node The node to check. + * @returns {boolean} if the node is inside an ObjectPattern + * @private + */ + function isInsideObjectPattern(node) { + let { parent } = node; + + while (parent) { + if (parent.type === "ObjectPattern") { + return true; + } + + parent = parent.parent; + } + + return false; + } + + /** + * Verifies if we should report an error or not based on the effective + * parent node and the identifier name. + * @param {ASTNode} effectiveParent The effective parent node of the node to be reported + * @param {string} name The identifier name of the identifier node + * @returns {boolean} whether an error should be reported or not + */ + function shouldReport(effectiveParent, name) { + return ( + (!onlyDeclarations || + DECLARATION_TYPES.has(effectiveParent.type)) && + !ALLOWED_PARENT_TYPES.has(effectiveParent.type) && + isInvalid(name) + ); + } + + /** + * Reports an AST node as a rule violation. + * @param {ASTNode} node The node to report. + * @returns {void} + * @private + */ + function report(node) { + /* + * We used the range instead of the node because it's possible + * for the same identifier to be represented by two different + * nodes, with the most clear example being shorthand properties: + * { foo } + * In this case, "foo" is represented by one node for the name + * and one for the value. The only way to know they are the same + * is to look at the range. + */ + if (!reportedNodes.has(node.range.toString())) { + const messageId = + node.type === "PrivateIdentifier" + ? "notMatchPrivate" + : "notMatch"; + + context.report({ + node, + messageId, + data: { + name: node.name, + pattern, + }, + }); + reportedNodes.add(node.range.toString()); + } + } + + return { + Program(node) { + globalScope = sourceCode.getScope(node); + }, + + Identifier(node) { + const name = node.name, + parent = node.parent, + effectiveParent = + parent.type === "MemberExpression" + ? parent.parent + : parent; + + if ( + isReferenceToGlobalVariable(node) || + astUtils.isImportAttributeKey(node) + ) { + return; + } + + if (parent.type === "MemberExpression") { + if (!checkProperties) { + return; + } + + // Always check object names + if ( + parent.object.type === "Identifier" && + parent.object.name === name + ) { + if (isInvalid(name)) { + report(node); + } + + // Report AssignmentExpressions left side's assigned variable id + } else if ( + effectiveParent.type === "AssignmentExpression" && + effectiveParent.left.type === "MemberExpression" && + effectiveParent.left.property.name === node.name + ) { + if (isInvalid(name)) { + report(node); + } + + // Report AssignmentExpressions only if they are the left side of the assignment + } else if ( + effectiveParent.type === "AssignmentExpression" && + effectiveParent.right.type !== "MemberExpression" + ) { + if (isInvalid(name)) { + report(node); + } + } + + // For https://github.com/eslint/eslint/issues/15123 + } else if ( + parent.type === "Property" && + parent.parent.type === "ObjectExpression" && + parent.key === node && + !parent.computed + ) { + if (checkProperties && isInvalid(name)) { + report(node); + } + + /* + * Properties have their own rules, and + * AssignmentPattern nodes can be treated like Properties: + * e.g.: const { no_camelcased = false } = bar; + */ + } else if ( + parent.type === "Property" || + parent.type === "AssignmentPattern" + ) { + if ( + parent.parent && + parent.parent.type === "ObjectPattern" + ) { + if ( + !ignoreDestructuring && + parent.shorthand && + parent.value.left && + isInvalid(name) + ) { + report(node); + } + + const assignmentKeyEqualsValue = + parent.key.name === parent.value.name; + + // prevent checking righthand side of destructured object + if (!assignmentKeyEqualsValue && parent.key === node) { + return; + } + + const valueIsInvalid = + parent.value.name && isInvalid(name); + + // ignore destructuring if the option is set, unless a new identifier is created + if ( + valueIsInvalid && + !(assignmentKeyEqualsValue && ignoreDestructuring) + ) { + report(node); + } + } + + // never check properties or always ignore destructuring + if ( + (!checkProperties && !parent.computed) || + (ignoreDestructuring && isInsideObjectPattern(node)) + ) { + return; + } + + // don't check right hand side of AssignmentExpression to prevent duplicate warnings + if ( + parent.right !== node && + shouldReport(effectiveParent, name) + ) { + report(node); + } + + // Check if it's an import specifier + } else if (IMPORT_TYPES.has(parent.type)) { + // Report only if the local imported identifier is invalid + if ( + parent.local && + parent.local.name === node.name && + isInvalid(name) + ) { + report(node); + } + } else if (parent.type === "PropertyDefinition") { + if (checkClassFields && isInvalid(name)) { + report(node); + } + + // Report anything that is invalid that isn't a CallExpression + } else if (shouldReport(effectiveParent, name)) { + report(node); + } + }, + + PrivateIdentifier(node) { + const isClassField = node.parent.type === "PropertyDefinition"; + + if (isClassField && !checkClassFields) { + return; + } + + if (isInvalid(node.name)) { + report(node); + } + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/implicit-arrow-linebreak.js b/tools/ui/node_modules/eslint/lib/rules/implicit-arrow-linebreak.js new file mode 100644 index 0000000000000000000000000000000000000000..e32d0cafc9c90ca5c55ae7daff7a495ed5cf5b70 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/implicit-arrow-linebreak.js @@ -0,0 +1,125 @@ +/** + * @fileoverview enforce the location of arrow function bodies + * @author Sharmila Jesupaul + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +const { isCommentToken, isNotOpeningParenToken } = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "implicit-arrow-linebreak", + url: "https://eslint.style/rules/implicit-arrow-linebreak", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce the location of arrow function bodies", + recommended: false, + url: "https://eslint.org/docs/latest/rules/implicit-arrow-linebreak", + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["beside", "below"], + }, + ], + messages: { + expected: "Expected a linebreak before this expression.", + unexpected: "Expected no linebreak before this expression.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const option = context.options[0] || "beside"; + + /** + * Validates the location of an arrow function body + * @param {ASTNode} node The arrow function body + * @returns {void} + */ + function validateExpression(node) { + if (node.body.type === "BlockStatement") { + return; + } + + const arrowToken = sourceCode.getTokenBefore( + node.body, + isNotOpeningParenToken, + ); + const firstTokenOfBody = sourceCode.getTokenAfter(arrowToken); + + if ( + arrowToken.loc.end.line === firstTokenOfBody.loc.start.line && + option === "below" + ) { + context.report({ + node: firstTokenOfBody, + messageId: "expected", + fix: fixer => + fixer.insertTextBefore(firstTokenOfBody, "\n"), + }); + } else if ( + arrowToken.loc.end.line !== firstTokenOfBody.loc.start.line && + option === "beside" + ) { + context.report({ + node: firstTokenOfBody, + messageId: "unexpected", + fix(fixer) { + if ( + sourceCode.getFirstTokenBetween( + arrowToken, + firstTokenOfBody, + { + includeComments: true, + filter: isCommentToken, + }, + ) + ) { + return null; + } + + return fixer.replaceTextRange( + [arrowToken.range[1], firstTokenOfBody.range[0]], + " ", + ); + }, + }); + } + } + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + return { + ArrowFunctionExpression: node => validateExpression(node), + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/indent-legacy.js b/tools/ui/node_modules/eslint/lib/rules/indent-legacy.js new file mode 100644 index 0000000000000000000000000000000000000000..3c14ff767e252a1480439893437f2561ba6093a6 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/indent-legacy.js @@ -0,0 +1,1369 @@ +/** + * @fileoverview This option sets a specific tab width for your code + * + * This rule has been ported and modified from nodeca. + * @author Vitaly Puzrin + * @author Gyandeep Singh + * @deprecated in ESLint v4.0.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ +// this rule has known coverage issues, but it's deprecated and shouldn't be updated in the future anyway. +/* c8 ignore next */ +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Enforce consistent indentation", + recommended: false, + url: "https://eslint.org/docs/latest/rules/indent-legacy", + }, + + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "4.0.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "indent", + url: "https://eslint.style/rules/indent", + }, + }, + ], + }, + + fixable: "whitespace", + + schema: [ + { + oneOf: [ + { + enum: ["tab"], + }, + { + type: "integer", + minimum: 0, + }, + ], + }, + { + type: "object", + properties: { + SwitchCase: { + type: "integer", + minimum: 0, + }, + VariableDeclarator: { + oneOf: [ + { + type: "integer", + minimum: 0, + }, + { + type: "object", + properties: { + var: { + type: "integer", + minimum: 0, + }, + let: { + type: "integer", + minimum: 0, + }, + const: { + type: "integer", + minimum: 0, + }, + }, + }, + ], + }, + outerIIFEBody: { + type: "integer", + minimum: 0, + }, + MemberExpression: { + type: "integer", + minimum: 0, + }, + FunctionDeclaration: { + type: "object", + properties: { + parameters: { + oneOf: [ + { + type: "integer", + minimum: 0, + }, + { + enum: ["first"], + }, + ], + }, + body: { + type: "integer", + minimum: 0, + }, + }, + }, + FunctionExpression: { + type: "object", + properties: { + parameters: { + oneOf: [ + { + type: "integer", + minimum: 0, + }, + { + enum: ["first"], + }, + ], + }, + body: { + type: "integer", + minimum: 0, + }, + }, + }, + CallExpression: { + type: "object", + properties: { + parameters: { + oneOf: [ + { + type: "integer", + minimum: 0, + }, + { + enum: ["first"], + }, + ], + }, + }, + }, + ArrayExpression: { + oneOf: [ + { + type: "integer", + minimum: 0, + }, + { + enum: ["first"], + }, + ], + }, + ObjectExpression: { + oneOf: [ + { + type: "integer", + minimum: 0, + }, + { + enum: ["first"], + }, + ], + }, + }, + additionalProperties: false, + }, + ], + messages: { + expected: + "Expected indentation of {{expected}} but found {{actual}}.", + }, + }, + + create(context) { + const DEFAULT_VARIABLE_INDENT = 1; + const DEFAULT_PARAMETER_INDENT = null; // For backwards compatibility, don't check parameter indentation unless specified in the config + const DEFAULT_FUNCTION_BODY_INDENT = 1; + + let indentType = "space"; + let indentSize = 4; + const options = { + SwitchCase: 0, + VariableDeclarator: { + var: DEFAULT_VARIABLE_INDENT, + let: DEFAULT_VARIABLE_INDENT, + const: DEFAULT_VARIABLE_INDENT, + }, + outerIIFEBody: null, + FunctionDeclaration: { + parameters: DEFAULT_PARAMETER_INDENT, + body: DEFAULT_FUNCTION_BODY_INDENT, + }, + FunctionExpression: { + parameters: DEFAULT_PARAMETER_INDENT, + body: DEFAULT_FUNCTION_BODY_INDENT, + }, + CallExpression: { + arguments: DEFAULT_PARAMETER_INDENT, + }, + ArrayExpression: 1, + ObjectExpression: 1, + }; + + const sourceCode = context.sourceCode; + + if (context.options.length) { + if (context.options[0] === "tab") { + indentSize = 1; + indentType = "tab"; + } /* c8 ignore start */ else if ( + typeof context.options[0] === "number" + ) { + indentSize = context.options[0]; + indentType = "space"; + } /* c8 ignore stop */ + + if (context.options[1]) { + const opts = context.options[1]; + + options.SwitchCase = opts.SwitchCase || 0; + const variableDeclaratorRules = opts.VariableDeclarator; + + if (typeof variableDeclaratorRules === "number") { + options.VariableDeclarator = { + var: variableDeclaratorRules, + let: variableDeclaratorRules, + const: variableDeclaratorRules, + }; + } else if (typeof variableDeclaratorRules === "object") { + Object.assign( + options.VariableDeclarator, + variableDeclaratorRules, + ); + } + + if (typeof opts.outerIIFEBody === "number") { + options.outerIIFEBody = opts.outerIIFEBody; + } + + if (typeof opts.MemberExpression === "number") { + options.MemberExpression = opts.MemberExpression; + } + + if (typeof opts.FunctionDeclaration === "object") { + Object.assign( + options.FunctionDeclaration, + opts.FunctionDeclaration, + ); + } + + if (typeof opts.FunctionExpression === "object") { + Object.assign( + options.FunctionExpression, + opts.FunctionExpression, + ); + } + + if (typeof opts.CallExpression === "object") { + Object.assign(options.CallExpression, opts.CallExpression); + } + + if ( + typeof opts.ArrayExpression === "number" || + typeof opts.ArrayExpression === "string" + ) { + options.ArrayExpression = opts.ArrayExpression; + } + + if ( + typeof opts.ObjectExpression === "number" || + typeof opts.ObjectExpression === "string" + ) { + options.ObjectExpression = opts.ObjectExpression; + } + } + } + + const caseIndentStore = {}; + + /** + * Creates an error message for a line, given the expected/actual indentation. + * @param {number} expectedAmount The expected amount of indentation characters for this line + * @param {number} actualSpaces The actual number of indentation spaces that were found on this line + * @param {number} actualTabs The actual number of indentation tabs that were found on this line + * @returns {string} An error message for this line + */ + function createErrorMessageData( + expectedAmount, + actualSpaces, + actualTabs, + ) { + const expectedStatement = `${expectedAmount} ${indentType}${expectedAmount === 1 ? "" : "s"}`; // e.g. "2 tabs" + const foundSpacesWord = `space${actualSpaces === 1 ? "" : "s"}`; // e.g. "space" + const foundTabsWord = `tab${actualTabs === 1 ? "" : "s"}`; // e.g. "tabs" + let foundStatement; + + if (actualSpaces > 0 && actualTabs > 0) { + foundStatement = `${actualSpaces} ${foundSpacesWord} and ${actualTabs} ${foundTabsWord}`; // e.g. "1 space and 2 tabs" + } else if (actualSpaces > 0) { + /* + * Abbreviate the message if the expected indentation is also spaces. + * e.g. 'Expected 4 spaces but found 2' rather than 'Expected 4 spaces but found 2 spaces' + */ + foundStatement = + indentType === "space" + ? actualSpaces + : `${actualSpaces} ${foundSpacesWord}`; + } else if (actualTabs > 0) { + foundStatement = + indentType === "tab" + ? actualTabs + : `${actualTabs} ${foundTabsWord}`; + } else { + foundStatement = "0"; + } + return { + expected: expectedStatement, + actual: foundStatement, + }; + } + + /** + * Reports a given indent violation + * @param {ASTNode} node Node violating the indent rule + * @param {number} needed Expected indentation character count + * @param {number} gottenSpaces Indentation space count in the actual node/code + * @param {number} gottenTabs Indentation tab count in the actual node/code + * @param {Object} [loc] Error line and column location + * @param {boolean} isLastNodeCheck Is the error for last node check + * @returns {void} + */ + function report( + node, + needed, + gottenSpaces, + gottenTabs, + loc, + isLastNodeCheck, + ) { + if (gottenSpaces && gottenTabs) { + // To avoid conflicts with `no-mixed-spaces-and-tabs`, don't report lines that have both spaces and tabs. + return; + } + + const desiredIndent = (indentType === "space" ? " " : "\t").repeat( + needed, + ); + + const textRange = isLastNodeCheck + ? [ + node.range[1] - node.loc.end.column, + node.range[1] - + node.loc.end.column + + gottenSpaces + + gottenTabs, + ] + : [ + node.range[0] - node.loc.start.column, + node.range[0] - + node.loc.start.column + + gottenSpaces + + gottenTabs, + ]; + + context.report({ + node, + loc, + messageId: "expected", + data: createErrorMessageData(needed, gottenSpaces, gottenTabs), + fix: fixer => fixer.replaceTextRange(textRange, desiredIndent), + }); + } + + /** + * Get the actual indent of node + * @param {ASTNode|Token} node Node to examine + * @param {boolean} [byLastLine=false] get indent of node's last line + * @returns {Object} The node's indent. Contains keys `space` and `tab`, representing the indent of each character. Also + * contains keys `goodChar` and `badChar`, where `goodChar` is the amount of the user's desired indentation character, and + * `badChar` is the amount of the other indentation character. + */ + function getNodeIndent(node, byLastLine) { + const token = byLastLine + ? sourceCode.getLastToken(node) + : sourceCode.getFirstToken(node); + const srcCharsBeforeNode = sourceCode + .getText(token, token.loc.start.column) + .split(""); + const indentChars = srcCharsBeforeNode.slice( + 0, + srcCharsBeforeNode.findIndex( + char => char !== " " && char !== "\t", + ), + ); + const spaces = indentChars.filter(char => char === " ").length; + const tabs = indentChars.filter(char => char === "\t").length; + + return { + space: spaces, + tab: tabs, + goodChar: indentType === "space" ? spaces : tabs, + badChar: indentType === "space" ? tabs : spaces, + }; + } + + /** + * Checks node is the first in its own start line. By default it looks by start line. + * @param {ASTNode} node The node to check + * @param {boolean} [byEndLocation=false] Lookup based on start position or end + * @returns {boolean} true if its the first in the its start line + */ + function isNodeFirstInLine(node, byEndLocation) { + const firstToken = + byEndLocation === true + ? sourceCode.getLastToken(node, 1) + : sourceCode.getTokenBefore(node), + startLine = + byEndLocation === true + ? node.loc.end.line + : node.loc.start.line, + endLine = firstToken ? firstToken.loc.end.line : -1; + + return startLine !== endLine; + } + + /** + * Check indent for node + * @param {ASTNode} node Node to check + * @param {number} neededIndent needed indent + * @returns {void} + */ + function checkNodeIndent(node, neededIndent) { + const actualIndent = getNodeIndent(node, false); + + if ( + node.type !== "ArrayExpression" && + node.type !== "ObjectExpression" && + (actualIndent.goodChar !== neededIndent || + actualIndent.badChar !== 0) && + isNodeFirstInLine(node) + ) { + report( + node, + neededIndent, + actualIndent.space, + actualIndent.tab, + ); + } + + if (node.type === "IfStatement" && node.alternate) { + const elseToken = sourceCode.getTokenBefore(node.alternate); + + checkNodeIndent(elseToken, neededIndent); + + if (!isNodeFirstInLine(node.alternate)) { + checkNodeIndent(node.alternate, neededIndent); + } + } + + if (node.type === "TryStatement" && node.handler) { + const catchToken = sourceCode.getFirstToken(node.handler); + + checkNodeIndent(catchToken, neededIndent); + } + + if (node.type === "TryStatement" && node.finalizer) { + const finallyToken = sourceCode.getTokenBefore(node.finalizer); + + checkNodeIndent(finallyToken, neededIndent); + } + + if (node.type === "DoWhileStatement") { + const whileToken = sourceCode.getTokenAfter(node.body); + + checkNodeIndent(whileToken, neededIndent); + } + } + + /** + * Check indent for nodes list + * @param {ASTNode[]} nodes list of node objects + * @param {number} indent needed indent + * @returns {void} + */ + function checkNodesIndent(nodes, indent) { + nodes.forEach(node => checkNodeIndent(node, indent)); + } + + /** + * Check last node line indent this detects, that block closed correctly + * @param {ASTNode} node Node to examine + * @param {number} lastLineIndent needed indent + * @returns {void} + */ + function checkLastNodeLineIndent(node, lastLineIndent) { + const lastToken = sourceCode.getLastToken(node); + const endIndent = getNodeIndent(lastToken, true); + + if ( + (endIndent.goodChar !== lastLineIndent || + endIndent.badChar !== 0) && + isNodeFirstInLine(node, true) + ) { + report( + node, + lastLineIndent, + endIndent.space, + endIndent.tab, + { + line: lastToken.loc.start.line, + column: lastToken.loc.start.column, + }, + true, + ); + } + } + + /** + * Check last node line indent this detects, that block closed correctly + * This function for more complicated return statement case, where closing parenthesis may be followed by ';' + * @param {ASTNode} node Node to examine + * @param {number} firstLineIndent first line needed indent + * @returns {void} + */ + function checkLastReturnStatementLineIndent(node, firstLineIndent) { + /* + * in case if return statement ends with ');' we have traverse back to ')' + * otherwise we'll measure indent for ';' and replace ')' + */ + const lastToken = sourceCode.getLastToken( + node, + astUtils.isClosingParenToken, + ); + const textBeforeClosingParenthesis = sourceCode + .getText(lastToken, lastToken.loc.start.column) + .slice(0, -1); + + if (textBeforeClosingParenthesis.trim()) { + // There are tokens before the closing paren, don't report this case + return; + } + + const endIndent = getNodeIndent(lastToken, true); + + if (endIndent.goodChar !== firstLineIndent) { + report( + node, + firstLineIndent, + endIndent.space, + endIndent.tab, + { + line: lastToken.loc.start.line, + column: lastToken.loc.start.column, + }, + true, + ); + } + } + + /** + * Check first node line indent is correct + * @param {ASTNode} node Node to examine + * @param {number} firstLineIndent needed indent + * @returns {void} + */ + function checkFirstNodeLineIndent(node, firstLineIndent) { + const startIndent = getNodeIndent(node, false); + + if ( + (startIndent.goodChar !== firstLineIndent || + startIndent.badChar !== 0) && + isNodeFirstInLine(node) + ) { + report( + node, + firstLineIndent, + startIndent.space, + startIndent.tab, + { + line: node.loc.start.line, + column: node.loc.start.column, + }, + ); + } + } + + /** + * Returns a parent node of given node based on a specified type + * if not present then return null + * @param {ASTNode} node node to examine + * @param {string} type type that is being looked for + * @param {string} stopAtList end points for the evaluating code + * @returns {ASTNode|void} if found then node otherwise null + */ + function getParentNodeByType(node, type, stopAtList) { + let parent = node.parent; + const stopAtSet = new Set(stopAtList || ["Program"]); + + while ( + parent.type !== type && + !stopAtSet.has(parent.type) && + parent.type !== "Program" + ) { + parent = parent.parent; + } + + return parent.type === type ? parent : null; + } + + /** + * Returns the VariableDeclarator based on the current node + * if not present then return null + * @param {ASTNode} node node to examine + * @returns {ASTNode|void} if found then node otherwise null + */ + function getVariableDeclaratorNode(node) { + return getParentNodeByType(node, "VariableDeclarator"); + } + + /** + * Check to see if the node is part of the multi-line variable declaration. + * Also if its on the same line as the varNode + * @param {ASTNode} node node to check + * @param {ASTNode} varNode variable declaration node to check against + * @returns {boolean} True if all the above condition satisfy + */ + function isNodeInVarOnTop(node, varNode) { + return ( + varNode && + varNode.parent.loc.start.line === node.loc.start.line && + varNode.parent.declarations.length > 1 + ); + } + + /** + * Check to see if the argument before the callee node is multi-line and + * there should only be 1 argument before the callee node + * @param {ASTNode} node node to check + * @returns {boolean} True if arguments are multi-line + */ + function isArgBeforeCalleeNodeMultiline(node) { + const parent = node.parent; + + if (parent.arguments.length >= 2 && parent.arguments[1] === node) { + return ( + parent.arguments[0].loc.end.line > + parent.arguments[0].loc.start.line + ); + } + + return false; + } + + /** + * Check to see if the node is a file level IIFE + * @param {ASTNode} node The function node to check. + * @returns {boolean} True if the node is the outer IIFE + */ + function isOuterIIFE(node) { + const parent = node.parent; + let stmt = parent.parent; + + /* + * Verify that the node is an IIEF + */ + if (parent.type !== "CallExpression" || parent.callee !== node) { + return false; + } + + /* + * Navigate legal ancestors to determine whether this IIEF is outer + */ + while ( + (stmt.type === "UnaryExpression" && + (stmt.operator === "!" || + stmt.operator === "~" || + stmt.operator === "+" || + stmt.operator === "-")) || + stmt.type === "AssignmentExpression" || + stmt.type === "LogicalExpression" || + stmt.type === "SequenceExpression" || + stmt.type === "VariableDeclarator" + ) { + stmt = stmt.parent; + } + + return ( + (stmt.type === "ExpressionStatement" || + stmt.type === "VariableDeclaration") && + stmt.parent && + stmt.parent.type === "Program" + ); + } + + /** + * Check indent for function block content + * @param {ASTNode} node A BlockStatement node that is inside of a function. + * @returns {void} + */ + function checkIndentInFunctionBlock(node) { + /* + * Search first caller in chain. + * Ex.: + * + * Models <- Identifier + * .User + * .find() + * .exec(function() { + * // function body + * }); + * + * Looks for 'Models' + */ + const calleeNode = node.parent; // FunctionExpression + let indent; + + if ( + calleeNode.parent && + (calleeNode.parent.type === "Property" || + calleeNode.parent.type === "ArrayExpression") + ) { + // If function is part of array or object, comma can be put at left + indent = getNodeIndent(calleeNode, false).goodChar; + } else { + // If function is standalone, simple calculate indent + indent = getNodeIndent(calleeNode).goodChar; + } + + if (calleeNode.parent.type === "CallExpression") { + const calleeParent = calleeNode.parent; + + if ( + calleeNode.type !== "FunctionExpression" && + calleeNode.type !== "ArrowFunctionExpression" + ) { + if ( + calleeParent && + calleeParent.loc.start.line < node.loc.start.line + ) { + indent = getNodeIndent(calleeParent).goodChar; + } + } else { + if ( + isArgBeforeCalleeNodeMultiline(calleeNode) && + calleeParent.callee.loc.start.line === + calleeParent.callee.loc.end.line && + !isNodeFirstInLine(calleeNode) + ) { + indent = getNodeIndent(calleeParent).goodChar; + } + } + } + + /* + * function body indent should be indent + indent size, unless this + * is a FunctionDeclaration, FunctionExpression, or outer IIFE and the corresponding options are enabled. + */ + let functionOffset = indentSize; + + if (options.outerIIFEBody !== null && isOuterIIFE(calleeNode)) { + functionOffset = options.outerIIFEBody * indentSize; + } else if (calleeNode.type === "FunctionExpression") { + functionOffset = options.FunctionExpression.body * indentSize; + } else if (calleeNode.type === "FunctionDeclaration") { + functionOffset = options.FunctionDeclaration.body * indentSize; + } + indent += functionOffset; + + // check if the node is inside a variable + const parentVarNode = getVariableDeclaratorNode(node); + + if (parentVarNode && isNodeInVarOnTop(node, parentVarNode)) { + indent += + indentSize * + options.VariableDeclarator[parentVarNode.parent.kind]; + } + + if (node.body.length > 0) { + checkNodesIndent(node.body, indent); + } + + checkLastNodeLineIndent(node, indent - functionOffset); + } + + /** + * Checks if the given node starts and ends on the same line + * @param {ASTNode} node The node to check + * @returns {boolean} Whether or not the block starts and ends on the same line. + */ + function isSingleLineNode(node) { + const lastToken = sourceCode.getLastToken(node), + startLine = node.loc.start.line, + endLine = lastToken.loc.end.line; + + return startLine === endLine; + } + + /** + * Check indent for array block content or object block content + * @param {ASTNode} node node to examine + * @returns {void} + */ + function checkIndentInArrayOrObjectBlock(node) { + // Skip inline + if (isSingleLineNode(node)) { + return; + } + + let elements = + node.type === "ArrayExpression" + ? node.elements + : node.properties; + + // filter out empty elements example would be [ , 2] so remove first element as espree considers it as null + elements = elements.filter(elem => elem !== null); + + let nodeIndent; + let elementsIndent; + const parentVarNode = getVariableDeclaratorNode(node); + + // TODO - come up with a better strategy in future + if (isNodeFirstInLine(node)) { + const parent = node.parent; + + nodeIndent = getNodeIndent(parent).goodChar; + if ( + !parentVarNode || + parentVarNode.loc.start.line !== node.loc.start.line + ) { + if ( + parent.type !== "VariableDeclarator" || + parentVarNode === parentVarNode.parent.declarations[0] + ) { + if ( + parent.type === "VariableDeclarator" && + parentVarNode.loc.start.line === + parent.loc.start.line + ) { + nodeIndent += + indentSize * + options.VariableDeclarator[ + parentVarNode.parent.kind + ]; + } else if ( + parent.type === "ObjectExpression" || + parent.type === "ArrayExpression" + ) { + const parentElements = + node.parent.type === "ObjectExpression" + ? node.parent.properties + : node.parent.elements; + + if ( + parentElements[0] && + parentElements[0].loc.start.line === + parent.loc.start.line && + parentElements[0].loc.end.line !== + parent.loc.start.line + ) { + /* + * If the first element of the array spans multiple lines, don't increase the expected indentation of the rest. + * e.g. [{ + * foo: 1 + * }, + * { + * bar: 1 + * }] + * the second object is not indented. + */ + } else if ( + typeof options[parent.type] === "number" + ) { + nodeIndent += options[parent.type] * indentSize; + } else { + nodeIndent = parentElements[0].loc.start.column; + } + } else if ( + parent.type === "CallExpression" || + parent.type === "NewExpression" + ) { + if ( + typeof options.CallExpression.arguments === + "number" + ) { + nodeIndent += + options.CallExpression.arguments * + indentSize; + } else if ( + options.CallExpression.arguments === "first" + ) { + if (parent.arguments.includes(node)) { + nodeIndent = + parent.arguments[0].loc.start.column; + } + } else { + nodeIndent += indentSize; + } + } else if ( + parent.type === "LogicalExpression" || + parent.type === "ArrowFunctionExpression" + ) { + nodeIndent += indentSize; + } + } + } + + checkFirstNodeLineIndent(node, nodeIndent); + } else { + nodeIndent = getNodeIndent(node).goodChar; + } + + if (options[node.type] === "first") { + elementsIndent = elements.length + ? elements[0].loc.start.column + : 0; // If there are no elements, elementsIndent doesn't matter. + } else { + elementsIndent = nodeIndent + indentSize * options[node.type]; + } + + /* + * Check if the node is a multiple variable declaration; if so, then + * make sure indentation takes that into account. + */ + if (isNodeInVarOnTop(node, parentVarNode)) { + elementsIndent += + indentSize * + options.VariableDeclarator[parentVarNode.parent.kind]; + } + + checkNodesIndent(elements, elementsIndent); + + if (elements.length > 0) { + // Skip last block line check if last item in same line + if (elements.at(-1).loc.end.line === node.loc.end.line) { + return; + } + } + + checkLastNodeLineIndent( + node, + nodeIndent + + (isNodeInVarOnTop(node, parentVarNode) + ? options.VariableDeclarator[ + parentVarNode.parent.kind + ] * indentSize + : 0), + ); + } + + /** + * Check if the node or node body is a BlockStatement or not + * @param {ASTNode} node node to test + * @returns {boolean} True if it or its body is a block statement + */ + function isNodeBodyBlock(node) { + return ( + node.type === "BlockStatement" || + node.type === "ClassBody" || + (node.body && node.body.type === "BlockStatement") || + (node.consequent && node.consequent.type === "BlockStatement") + ); + } + + /** + * Check indentation for blocks + * @param {ASTNode} node node to check + * @returns {void} + */ + function blockIndentationCheck(node) { + // Skip inline blocks + if (isSingleLineNode(node)) { + return; + } + + if ( + node.parent && + (node.parent.type === "FunctionExpression" || + node.parent.type === "FunctionDeclaration" || + node.parent.type === "ArrowFunctionExpression") + ) { + checkIndentInFunctionBlock(node); + return; + } + + let indent; + let nodesToCheck; + + /* + * For this statements we should check indent from statement beginning, + * not from the beginning of the block. + */ + const statementsWithProperties = [ + "IfStatement", + "WhileStatement", + "ForStatement", + "ForInStatement", + "ForOfStatement", + "DoWhileStatement", + "ClassDeclaration", + "TryStatement", + ]; + + if ( + node.parent && + statementsWithProperties.includes(node.parent.type) && + isNodeBodyBlock(node) + ) { + indent = getNodeIndent(node.parent).goodChar; + } else if (node.parent && node.parent.type === "CatchClause") { + indent = getNodeIndent(node.parent.parent).goodChar; + } else { + indent = getNodeIndent(node).goodChar; + } + + if ( + node.type === "IfStatement" && + node.consequent.type !== "BlockStatement" + ) { + nodesToCheck = [node.consequent]; + } else if (Array.isArray(node.body)) { + nodesToCheck = node.body; + } else { + nodesToCheck = [node.body]; + } + + if (nodesToCheck.length > 0) { + checkNodesIndent(nodesToCheck, indent + indentSize); + } + + if (node.type === "BlockStatement") { + checkLastNodeLineIndent(node, indent); + } + } + + /** + * Filter out the elements which are on the same line of each other or the node. + * basically have only 1 elements from each line except the variable declaration line. + * @param {ASTNode} node Variable declaration node + * @returns {ASTNode[]} Filtered elements + */ + function filterOutSameLineVars(node) { + return node.declarations.reduce((finalCollection, elem) => { + const lastElem = finalCollection.at(-1); + + if ( + (elem.loc.start.line !== node.loc.start.line && + !lastElem) || + (lastElem && + lastElem.loc.start.line !== elem.loc.start.line) + ) { + finalCollection.push(elem); + } + + return finalCollection; + }, []); + } + + /** + * Check indentation for variable declarations + * @param {ASTNode} node node to examine + * @returns {void} + */ + function checkIndentInVariableDeclarations(node) { + const elements = filterOutSameLineVars(node); + const nodeIndent = getNodeIndent(node).goodChar; + const lastElement = elements.at(-1); + + const elementsIndent = + nodeIndent + indentSize * options.VariableDeclarator[node.kind]; + + checkNodesIndent(elements, elementsIndent); + + // Only check the last line if there is any token after the last item + if ( + sourceCode.getLastToken(node).loc.end.line <= + lastElement.loc.end.line + ) { + return; + } + + const tokenBeforeLastElement = + sourceCode.getTokenBefore(lastElement); + + if (tokenBeforeLastElement.value === ",") { + // Special case for comma-first syntax where the semicolon is indented + checkLastNodeLineIndent( + node, + getNodeIndent(tokenBeforeLastElement).goodChar, + ); + } else { + checkLastNodeLineIndent(node, elementsIndent - indentSize); + } + } + + /** + * Check and decide whether to check for indentation for blockless nodes + * Scenarios are for or while statements without braces around them + * @param {ASTNode} node node to examine + * @returns {void} + */ + function blockLessNodes(node) { + if (node.body.type !== "BlockStatement") { + blockIndentationCheck(node); + } + } + + /** + * Returns the expected indentation for the case statement + * @param {ASTNode} node node to examine + * @param {number} [providedSwitchIndent] indent for switch statement + * @returns {number} indent size + */ + function expectedCaseIndent(node, providedSwitchIndent) { + const switchNode = + node.type === "SwitchStatement" ? node : node.parent; + const switchIndent = + typeof providedSwitchIndent === "undefined" + ? getNodeIndent(switchNode).goodChar + : providedSwitchIndent; + let caseIndent; + + if (caseIndentStore[switchNode.loc.start.line]) { + return caseIndentStore[switchNode.loc.start.line]; + } + + if (switchNode.cases.length > 0 && options.SwitchCase === 0) { + caseIndent = switchIndent; + } else { + caseIndent = switchIndent + indentSize * options.SwitchCase; + } + + caseIndentStore[switchNode.loc.start.line] = caseIndent; + return caseIndent; + } + + /** + * Checks whether a return statement is wrapped in () + * @param {ASTNode} node node to examine + * @returns {boolean} the result + */ + function isWrappedInParenthesis(node) { + const regex = /^return\s*\(\s*\)/u; + + const statementWithoutArgument = sourceCode + .getText(node) + .replace(sourceCode.getText(node.argument), ""); + + return regex.test(statementWithoutArgument); + } + + return { + Program(node) { + if (node.body.length > 0) { + // Root nodes should have no indent + checkNodesIndent(node.body, getNodeIndent(node).goodChar); + } + }, + + ClassBody: blockIndentationCheck, + + BlockStatement: blockIndentationCheck, + + WhileStatement: blockLessNodes, + + ForStatement: blockLessNodes, + + ForInStatement: blockLessNodes, + + ForOfStatement: blockLessNodes, + + DoWhileStatement: blockLessNodes, + + IfStatement(node) { + if ( + node.consequent.type !== "BlockStatement" && + node.consequent.loc.start.line > node.loc.start.line + ) { + blockIndentationCheck(node); + } + }, + + VariableDeclaration(node) { + if ( + node.declarations.at(-1).loc.start.line > + node.declarations[0].loc.start.line + ) { + checkIndentInVariableDeclarations(node); + } + }, + + ObjectExpression(node) { + checkIndentInArrayOrObjectBlock(node); + }, + + ArrayExpression(node) { + checkIndentInArrayOrObjectBlock(node); + }, + + MemberExpression(node) { + if (typeof options.MemberExpression === "undefined") { + return; + } + + if (isSingleLineNode(node)) { + return; + } + + /* + * The typical layout of variable declarations and assignments + * alter the expectation of correct indentation. Skip them. + * TODO: Add appropriate configuration options for variable + * declarations and assignments. + */ + if ( + getParentNodeByType(node, "VariableDeclarator", [ + "FunctionExpression", + "ArrowFunctionExpression", + ]) + ) { + return; + } + + if ( + getParentNodeByType(node, "AssignmentExpression", [ + "FunctionExpression", + ]) + ) { + return; + } + + const propertyIndent = + getNodeIndent(node).goodChar + + indentSize * options.MemberExpression; + + const checkNodes = [node.property]; + + const dot = sourceCode.getTokenBefore(node.property); + + if (dot.type === "Punctuator" && dot.value === ".") { + checkNodes.push(dot); + } + + checkNodesIndent(checkNodes, propertyIndent); + }, + + SwitchStatement(node) { + // Switch is not a 'BlockStatement' + const switchIndent = getNodeIndent(node).goodChar; + const caseIndent = expectedCaseIndent(node, switchIndent); + + checkNodesIndent(node.cases, caseIndent); + + checkLastNodeLineIndent(node, switchIndent); + }, + + SwitchCase(node) { + // Skip inline cases + if (isSingleLineNode(node)) { + return; + } + const caseIndent = expectedCaseIndent(node); + + checkNodesIndent(node.consequent, caseIndent + indentSize); + }, + + FunctionDeclaration(node) { + if (isSingleLineNode(node)) { + return; + } + if ( + options.FunctionDeclaration.parameters === "first" && + node.params.length + ) { + checkNodesIndent( + node.params.slice(1), + node.params[0].loc.start.column, + ); + } else if (options.FunctionDeclaration.parameters !== null) { + checkNodesIndent( + node.params, + getNodeIndent(node).goodChar + + indentSize * options.FunctionDeclaration.parameters, + ); + } + }, + + FunctionExpression(node) { + if (isSingleLineNode(node)) { + return; + } + if ( + options.FunctionExpression.parameters === "first" && + node.params.length + ) { + checkNodesIndent( + node.params.slice(1), + node.params[0].loc.start.column, + ); + } else if (options.FunctionExpression.parameters !== null) { + checkNodesIndent( + node.params, + getNodeIndent(node).goodChar + + indentSize * options.FunctionExpression.parameters, + ); + } + }, + + ReturnStatement(node) { + if (isSingleLineNode(node)) { + return; + } + + const firstLineIndent = getNodeIndent(node).goodChar; + + // in case if return statement is wrapped in parenthesis + if (isWrappedInParenthesis(node)) { + checkLastReturnStatementLineIndent(node, firstLineIndent); + } else { + checkNodeIndent(node, firstLineIndent); + } + }, + + CallExpression(node) { + if (isSingleLineNode(node)) { + return; + } + if ( + options.CallExpression.arguments === "first" && + node.arguments.length + ) { + checkNodesIndent( + node.arguments.slice(1), + node.arguments[0].loc.start.column, + ); + } else if (options.CallExpression.arguments !== null) { + checkNodesIndent( + node.arguments, + getNodeIndent(node).goodChar + + indentSize * options.CallExpression.arguments, + ); + } + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/indent.js b/tools/ui/node_modules/eslint/lib/rules/indent.js new file mode 100644 index 0000000000000000000000000000000000000000..c6c18759a3b874ad023cc587b5058906ccb63ab4 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/indent.js @@ -0,0 +1,2334 @@ +/** + * @fileoverview This rule sets a specific indentation style and width for your code + * + * @author Teddy Katz + * @author Vitaly Puzrin + * @author Gyandeep Singh + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const KNOWN_NODES = new Set([ + "AssignmentExpression", + "AssignmentPattern", + "ArrayExpression", + "ArrayPattern", + "ArrowFunctionExpression", + "AwaitExpression", + "BlockStatement", + "BinaryExpression", + "BreakStatement", + "CallExpression", + "CatchClause", + "ChainExpression", + "ClassBody", + "ClassDeclaration", + "ClassExpression", + "ConditionalExpression", + "ContinueStatement", + "DoWhileStatement", + "DebuggerStatement", + "EmptyStatement", + "ExperimentalRestProperty", + "ExperimentalSpreadProperty", + "ExpressionStatement", + "ForStatement", + "ForInStatement", + "ForOfStatement", + "FunctionDeclaration", + "FunctionExpression", + "Identifier", + "IfStatement", + "Literal", + "LabeledStatement", + "LogicalExpression", + "MemberExpression", + "MetaProperty", + "MethodDefinition", + "NewExpression", + "ObjectExpression", + "ObjectPattern", + "PrivateIdentifier", + "Program", + "Property", + "PropertyDefinition", + "RestElement", + "ReturnStatement", + "SequenceExpression", + "SpreadElement", + "StaticBlock", + "Super", + "SwitchCase", + "SwitchStatement", + "TaggedTemplateExpression", + "TemplateElement", + "TemplateLiteral", + "ThisExpression", + "ThrowStatement", + "TryStatement", + "UnaryExpression", + "UpdateExpression", + "VariableDeclaration", + "VariableDeclarator", + "WhileStatement", + "WithStatement", + "YieldExpression", + "JSXFragment", + "JSXOpeningFragment", + "JSXClosingFragment", + "JSXIdentifier", + "JSXNamespacedName", + "JSXMemberExpression", + "JSXEmptyExpression", + "JSXExpressionContainer", + "JSXElement", + "JSXClosingElement", + "JSXOpeningElement", + "JSXAttribute", + "JSXSpreadAttribute", + "JSXText", + "ExportDefaultDeclaration", + "ExportNamedDeclaration", + "ExportAllDeclaration", + "ExportSpecifier", + "ImportDeclaration", + "ImportSpecifier", + "ImportDefaultSpecifier", + "ImportNamespaceSpecifier", + "ImportExpression", +]); + +/* + * General rule strategy: + * 1. An OffsetStorage instance stores a map of desired offsets, where each token has a specified offset from another + * specified token or to the first column. + * 2. As the AST is traversed, modify the desired offsets of tokens accordingly. For example, when entering a + * BlockStatement, offset all of the tokens in the BlockStatement by 1 indent level from the opening curly + * brace of the BlockStatement. + * 3. After traversing the AST, calculate the expected indentation levels of every token according to the + * OffsetStorage container. + * 4. For each line, compare the expected indentation of the first token to the actual indentation in the file, + * and report the token if the two values are not equal. + */ + +/** + * A mutable map that stores (key, value) pairs. The keys are numeric indices, and must be unique. + * This is intended to be a generic wrapper around a map with non-negative integer keys, so that the underlying implementation + * can easily be swapped out. + */ +class IndexMap { + /** + * Creates an empty map + * @param {number} maxKey The maximum key + */ + constructor(maxKey) { + // Initializing the array with the maximum expected size avoids dynamic reallocations that could degrade performance. + this._values = Array(maxKey + 1); + } + + /** + * Inserts an entry into the map. + * @param {number} key The entry's key + * @param {any} value The entry's value + * @returns {void} + */ + insert(key, value) { + this._values[key] = value; + } + + /** + * Finds the value of the entry with the largest key less than or equal to the provided key + * @param {number} key The provided key + * @returns {*|undefined} The value of the found entry, or undefined if no such entry exists. + */ + findLastNotAfter(key) { + const values = this._values; + + for (let index = key; index >= 0; index--) { + const value = values[index]; + + if (value) { + return value; + } + } + return void 0; + } + + /** + * Deletes all of the keys in the interval [start, end) + * @param {number} start The start of the range + * @param {number} end The end of the range + * @returns {void} + */ + deleteRange(start, end) { + this._values.fill(void 0, start, end); + } +} + +/** + * A helper class to get token-based info related to indentation + */ +class TokenInfo { + /** + * @param {SourceCode} sourceCode A SourceCode object + */ + constructor(sourceCode) { + this.sourceCode = sourceCode; + this.firstTokensByLineNumber = new Map(); + const tokens = sourceCode.tokensAndComments; + + for (let i = 0; i < tokens.length; i++) { + const token = tokens[i]; + + if (!this.firstTokensByLineNumber.has(token.loc.start.line)) { + this.firstTokensByLineNumber.set(token.loc.start.line, token); + } + if ( + !this.firstTokensByLineNumber.has(token.loc.end.line) && + sourceCode.text + .slice( + token.range[1] - token.loc.end.column, + token.range[1], + ) + .trim() + ) { + this.firstTokensByLineNumber.set(token.loc.end.line, token); + } + } + } + + /** + * Gets the first token on a given token's line + * @param {Token|ASTNode} token a node or token + * @returns {Token} The first token on the given line + */ + getFirstTokenOfLine(token) { + return this.firstTokensByLineNumber.get(token.loc.start.line); + } + + /** + * Determines whether a token is the first token in its line + * @param {Token} token The token + * @returns {boolean} `true` if the token is the first on its line + */ + isFirstTokenOfLine(token) { + return this.getFirstTokenOfLine(token) === token; + } + + /** + * Get the actual indent of a token + * @param {Token} token Token to examine. This should be the first token on its line. + * @returns {string} The indentation characters that precede the token + */ + getTokenIndent(token) { + return this.sourceCode.text.slice( + token.range[0] - token.loc.start.column, + token.range[0], + ); + } +} + +/** + * A class to store information on desired offsets of tokens from each other + */ +class OffsetStorage { + /** + * @param {TokenInfo} tokenInfo a TokenInfo instance + * @param {number} indentSize The desired size of each indentation level + * @param {string} indentType The indentation character + * @param {number} maxIndex The maximum end index of any token + */ + constructor(tokenInfo, indentSize, indentType, maxIndex) { + this._tokenInfo = tokenInfo; + this._indentSize = indentSize; + this._indentType = indentType; + + this._indexMap = new IndexMap(maxIndex); + this._indexMap.insert(0, { offset: 0, from: null, force: false }); + + this._lockedFirstTokens = new WeakMap(); + this._desiredIndentCache = new WeakMap(); + this._ignoredTokens = new WeakSet(); + } + + _getOffsetDescriptor(token) { + return this._indexMap.findLastNotAfter(token.range[0]); + } + + /** + * Sets the offset column of token B to match the offset column of token A. + * - **WARNING**: This matches a *column*, even if baseToken is not the first token on its line. In + * most cases, `setDesiredOffset` should be used instead. + * @param {Token} baseToken The first token + * @param {Token} offsetToken The second token, whose offset should be matched to the first token + * @returns {void} + */ + matchOffsetOf(baseToken, offsetToken) { + /* + * lockedFirstTokens is a map from a token whose indentation is controlled by the "first" option to + * the token that it depends on. For example, with the `ArrayExpression: first` option, the first + * token of each element in the array after the first will be mapped to the first token of the first + * element. The desired indentation of each of these tokens is computed based on the desired indentation + * of the "first" element, rather than through the normal offset mechanism. + */ + this._lockedFirstTokens.set(offsetToken, baseToken); + } + + /** + * Sets the desired offset of a token. + * + * This uses a line-based offset collapsing behavior to handle tokens on the same line. + * For example, consider the following two cases: + * + * ( + * [ + * bar + * ] + * ) + * + * ([ + * bar + * ]) + * + * Based on the first case, it's clear that the `bar` token needs to have an offset of 1 indent level (4 spaces) from + * the `[` token, and the `[` token has to have an offset of 1 indent level from the `(` token. Since the `(` token is + * the first on its line (with an indent of 0 spaces), the `bar` token needs to be offset by 2 indent levels (8 spaces) + * from the start of its line. + * + * However, in the second case `bar` should only be indented by 4 spaces. This is because the offset of 1 indent level + * between the `(` and the `[` tokens gets "collapsed" because the two tokens are on the same line. As a result, the + * `(` token is mapped to the `[` token with an offset of 0, and the rule correctly decides that `bar` should be indented + * by 1 indent level from the start of the line. + * + * This is useful because rule listeners can usually just call `setDesiredOffset` for all the tokens in the node, + * without needing to check which lines those tokens are on. + * + * Note that since collapsing only occurs when two tokens are on the same line, there are a few cases where non-intuitive + * behavior can occur. For example, consider the following cases: + * + * foo( + * ). + * bar( + * baz + * ) + * + * foo( + * ).bar( + * baz + * ) + * + * Based on the first example, it would seem that `bar` should be offset by 1 indent level from `foo`, and `baz` + * should be offset by 1 indent level from `bar`. However, this is not correct, because it would result in `baz` + * being indented by 2 indent levels in the second case (since `foo`, `bar`, and `baz` are all on separate lines, no + * collapsing would occur). + * + * Instead, the correct way would be to offset `baz` by 1 level from `bar`, offset `bar` by 1 level from the `)`, and + * offset the `)` by 0 levels from `foo`. This ensures that the offset between `bar` and the `)` are correctly collapsed + * in the second case. + * @param {Token} token The token + * @param {Token} fromToken The token that `token` should be offset from + * @param {number} offset The desired indent level + * @returns {void} + */ + setDesiredOffset(token, fromToken, offset) { + return this.setDesiredOffsets(token.range, fromToken, offset); + } + + /** + * Sets the desired offset of all tokens in a range + * It's common for node listeners in this file to need to apply the same offset to a large, contiguous range of tokens. + * Moreover, the offset of any given token is usually updated multiple times (roughly once for each node that contains + * it). This means that the offset of each token is updated O(AST depth) times. + * It would not be performant to store and update the offsets for each token independently, because the rule would end + * up having a time complexity of O(number of tokens * AST depth), which is quite slow for large files. + * + * Instead, the offset tree is represented as a collection of contiguous offset ranges in a file. For example, the following + * list could represent the state of the offset tree at a given point: + * + * - Tokens starting in the interval [0, 15) are aligned with the beginning of the file + * - Tokens starting in the interval [15, 30) are offset by 1 indent level from the `bar` token + * - Tokens starting in the interval [30, 43) are offset by 1 indent level from the `foo` token + * - Tokens starting in the interval [43, 820) are offset by 2 indent levels from the `bar` token + * - Tokens starting in the interval [820, ∞) are offset by 1 indent level from the `baz` token + * + * The `setDesiredOffsets` methods inserts ranges like the ones above. The third line above would be inserted by using: + * `setDesiredOffsets([30, 43], fooToken, 1);` + * @param {[number, number]} range A [start, end] pair. All tokens with range[0] <= token.start < range[1] will have the offset applied. + * @param {Token} fromToken The token that this is offset from + * @param {number} offset The desired indent level + * @param {boolean} force `true` if this offset should not use the normal collapsing behavior. This should almost always be false. + * @returns {void} + */ + setDesiredOffsets(range, fromToken, offset, force) { + /* + * Offset ranges are stored as a collection of nodes, where each node maps a numeric key to an offset + * descriptor. The tree for the example above would have the following nodes: + * + * * key: 0, value: { offset: 0, from: null } + * * key: 15, value: { offset: 1, from: barToken } + * * key: 30, value: { offset: 1, from: fooToken } + * * key: 43, value: { offset: 2, from: barToken } + * * key: 820, value: { offset: 1, from: bazToken } + * + * To find the offset descriptor for any given token, one needs to find the node with the largest key + * which is <= token.start. To make this operation fast, the nodes are stored in a map indexed by key. + */ + + const descriptorToInsert = { offset, from: fromToken, force }; + + const descriptorAfterRange = this._indexMap.findLastNotAfter(range[1]); + + const fromTokenIsInRange = + fromToken && + fromToken.range[0] >= range[0] && + fromToken.range[1] <= range[1]; + const fromTokenDescriptor = + fromTokenIsInRange && this._getOffsetDescriptor(fromToken); + + // First, remove any existing nodes in the range from the map. + this._indexMap.deleteRange(range[0] + 1, range[1]); + + // Insert a new node into the map for this range + this._indexMap.insert(range[0], descriptorToInsert); + + /* + * To avoid circular offset dependencies, keep the `fromToken` token mapped to whatever it was mapped to previously, + * even if it's in the current range. + */ + if (fromTokenIsInRange) { + this._indexMap.insert(fromToken.range[0], fromTokenDescriptor); + this._indexMap.insert(fromToken.range[1], descriptorToInsert); + } + + /* + * To avoid modifying the offset of tokens after the range, insert another node to keep the offset of the following + * tokens the same as it was before. + */ + this._indexMap.insert(range[1], descriptorAfterRange); + } + + /** + * Gets the desired indent of a token + * @param {Token} token The token + * @returns {string} The desired indent of the token + */ + getDesiredIndent(token) { + if (!this._desiredIndentCache.has(token)) { + if (this._ignoredTokens.has(token)) { + /* + * If the token is ignored, use the actual indent of the token as the desired indent. + * This ensures that no errors are reported for this token. + */ + this._desiredIndentCache.set( + token, + this._tokenInfo.getTokenIndent(token), + ); + } else if (this._lockedFirstTokens.has(token)) { + const firstToken = this._lockedFirstTokens.get(token); + + this._desiredIndentCache.set( + token, + + // (indentation for the first element's line) + this.getDesiredIndent( + this._tokenInfo.getFirstTokenOfLine(firstToken), + ) + + // (space between the start of the first element's line and the first element) + this._indentType.repeat( + firstToken.loc.start.column - + this._tokenInfo.getFirstTokenOfLine(firstToken) + .loc.start.column, + ), + ); + } else { + const offsetInfo = this._getOffsetDescriptor(token); + const offset = + offsetInfo.from && + offsetInfo.from.loc.start.line === token.loc.start.line && + !/^\s*?\n/u.test(token.value) && + !offsetInfo.force + ? 0 + : offsetInfo.offset * this._indentSize; + + this._desiredIndentCache.set( + token, + (offsetInfo.from + ? this.getDesiredIndent(offsetInfo.from) + : "") + this._indentType.repeat(offset), + ); + } + } + return this._desiredIndentCache.get(token); + } + + /** + * Ignores a token, preventing it from being reported. + * @param {Token} token The token + * @returns {void} + */ + ignoreToken(token) { + if (this._tokenInfo.isFirstTokenOfLine(token)) { + this._ignoredTokens.add(token); + } + } + + /** + * Gets the first token that the given token's indentation is dependent on + * @param {Token} token The token + * @returns {Token} The token that the given token depends on, or `null` if the given token is at the top level + */ + getFirstDependency(token) { + return this._getOffsetDescriptor(token).from; + } +} + +const ELEMENT_LIST_SCHEMA = { + oneOf: [ + { + type: "integer", + minimum: 0, + }, + { + enum: ["first", "off"], + }, + ], +}; + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "indent", + url: "https://eslint.style/rules/indent", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce consistent indentation", + recommended: false, + url: "https://eslint.org/docs/latest/rules/indent", + }, + + fixable: "whitespace", + + schema: [ + { + oneOf: [ + { + enum: ["tab"], + }, + { + type: "integer", + minimum: 0, + }, + ], + }, + { + type: "object", + properties: { + SwitchCase: { + type: "integer", + minimum: 0, + default: 0, + }, + VariableDeclarator: { + oneOf: [ + ELEMENT_LIST_SCHEMA, + { + type: "object", + properties: { + var: ELEMENT_LIST_SCHEMA, + let: ELEMENT_LIST_SCHEMA, + const: ELEMENT_LIST_SCHEMA, + }, + additionalProperties: false, + }, + ], + }, + outerIIFEBody: { + oneOf: [ + { + type: "integer", + minimum: 0, + }, + { + enum: ["off"], + }, + ], + }, + MemberExpression: { + oneOf: [ + { + type: "integer", + minimum: 0, + }, + { + enum: ["off"], + }, + ], + }, + FunctionDeclaration: { + type: "object", + properties: { + parameters: ELEMENT_LIST_SCHEMA, + body: { + type: "integer", + minimum: 0, + }, + }, + additionalProperties: false, + }, + FunctionExpression: { + type: "object", + properties: { + parameters: ELEMENT_LIST_SCHEMA, + body: { + type: "integer", + minimum: 0, + }, + }, + additionalProperties: false, + }, + StaticBlock: { + type: "object", + properties: { + body: { + type: "integer", + minimum: 0, + }, + }, + additionalProperties: false, + }, + CallExpression: { + type: "object", + properties: { + arguments: ELEMENT_LIST_SCHEMA, + }, + additionalProperties: false, + }, + ArrayExpression: ELEMENT_LIST_SCHEMA, + ObjectExpression: ELEMENT_LIST_SCHEMA, + ImportDeclaration: ELEMENT_LIST_SCHEMA, + flatTernaryExpressions: { + type: "boolean", + default: false, + }, + offsetTernaryExpressions: { + type: "boolean", + default: false, + }, + ignoredNodes: { + type: "array", + items: { + type: "string", + not: { + pattern: ":exit$", + }, + }, + }, + ignoreComments: { + type: "boolean", + default: false, + }, + }, + additionalProperties: false, + }, + ], + messages: { + wrongIndentation: + "Expected indentation of {{expected}} but found {{actual}}.", + }, + }, + + create(context) { + const DEFAULT_VARIABLE_INDENT = 1; + const DEFAULT_PARAMETER_INDENT = 1; + const DEFAULT_FUNCTION_BODY_INDENT = 1; + + let indentType = "space"; + let indentSize = 4; + const options = { + SwitchCase: 0, + VariableDeclarator: { + var: DEFAULT_VARIABLE_INDENT, + let: DEFAULT_VARIABLE_INDENT, + const: DEFAULT_VARIABLE_INDENT, + }, + outerIIFEBody: 1, + FunctionDeclaration: { + parameters: DEFAULT_PARAMETER_INDENT, + body: DEFAULT_FUNCTION_BODY_INDENT, + }, + FunctionExpression: { + parameters: DEFAULT_PARAMETER_INDENT, + body: DEFAULT_FUNCTION_BODY_INDENT, + }, + StaticBlock: { + body: DEFAULT_FUNCTION_BODY_INDENT, + }, + CallExpression: { + arguments: DEFAULT_PARAMETER_INDENT, + }, + MemberExpression: 1, + ArrayExpression: 1, + ObjectExpression: 1, + ImportDeclaration: 1, + flatTernaryExpressions: false, + ignoredNodes: [], + ignoreComments: false, + }; + + if (context.options.length) { + if (context.options[0] === "tab") { + indentSize = 1; + indentType = "tab"; + } else { + indentSize = context.options[0]; + indentType = "space"; + } + + if (context.options[1]) { + Object.assign(options, context.options[1]); + + if ( + typeof options.VariableDeclarator === "number" || + options.VariableDeclarator === "first" + ) { + options.VariableDeclarator = { + var: options.VariableDeclarator, + let: options.VariableDeclarator, + const: options.VariableDeclarator, + }; + } + } + } + + const sourceCode = context.sourceCode; + const tokenInfo = new TokenInfo(sourceCode); + const offsets = new OffsetStorage( + tokenInfo, + indentSize, + indentType === "space" ? " " : "\t", + sourceCode.text.length, + ); + const parameterParens = new WeakSet(); + + /** + * Creates an error message for a line, given the expected/actual indentation. + * @param {number} expectedAmount The expected amount of indentation characters for this line + * @param {number} actualSpaces The actual number of indentation spaces that were found on this line + * @param {number} actualTabs The actual number of indentation tabs that were found on this line + * @returns {string} An error message for this line + */ + function createErrorMessageData( + expectedAmount, + actualSpaces, + actualTabs, + ) { + const expectedStatement = `${expectedAmount} ${indentType}${expectedAmount === 1 ? "" : "s"}`; // e.g. "2 tabs" + const foundSpacesWord = `space${actualSpaces === 1 ? "" : "s"}`; // e.g. "space" + const foundTabsWord = `tab${actualTabs === 1 ? "" : "s"}`; // e.g. "tabs" + let foundStatement; + + if (actualSpaces > 0) { + /* + * Abbreviate the message if the expected indentation is also spaces. + * e.g. 'Expected 4 spaces but found 2' rather than 'Expected 4 spaces but found 2 spaces' + */ + foundStatement = + indentType === "space" + ? actualSpaces + : `${actualSpaces} ${foundSpacesWord}`; + } else if (actualTabs > 0) { + foundStatement = + indentType === "tab" + ? actualTabs + : `${actualTabs} ${foundTabsWord}`; + } else { + foundStatement = "0"; + } + return { + expected: expectedStatement, + actual: foundStatement, + }; + } + + /** + * Reports a given indent violation + * @param {Token} token Token violating the indent rule + * @param {string} neededIndent Expected indentation string + * @returns {void} + */ + function report(token, neededIndent) { + const actualIndent = Array.from(tokenInfo.getTokenIndent(token)); + const numSpaces = actualIndent.filter(char => char === " ").length; + const numTabs = actualIndent.filter(char => char === "\t").length; + + context.report({ + node: token, + messageId: "wrongIndentation", + data: createErrorMessageData( + neededIndent.length, + numSpaces, + numTabs, + ), + loc: { + start: { line: token.loc.start.line, column: 0 }, + end: { + line: token.loc.start.line, + column: token.loc.start.column, + }, + }, + fix(fixer) { + const range = [ + token.range[0] - token.loc.start.column, + token.range[0], + ]; + const newText = neededIndent; + + return fixer.replaceTextRange(range, newText); + }, + }); + } + + /** + * Checks if a token's indentation is correct + * @param {Token} token Token to examine + * @param {string} desiredIndent Desired indentation of the string + * @returns {boolean} `true` if the token's indentation is correct + */ + function validateTokenIndent(token, desiredIndent) { + const indentation = tokenInfo.getTokenIndent(token); + + return ( + indentation === desiredIndent || + // To avoid conflicts with no-mixed-spaces-and-tabs, don't report mixed spaces and tabs. + (indentation.includes(" ") && indentation.includes("\t")) + ); + } + + /** + * Check to see if the node is a file level IIFE + * @param {ASTNode} node The function node to check. + * @returns {boolean} True if the node is the outer IIFE + */ + function isOuterIIFE(node) { + /* + * Verify that the node is an IIFE + */ + if ( + !node.parent || + node.parent.type !== "CallExpression" || + node.parent.callee !== node + ) { + return false; + } + + /* + * Navigate legal ancestors to determine whether this IIFE is outer. + * A "legal ancestor" is an expression or statement that causes the function to get executed immediately. + * For example, `!(function(){})()` is an outer IIFE even though it is preceded by a ! operator. + */ + let statement = node.parent && node.parent.parent; + + while ( + (statement.type === "UnaryExpression" && + ["!", "~", "+", "-"].includes(statement.operator)) || + statement.type === "AssignmentExpression" || + statement.type === "LogicalExpression" || + statement.type === "SequenceExpression" || + statement.type === "VariableDeclarator" + ) { + statement = statement.parent; + } + + return ( + (statement.type === "ExpressionStatement" || + statement.type === "VariableDeclaration") && + statement.parent.type === "Program" + ); + } + + /** + * Counts the number of linebreaks that follow the last non-whitespace character in a string + * @param {string} string The string to check + * @returns {number} The number of JavaScript linebreaks that follow the last non-whitespace character, + * or the total number of linebreaks if the string is all whitespace. + */ + function countTrailingLinebreaks(string) { + const trailingWhitespace = string.match(/\s*$/u)[0]; + const linebreakMatches = trailingWhitespace.match( + astUtils.createGlobalLinebreakMatcher(), + ); + + return linebreakMatches === null ? 0 : linebreakMatches.length; + } + + /** + * Check indentation for lists of elements (arrays, objects, function params) + * @param {ASTNode[]} elements List of elements that should be offset + * @param {Token} startToken The start token of the list that element should be aligned against, e.g. '[' + * @param {Token} endToken The end token of the list, e.g. ']' + * @param {number|string} offset The amount that the elements should be offset + * @returns {void} + */ + function addElementListIndent(elements, startToken, endToken, offset) { + /** + * Gets the first token of a given element, including surrounding parentheses. + * @param {ASTNode} element A node in the `elements` list + * @returns {Token} The first token of this element + */ + function getFirstToken(element) { + let token = sourceCode.getTokenBefore(element); + + while ( + astUtils.isOpeningParenToken(token) && + token !== startToken + ) { + token = sourceCode.getTokenBefore(token); + } + return sourceCode.getTokenAfter(token); + } + + // Run through all the tokens in the list, and offset them by one indent level (mainly for comments, other things will end up overridden) + offsets.setDesiredOffsets( + [startToken.range[1], endToken.range[0]], + startToken, + typeof offset === "number" ? offset : 1, + ); + offsets.setDesiredOffset(endToken, startToken, 0); + + // If the preference is "first" but there is no first element (e.g. sparse arrays w/ empty first slot), fall back to 1 level. + if (offset === "first" && elements.length && !elements[0]) { + return; + } + elements.forEach((element, index) => { + if (!element) { + // Skip holes in arrays + return; + } + if (offset === "off") { + // Ignore the first token of every element if the "off" option is used + offsets.ignoreToken(getFirstToken(element)); + } + + // Offset the following elements correctly relative to the first element + if (index === 0) { + return; + } + if ( + offset === "first" && + tokenInfo.isFirstTokenOfLine(getFirstToken(element)) + ) { + offsets.matchOffsetOf( + getFirstToken(elements[0]), + getFirstToken(element), + ); + } else { + const previousElement = elements[index - 1]; + const firstTokenOfPreviousElement = + previousElement && getFirstToken(previousElement); + const previousElementLastToken = + previousElement && + sourceCode.getLastToken(previousElement); + + if ( + previousElement && + previousElementLastToken.loc.end.line - + countTrailingLinebreaks( + previousElementLastToken.value, + ) > + startToken.loc.end.line + ) { + offsets.setDesiredOffsets( + [previousElement.range[1], element.range[1]], + firstTokenOfPreviousElement, + 0, + ); + } + } + }); + } + + /** + * Check and decide whether to check for indentation for blockless nodes + * Scenarios are for or while statements without braces around them + * @param {ASTNode} node node to examine + * @returns {void} + */ + function addBlocklessNodeIndent(node) { + if (node.type !== "BlockStatement") { + const lastParentToken = sourceCode.getTokenBefore( + node, + astUtils.isNotOpeningParenToken, + ); + + let firstBodyToken = sourceCode.getFirstToken(node); + let lastBodyToken = sourceCode.getLastToken(node); + + while ( + astUtils.isOpeningParenToken( + sourceCode.getTokenBefore(firstBodyToken), + ) && + astUtils.isClosingParenToken( + sourceCode.getTokenAfter(lastBodyToken), + ) + ) { + firstBodyToken = sourceCode.getTokenBefore(firstBodyToken); + lastBodyToken = sourceCode.getTokenAfter(lastBodyToken); + } + + offsets.setDesiredOffsets( + [firstBodyToken.range[0], lastBodyToken.range[1]], + lastParentToken, + 1, + ); + } + } + + /** + * Checks the indentation for nodes that are like function calls (`CallExpression` and `NewExpression`) + * @param {ASTNode} node A CallExpression or NewExpression node + * @returns {void} + */ + function addFunctionCallIndent(node) { + let openingParen; + + if (node.arguments.length) { + openingParen = sourceCode.getFirstTokenBetween( + node.callee, + node.arguments[0], + astUtils.isOpeningParenToken, + ); + } else { + openingParen = sourceCode.getLastToken(node, 1); + } + const closingParen = sourceCode.getLastToken(node); + + parameterParens.add(openingParen); + parameterParens.add(closingParen); + + /* + * If `?.` token exists, set desired offset for that. + * This logic is copied from `MemberExpression`'s. + */ + if (node.optional) { + const dotToken = sourceCode.getTokenAfter( + node.callee, + astUtils.isQuestionDotToken, + ); + const calleeParenCount = sourceCode.getTokensBetween( + node.callee, + dotToken, + { filter: astUtils.isClosingParenToken }, + ).length; + const firstTokenOfCallee = calleeParenCount + ? sourceCode.getTokenBefore(node.callee, { + skip: calleeParenCount - 1, + }) + : sourceCode.getFirstToken(node.callee); + const lastTokenOfCallee = sourceCode.getTokenBefore(dotToken); + const offsetBase = + lastTokenOfCallee.loc.end.line === + openingParen.loc.start.line + ? lastTokenOfCallee + : firstTokenOfCallee; + + offsets.setDesiredOffset(dotToken, offsetBase, 1); + } + + const offsetAfterToken = + node.callee.type === "TaggedTemplateExpression" + ? sourceCode.getFirstToken(node.callee.quasi) + : openingParen; + const offsetToken = sourceCode.getTokenBefore(offsetAfterToken); + + offsets.setDesiredOffset(openingParen, offsetToken, 0); + + addElementListIndent( + node.arguments, + openingParen, + closingParen, + options.CallExpression.arguments, + ); + } + + /** + * Checks the indentation of parenthesized values, given a list of tokens in a program + * @param {Token[]} tokens A list of tokens + * @returns {void} + */ + function addParensIndent(tokens) { + const parenStack = []; + const parenPairs = []; + + for (let i = 0; i < tokens.length; i++) { + const nextToken = tokens[i]; + + if (astUtils.isOpeningParenToken(nextToken)) { + parenStack.push(nextToken); + } else if (astUtils.isClosingParenToken(nextToken)) { + parenPairs.push({ + left: parenStack.pop(), + right: nextToken, + }); + } + } + + for (let i = parenPairs.length - 1; i >= 0; i--) { + const leftParen = parenPairs[i].left; + const rightParen = parenPairs[i].right; + + // We only want to handle parens around expressions, so exclude parentheses that are in function parameters and function call arguments. + if ( + !parameterParens.has(leftParen) && + !parameterParens.has(rightParen) + ) { + const parenthesizedTokens = new Set( + sourceCode.getTokensBetween(leftParen, rightParen), + ); + + parenthesizedTokens.forEach(token => { + if ( + !parenthesizedTokens.has( + offsets.getFirstDependency(token), + ) + ) { + offsets.setDesiredOffset(token, leftParen, 1); + } + }); + } + + offsets.setDesiredOffset(rightParen, leftParen, 0); + } + } + + /** + * Ignore all tokens within an unknown node whose offset do not depend + * on another token's offset within the unknown node + * @param {ASTNode} node Unknown Node + * @returns {void} + */ + function ignoreNode(node) { + const unknownNodeTokens = new Set( + sourceCode.getTokens(node, { includeComments: true }), + ); + + unknownNodeTokens.forEach(token => { + if (!unknownNodeTokens.has(offsets.getFirstDependency(token))) { + const firstTokenOfLine = + tokenInfo.getFirstTokenOfLine(token); + + if (token === firstTokenOfLine) { + offsets.ignoreToken(token); + } else { + offsets.setDesiredOffset(token, firstTokenOfLine, 0); + } + } + }); + } + + /** + * Check whether the given token is on the first line of a statement. + * @param {Token} token The token to check. + * @param {ASTNode} leafNode The expression node that the token belongs directly. + * @returns {boolean} `true` if the token is on the first line of a statement. + */ + function isOnFirstLineOfStatement(token, leafNode) { + let node = leafNode; + + while ( + node.parent && + !node.parent.type.endsWith("Statement") && + !node.parent.type.endsWith("Declaration") + ) { + node = node.parent; + } + node = node.parent; + + return !node || node.loc.start.line === token.loc.start.line; + } + + /** + * Check whether there are any blank (whitespace-only) lines between + * two tokens on separate lines. + * @param {Token} firstToken The first token. + * @param {Token} secondToken The second token. + * @returns {boolean} `true` if the tokens are on separate lines and + * there exists a blank line between them, `false` otherwise. + */ + function hasBlankLinesBetween(firstToken, secondToken) { + const firstTokenLine = firstToken.loc.end.line; + const secondTokenLine = secondToken.loc.start.line; + + if ( + firstTokenLine === secondTokenLine || + firstTokenLine === secondTokenLine - 1 + ) { + return false; + } + + for ( + let line = firstTokenLine + 1; + line < secondTokenLine; + ++line + ) { + if (!tokenInfo.firstTokensByLineNumber.has(line)) { + return true; + } + } + + return false; + } + + const ignoredNodeFirstTokens = new Set(); + + const baseOffsetListeners = { + "ArrayExpression, ArrayPattern"(node) { + const openingBracket = sourceCode.getFirstToken(node); + const closingBracket = sourceCode.getTokenAfter( + [...node.elements].reverse().find(_ => _) || openingBracket, + astUtils.isClosingBracketToken, + ); + + addElementListIndent( + node.elements, + openingBracket, + closingBracket, + options.ArrayExpression, + ); + }, + + "ObjectExpression, ObjectPattern"(node) { + const openingCurly = sourceCode.getFirstToken(node); + const closingCurly = sourceCode.getTokenAfter( + node.properties.length + ? node.properties.at(-1) + : openingCurly, + astUtils.isClosingBraceToken, + ); + + addElementListIndent( + node.properties, + openingCurly, + closingCurly, + options.ObjectExpression, + ); + }, + + ArrowFunctionExpression(node) { + const maybeOpeningParen = sourceCode.getFirstToken(node, { + skip: node.async ? 1 : 0, + }); + + if (astUtils.isOpeningParenToken(maybeOpeningParen)) { + const openingParen = maybeOpeningParen; + const closingParen = sourceCode.getTokenBefore( + node.body, + astUtils.isClosingParenToken, + ); + + parameterParens.add(openingParen); + parameterParens.add(closingParen); + addElementListIndent( + node.params, + openingParen, + closingParen, + options.FunctionExpression.parameters, + ); + } + + addBlocklessNodeIndent(node.body); + }, + + AssignmentExpression(node) { + const operator = sourceCode.getFirstTokenBetween( + node.left, + node.right, + token => token.value === node.operator, + ); + + offsets.setDesiredOffsets( + [operator.range[0], node.range[1]], + sourceCode.getLastToken(node.left), + 1, + ); + offsets.ignoreToken(operator); + offsets.ignoreToken(sourceCode.getTokenAfter(operator)); + }, + + "BinaryExpression, LogicalExpression"(node) { + const operator = sourceCode.getFirstTokenBetween( + node.left, + node.right, + token => token.value === node.operator, + ); + + /* + * For backwards compatibility, don't check BinaryExpression indents, e.g. + * var foo = bar && + * baz; + */ + + const tokenAfterOperator = sourceCode.getTokenAfter(operator); + + offsets.ignoreToken(operator); + offsets.ignoreToken(tokenAfterOperator); + offsets.setDesiredOffset(tokenAfterOperator, operator, 0); + }, + + "BlockStatement, ClassBody"(node) { + let blockIndentLevel; + + if (node.parent && isOuterIIFE(node.parent)) { + blockIndentLevel = options.outerIIFEBody; + } else if ( + node.parent && + (node.parent.type === "FunctionExpression" || + node.parent.type === "ArrowFunctionExpression") + ) { + blockIndentLevel = options.FunctionExpression.body; + } else if ( + node.parent && + node.parent.type === "FunctionDeclaration" + ) { + blockIndentLevel = options.FunctionDeclaration.body; + } else { + blockIndentLevel = 1; + } + + /* + * For blocks that aren't lone statements, ensure that the opening curly brace + * is aligned with the parent. + */ + if (!astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type)) { + offsets.setDesiredOffset( + sourceCode.getFirstToken(node), + sourceCode.getFirstToken(node.parent), + 0, + ); + } + + addElementListIndent( + node.body, + sourceCode.getFirstToken(node), + sourceCode.getLastToken(node), + blockIndentLevel, + ); + }, + + CallExpression: addFunctionCallIndent, + + "ClassDeclaration[superClass], ClassExpression[superClass]"(node) { + const classToken = sourceCode.getFirstToken(node); + const extendsToken = sourceCode.getTokenBefore( + node.superClass, + astUtils.isNotOpeningParenToken, + ); + + offsets.setDesiredOffsets( + [extendsToken.range[0], node.body.range[0]], + classToken, + 1, + ); + }, + + ConditionalExpression(node) { + const firstToken = sourceCode.getFirstToken(node); + + // `flatTernaryExpressions` option is for the following style: + // var a = + // foo > 0 ? bar : + // foo < 0 ? baz : + // /*else*/ qiz ; + if ( + !options.flatTernaryExpressions || + !astUtils.isTokenOnSameLine(node.test, node.consequent) || + isOnFirstLineOfStatement(firstToken, node) + ) { + const questionMarkToken = sourceCode.getFirstTokenBetween( + node.test, + node.consequent, + token => + token.type === "Punctuator" && token.value === "?", + ); + const colonToken = sourceCode.getFirstTokenBetween( + node.consequent, + node.alternate, + token => + token.type === "Punctuator" && token.value === ":", + ); + + const firstConsequentToken = + sourceCode.getTokenAfter(questionMarkToken); + const lastConsequentToken = + sourceCode.getTokenBefore(colonToken); + const firstAlternateToken = + sourceCode.getTokenAfter(colonToken); + + offsets.setDesiredOffset(questionMarkToken, firstToken, 1); + offsets.setDesiredOffset(colonToken, firstToken, 1); + + offsets.setDesiredOffset( + firstConsequentToken, + firstToken, + firstConsequentToken.type === "Punctuator" && + options.offsetTernaryExpressions + ? 2 + : 1, + ); + + /* + * The alternate and the consequent should usually have the same indentation. + * If they share part of a line, align the alternate against the first token of the consequent. + * This allows the alternate to be indented correctly in cases like this: + * foo ? ( + * bar + * ) : ( // this '(' is aligned with the '(' above, so it's considered to be aligned with `foo` + * baz // as a result, `baz` is offset by 1 rather than 2 + * ) + */ + if ( + lastConsequentToken.loc.end.line === + firstAlternateToken.loc.start.line + ) { + offsets.setDesiredOffset( + firstAlternateToken, + firstConsequentToken, + 0, + ); + } else { + /** + * If the alternate and consequent do not share part of a line, offset the alternate from the first + * token of the conditional expression. For example: + * foo ? bar + * : baz + * + * If `baz` were aligned with `bar` rather than being offset by 1 from `foo`, `baz` would end up + * having no expected indentation. + */ + offsets.setDesiredOffset( + firstAlternateToken, + firstToken, + firstAlternateToken.type === "Punctuator" && + options.offsetTernaryExpressions + ? 2 + : 1, + ); + } + } + }, + + "DoWhileStatement, WhileStatement, ForInStatement, ForOfStatement, WithStatement": + node => addBlocklessNodeIndent(node.body), + + ExportNamedDeclaration(node) { + if (node.declaration === null) { + const closingCurly = sourceCode.getLastToken( + node, + astUtils.isClosingBraceToken, + ); + + // Indent the specifiers in `export {foo, bar, baz}` + addElementListIndent( + node.specifiers, + sourceCode.getFirstToken(node, { skip: 1 }), + closingCurly, + 1, + ); + + if (node.source) { + // Indent everything after and including the `from` token in `export {foo, bar, baz} from 'qux'` + offsets.setDesiredOffsets( + [closingCurly.range[1], node.range[1]], + sourceCode.getFirstToken(node), + 1, + ); + } + } + }, + + ForStatement(node) { + const forOpeningParen = sourceCode.getFirstToken(node, 1); + + if (node.init) { + offsets.setDesiredOffsets( + node.init.range, + forOpeningParen, + 1, + ); + } + if (node.test) { + offsets.setDesiredOffsets( + node.test.range, + forOpeningParen, + 1, + ); + } + if (node.update) { + offsets.setDesiredOffsets( + node.update.range, + forOpeningParen, + 1, + ); + } + addBlocklessNodeIndent(node.body); + }, + + "FunctionDeclaration, FunctionExpression"(node) { + const closingParen = sourceCode.getTokenBefore(node.body); + const openingParen = sourceCode.getTokenBefore( + node.params.length ? node.params[0] : closingParen, + ); + + parameterParens.add(openingParen); + parameterParens.add(closingParen); + addElementListIndent( + node.params, + openingParen, + closingParen, + options[node.type].parameters, + ); + }, + + IfStatement(node) { + addBlocklessNodeIndent(node.consequent); + if (node.alternate) { + addBlocklessNodeIndent(node.alternate); + } + }, + + /* + * For blockless nodes with semicolon-first style, don't indent the semicolon. + * e.g. + * if (foo) + * bar() + * ; [1, 2, 3].map(foo) + * + * Traversal into the node sets indentation of the semicolon, so we need to override it on exit. + */ + ":matches(DoWhileStatement, ForStatement, ForInStatement, ForOfStatement, IfStatement, WhileStatement, WithStatement):exit"( + node, + ) { + let nodesToCheck; + + if (node.type === "IfStatement") { + nodesToCheck = [node.consequent]; + if (node.alternate) { + nodesToCheck.push(node.alternate); + } + } else { + nodesToCheck = [node.body]; + } + + for (const nodeToCheck of nodesToCheck) { + const lastToken = sourceCode.getLastToken(nodeToCheck); + + if (astUtils.isSemicolonToken(lastToken)) { + const tokenBeforeLast = + sourceCode.getTokenBefore(lastToken); + const tokenAfterLast = + sourceCode.getTokenAfter(lastToken); + + // override indentation of `;` only if its line looks like a semicolon-first style line + if ( + !astUtils.isTokenOnSameLine( + tokenBeforeLast, + lastToken, + ) && + tokenAfterLast && + astUtils.isTokenOnSameLine( + lastToken, + tokenAfterLast, + ) + ) { + offsets.setDesiredOffset( + lastToken, + sourceCode.getFirstToken(node), + 0, + ); + } + } + } + }, + + ImportDeclaration(node) { + if ( + node.specifiers.some( + specifier => specifier.type === "ImportSpecifier", + ) + ) { + const openingCurly = sourceCode.getFirstToken( + node, + astUtils.isOpeningBraceToken, + ); + const closingCurly = sourceCode.getLastToken( + node, + astUtils.isClosingBraceToken, + ); + + addElementListIndent( + node.specifiers.filter( + specifier => specifier.type === "ImportSpecifier", + ), + openingCurly, + closingCurly, + options.ImportDeclaration, + ); + } + + const fromToken = sourceCode.getLastToken( + node, + token => + token.type === "Identifier" && token.value === "from", + ); + const sourceToken = sourceCode.getLastToken( + node, + token => token.type === "String", + ); + const semiToken = sourceCode.getLastToken( + node, + token => token.type === "Punctuator" && token.value === ";", + ); + + if (fromToken) { + const end = + semiToken && semiToken.range[1] === sourceToken.range[1] + ? node.range[1] + : sourceToken.range[1]; + + offsets.setDesiredOffsets( + [fromToken.range[0], end], + sourceCode.getFirstToken(node), + 1, + ); + } + }, + + ImportExpression(node) { + const openingParen = sourceCode.getFirstToken(node, 1); + const closingParen = sourceCode.getLastToken(node); + + parameterParens.add(openingParen); + parameterParens.add(closingParen); + offsets.setDesiredOffset( + openingParen, + sourceCode.getTokenBefore(openingParen), + 0, + ); + + addElementListIndent( + [node.source], + openingParen, + closingParen, + options.CallExpression.arguments, + ); + }, + + "MemberExpression, JSXMemberExpression, MetaProperty"(node) { + const object = + node.type === "MetaProperty" ? node.meta : node.object; + const firstNonObjectToken = sourceCode.getFirstTokenBetween( + object, + node.property, + astUtils.isNotClosingParenToken, + ); + const secondNonObjectToken = + sourceCode.getTokenAfter(firstNonObjectToken); + + const objectParenCount = sourceCode.getTokensBetween( + object, + node.property, + { filter: astUtils.isClosingParenToken }, + ).length; + const firstObjectToken = objectParenCount + ? sourceCode.getTokenBefore(object, { + skip: objectParenCount - 1, + }) + : sourceCode.getFirstToken(object); + const lastObjectToken = + sourceCode.getTokenBefore(firstNonObjectToken); + const firstPropertyToken = node.computed + ? firstNonObjectToken + : secondNonObjectToken; + + if (node.computed) { + // For computed MemberExpressions, match the closing bracket with the opening bracket. + offsets.setDesiredOffset( + sourceCode.getLastToken(node), + firstNonObjectToken, + 0, + ); + offsets.setDesiredOffsets( + node.property.range, + firstNonObjectToken, + 1, + ); + } + + /* + * If the object ends on the same line that the property starts, match against the last token + * of the object, to ensure that the MemberExpression is not indented. + * + * Otherwise, match against the first token of the object, e.g. + * foo + * .bar + * .baz // <-- offset by 1 from `foo` + */ + const offsetBase = + lastObjectToken.loc.end.line === + firstPropertyToken.loc.start.line + ? lastObjectToken + : firstObjectToken; + + if (typeof options.MemberExpression === "number") { + // Match the dot (for non-computed properties) or the opening bracket (for computed properties) against the object. + offsets.setDesiredOffset( + firstNonObjectToken, + offsetBase, + options.MemberExpression, + ); + + /* + * For computed MemberExpressions, match the first token of the property against the opening bracket. + * Otherwise, match the first token of the property against the object. + */ + offsets.setDesiredOffset( + secondNonObjectToken, + node.computed ? firstNonObjectToken : offsetBase, + options.MemberExpression, + ); + } else { + // If the MemberExpression option is off, ignore the dot and the first token of the property. + offsets.ignoreToken(firstNonObjectToken); + offsets.ignoreToken(secondNonObjectToken); + + // To ignore the property indentation, ensure that the property tokens depend on the ignored tokens. + offsets.setDesiredOffset( + firstNonObjectToken, + offsetBase, + 0, + ); + offsets.setDesiredOffset( + secondNonObjectToken, + firstNonObjectToken, + 0, + ); + } + }, + + NewExpression(node) { + // Only indent the arguments if the NewExpression has parens (e.g. `new Foo(bar)` or `new Foo()`, but not `new Foo` + if ( + node.arguments.length > 0 || + (astUtils.isClosingParenToken( + sourceCode.getLastToken(node), + ) && + astUtils.isOpeningParenToken( + sourceCode.getLastToken(node, 1), + )) + ) { + addFunctionCallIndent(node); + } + }, + + Property(node) { + if (!node.shorthand && !node.method && node.kind === "init") { + const colon = sourceCode.getFirstTokenBetween( + node.key, + node.value, + astUtils.isColonToken, + ); + + offsets.ignoreToken(sourceCode.getTokenAfter(colon)); + } + }, + + PropertyDefinition(node) { + const firstToken = sourceCode.getFirstToken(node); + const maybeSemicolonToken = sourceCode.getLastToken(node); + let keyLastToken; + + // Indent key. + if (node.computed) { + const bracketTokenL = sourceCode.getTokenBefore( + node.key, + astUtils.isOpeningBracketToken, + ); + const bracketTokenR = (keyLastToken = + sourceCode.getTokenAfter( + node.key, + astUtils.isClosingBracketToken, + )); + const keyRange = [ + bracketTokenL.range[1], + bracketTokenR.range[0], + ]; + + if (bracketTokenL !== firstToken) { + offsets.setDesiredOffset(bracketTokenL, firstToken, 0); + } + offsets.setDesiredOffsets(keyRange, bracketTokenL, 1); + offsets.setDesiredOffset(bracketTokenR, bracketTokenL, 0); + } else { + const idToken = (keyLastToken = sourceCode.getFirstToken( + node.key, + )); + + if (idToken !== firstToken) { + offsets.setDesiredOffset(idToken, firstToken, 1); + } + } + + // Indent initializer. + if (node.value) { + const eqToken = sourceCode.getTokenBefore( + node.value, + astUtils.isEqToken, + ); + const valueToken = sourceCode.getTokenAfter(eqToken); + + offsets.setDesiredOffset(eqToken, keyLastToken, 1); + offsets.setDesiredOffset(valueToken, eqToken, 1); + if (astUtils.isSemicolonToken(maybeSemicolonToken)) { + offsets.setDesiredOffset( + maybeSemicolonToken, + eqToken, + 1, + ); + } + } else if (astUtils.isSemicolonToken(maybeSemicolonToken)) { + offsets.setDesiredOffset( + maybeSemicolonToken, + keyLastToken, + 1, + ); + } + }, + + StaticBlock(node) { + const openingCurly = sourceCode.getFirstToken(node, { + skip: 1, + }); // skip the `static` token + const closingCurly = sourceCode.getLastToken(node); + + addElementListIndent( + node.body, + openingCurly, + closingCurly, + options.StaticBlock.body, + ); + }, + + SwitchStatement(node) { + const openingCurly = sourceCode.getTokenAfter( + node.discriminant, + astUtils.isOpeningBraceToken, + ); + const closingCurly = sourceCode.getLastToken(node); + + offsets.setDesiredOffsets( + [openingCurly.range[1], closingCurly.range[0]], + openingCurly, + options.SwitchCase, + ); + + if (node.cases.length) { + sourceCode + .getTokensBetween(node.cases.at(-1), closingCurly, { + includeComments: true, + filter: astUtils.isCommentToken, + }) + .forEach(token => offsets.ignoreToken(token)); + } + }, + + SwitchCase(node) { + if ( + !( + node.consequent.length === 1 && + node.consequent[0].type === "BlockStatement" + ) + ) { + const caseKeyword = sourceCode.getFirstToken(node); + const tokenAfterCurrentCase = + sourceCode.getTokenAfter(node); + + offsets.setDesiredOffsets( + [caseKeyword.range[1], tokenAfterCurrentCase.range[0]], + caseKeyword, + 1, + ); + } + }, + + TemplateLiteral(node) { + node.expressions.forEach((expression, index) => { + const previousQuasi = node.quasis[index]; + const nextQuasi = node.quasis[index + 1]; + const tokenToAlignFrom = + previousQuasi.loc.start.line === + previousQuasi.loc.end.line + ? sourceCode.getFirstToken(previousQuasi) + : null; + + offsets.setDesiredOffsets( + [previousQuasi.range[1], nextQuasi.range[0]], + tokenToAlignFrom, + 1, + ); + offsets.setDesiredOffset( + sourceCode.getFirstToken(nextQuasi), + tokenToAlignFrom, + 0, + ); + }); + }, + + VariableDeclaration(node) { + let variableIndent = Object.hasOwn( + options.VariableDeclarator, + node.kind, + ) + ? options.VariableDeclarator[node.kind] + : DEFAULT_VARIABLE_INDENT; + + const firstToken = sourceCode.getFirstToken(node), + lastToken = sourceCode.getLastToken(node); + + if (options.VariableDeclarator[node.kind] === "first") { + if (node.declarations.length > 1) { + addElementListIndent( + node.declarations, + firstToken, + lastToken, + "first", + ); + return; + } + + variableIndent = DEFAULT_VARIABLE_INDENT; + } + + if ( + node.declarations.at(-1).loc.start.line > + node.loc.start.line + ) { + /* + * VariableDeclarator indentation is a bit different from other forms of indentation, in that the + * indentation of an opening bracket sometimes won't match that of a closing bracket. For example, + * the following indentations are correct: + * + * var foo = { + * ok: true + * }; + * + * var foo = { + * ok: true, + * }, + * bar = 1; + * + * Account for when exiting the AST (after indentations have already been set for the nodes in + * the declaration) by manually increasing the indentation level of the tokens in this declarator + * on the same line as the start of the declaration, provided that there are declarators that + * follow this one. + */ + offsets.setDesiredOffsets( + node.range, + firstToken, + variableIndent, + true, + ); + } else { + offsets.setDesiredOffsets( + node.range, + firstToken, + variableIndent, + ); + } + + if (astUtils.isSemicolonToken(lastToken)) { + offsets.ignoreToken(lastToken); + } + }, + + VariableDeclarator(node) { + if (node.init) { + const equalOperator = sourceCode.getTokenBefore( + node.init, + astUtils.isNotOpeningParenToken, + ); + const tokenAfterOperator = + sourceCode.getTokenAfter(equalOperator); + + offsets.ignoreToken(equalOperator); + offsets.ignoreToken(tokenAfterOperator); + offsets.setDesiredOffsets( + [tokenAfterOperator.range[0], node.range[1]], + equalOperator, + 1, + ); + offsets.setDesiredOffset( + equalOperator, + sourceCode.getLastToken(node.id), + 0, + ); + } + }, + + "JSXAttribute[value]"(node) { + const equalsToken = sourceCode.getFirstTokenBetween( + node.name, + node.value, + token => token.type === "Punctuator" && token.value === "=", + ); + + offsets.setDesiredOffsets( + [equalsToken.range[0], node.value.range[1]], + sourceCode.getFirstToken(node.name), + 1, + ); + }, + + JSXElement(node) { + if (node.closingElement) { + addElementListIndent( + node.children, + sourceCode.getFirstToken(node.openingElement), + sourceCode.getFirstToken(node.closingElement), + 1, + ); + } + }, + + JSXOpeningElement(node) { + const firstToken = sourceCode.getFirstToken(node); + let closingToken; + + if (node.selfClosing) { + closingToken = sourceCode.getLastToken(node, { skip: 1 }); + offsets.setDesiredOffset( + sourceCode.getLastToken(node), + closingToken, + 0, + ); + } else { + closingToken = sourceCode.getLastToken(node); + } + offsets.setDesiredOffsets( + node.name.range, + sourceCode.getFirstToken(node), + ); + addElementListIndent( + node.attributes, + firstToken, + closingToken, + 1, + ); + }, + + JSXClosingElement(node) { + const firstToken = sourceCode.getFirstToken(node); + + offsets.setDesiredOffsets(node.name.range, firstToken, 1); + }, + + JSXFragment(node) { + const firstOpeningToken = sourceCode.getFirstToken( + node.openingFragment, + ); + const firstClosingToken = sourceCode.getFirstToken( + node.closingFragment, + ); + + addElementListIndent( + node.children, + firstOpeningToken, + firstClosingToken, + 1, + ); + }, + + JSXOpeningFragment(node) { + const firstToken = sourceCode.getFirstToken(node); + const closingToken = sourceCode.getLastToken(node); + + offsets.setDesiredOffsets(node.range, firstToken, 1); + offsets.matchOffsetOf(firstToken, closingToken); + }, + + JSXClosingFragment(node) { + const firstToken = sourceCode.getFirstToken(node); + const slashToken = sourceCode.getLastToken(node, { skip: 1 }); + const closingToken = sourceCode.getLastToken(node); + const tokenToMatch = astUtils.isTokenOnSameLine( + slashToken, + closingToken, + ) + ? slashToken + : closingToken; + + offsets.setDesiredOffsets(node.range, firstToken, 1); + offsets.matchOffsetOf(firstToken, tokenToMatch); + }, + + JSXExpressionContainer(node) { + const openingCurly = sourceCode.getFirstToken(node); + const closingCurly = sourceCode.getLastToken(node); + + offsets.setDesiredOffsets( + [openingCurly.range[1], closingCurly.range[0]], + openingCurly, + 1, + ); + }, + + JSXSpreadAttribute(node) { + const openingCurly = sourceCode.getFirstToken(node); + const closingCurly = sourceCode.getLastToken(node); + + offsets.setDesiredOffsets( + [openingCurly.range[1], closingCurly.range[0]], + openingCurly, + 1, + ); + }, + + "*"(node) { + const firstToken = sourceCode.getFirstToken(node); + + // Ensure that the children of every node are indented at least as much as the first token. + if (firstToken && !ignoredNodeFirstTokens.has(firstToken)) { + offsets.setDesiredOffsets(node.range, firstToken, 0); + } + }, + }; + + const listenerCallQueue = []; + + /* + * To ignore the indentation of a node: + * 1. Don't call the node's listener when entering it (if it has a listener) + * 2. Don't set any offsets against the first token of the node. + * 3. Call `ignoreNode` on the node sometime after exiting it and before validating offsets. + */ + const offsetListeners = {}; + + for (const [selector, listener] of Object.entries( + baseOffsetListeners, + )) { + /* + * Offset listener calls are deferred until traversal is finished, and are called as + * part of the final `Program:exit` listener. This is necessary because a node might + * be matched by multiple selectors. + * + * Example: Suppose there is an offset listener for `Identifier`, and the user has + * specified in configuration that `MemberExpression > Identifier` should be ignored. + * Due to selector specificity rules, the `Identifier` listener will get called first. However, + * if a given Identifier node is supposed to be ignored, then the `Identifier` offset listener + * should not have been called at all. Without doing extra selector matching, we don't know + * whether the Identifier matches the `MemberExpression > Identifier` selector until the + * `MemberExpression > Identifier` listener is called. + * + * To avoid this, the `Identifier` listener isn't called until traversal finishes and all + * ignored nodes are known. + */ + offsetListeners[selector] = node => + listenerCallQueue.push({ listener, node }); + } + + // For each ignored node selector, set up a listener to collect it into the `ignoredNodes` set. + const ignoredNodes = new Set(); + + /** + * Ignores a node + * @param {ASTNode} node The node to ignore + * @returns {void} + */ + function addToIgnoredNodes(node) { + ignoredNodes.add(node); + ignoredNodeFirstTokens.add(sourceCode.getFirstToken(node)); + } + + const ignoredNodeListeners = options.ignoredNodes.reduce( + (listeners, ignoredSelector) => + Object.assign(listeners, { + [ignoredSelector]: addToIgnoredNodes, + }), + {}, + ); + + /* + * Join the listeners, and add a listener to verify that all tokens actually have the correct indentation + * at the end. + * + * Using Object.assign will cause some offset listeners to be overwritten if the same selector also appears + * in `ignoredNodeListeners`. This isn't a problem because all of the matching nodes will be ignored, + * so those listeners wouldn't be called anyway. + */ + return Object.assign(offsetListeners, ignoredNodeListeners, { + "*:exit"(node) { + // If a node's type is nonstandard, we can't tell how its children should be offset, so ignore it. + if (!KNOWN_NODES.has(node.type)) { + addToIgnoredNodes(node); + } + }, + "Program:exit"() { + // If ignoreComments option is enabled, ignore all comment tokens. + if (options.ignoreComments) { + sourceCode + .getAllComments() + .forEach(comment => offsets.ignoreToken(comment)); + } + + // Invoke the queued offset listeners for the nodes that aren't ignored. + for (let i = 0; i < listenerCallQueue.length; i++) { + const nodeInfo = listenerCallQueue[i]; + + if (!ignoredNodes.has(nodeInfo.node)) { + nodeInfo.listener(nodeInfo.node); + } + } + + // Update the offsets for ignored nodes to prevent their child tokens from being reported. + ignoredNodes.forEach(ignoreNode); + + addParensIndent(sourceCode.ast.tokens); + + /* + * Create a Map from (tokenOrComment) => (precedingToken). + * This is necessary because sourceCode.getTokenBefore does not handle a comment as an argument correctly. + */ + const precedingTokens = new WeakMap(); + + for (let i = 0; i < sourceCode.ast.comments.length; i++) { + const comment = sourceCode.ast.comments[i]; + + const tokenOrCommentBefore = sourceCode.getTokenBefore( + comment, + { includeComments: true }, + ); + const hasToken = precedingTokens.has(tokenOrCommentBefore) + ? precedingTokens.get(tokenOrCommentBefore) + : tokenOrCommentBefore; + + precedingTokens.set(comment, hasToken); + } + + for (let i = 1; i < sourceCode.lines.length + 1; i++) { + if (!tokenInfo.firstTokensByLineNumber.has(i)) { + // Don't check indentation on blank lines + continue; + } + + const firstTokenOfLine = + tokenInfo.firstTokensByLineNumber.get(i); + + if (firstTokenOfLine.loc.start.line !== i) { + // Don't check the indentation of multi-line tokens (e.g. template literals or block comments) twice. + continue; + } + + if (astUtils.isCommentToken(firstTokenOfLine)) { + const tokenBefore = + precedingTokens.get(firstTokenOfLine); + const tokenAfter = tokenBefore + ? sourceCode.getTokenAfter(tokenBefore) + : sourceCode.ast.tokens[0]; + const mayAlignWithBefore = + tokenBefore && + !hasBlankLinesBetween( + tokenBefore, + firstTokenOfLine, + ); + const mayAlignWithAfter = + tokenAfter && + !hasBlankLinesBetween(firstTokenOfLine, tokenAfter); + + /* + * If a comment precedes a line that begins with a semicolon token, align to that token, i.e. + * + * let foo + * // comment + * ;(async () => {})() + */ + if ( + tokenAfter && + astUtils.isSemicolonToken(tokenAfter) && + !astUtils.isTokenOnSameLine( + firstTokenOfLine, + tokenAfter, + ) + ) { + offsets.setDesiredOffset( + firstTokenOfLine, + tokenAfter, + 0, + ); + } + + // If a comment matches the expected indentation of the token immediately before or after, don't report it. + if ( + (mayAlignWithBefore && + validateTokenIndent( + firstTokenOfLine, + offsets.getDesiredIndent(tokenBefore), + )) || + (mayAlignWithAfter && + validateTokenIndent( + firstTokenOfLine, + offsets.getDesiredIndent(tokenAfter), + )) + ) { + continue; + } + } + + // If the token matches the expected indentation, don't report it. + if ( + validateTokenIndent( + firstTokenOfLine, + offsets.getDesiredIndent(firstTokenOfLine), + ) + ) { + continue; + } + + // Otherwise, report the token/comment. + report( + firstTokenOfLine, + offsets.getDesiredIndent(firstTokenOfLine), + ); + } + }, + }); + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/index.js b/tools/ui/node_modules/eslint/lib/rules/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a750e0872782a9126c720bc06ea8cc806405439c --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/index.js @@ -0,0 +1,332 @@ +/** + * @fileoverview Collects the built-in rules into a map structure so that they can be imported all at once and without + * using the file-system directly. + * @author Peter (Somogyvari) Metz + */ + +"use strict"; + +/* eslint sort-keys: ["error", "asc"] -- More readable for long list */ + +const { LazyLoadingRuleMap } = require("./utils/lazy-loading-rule-map"); + +/** @type {Map} */ +module.exports = new LazyLoadingRuleMap( + Object.entries({ + "accessor-pairs": () => require("./accessor-pairs"), + "array-bracket-newline": () => require("./array-bracket-newline"), + "array-bracket-spacing": () => require("./array-bracket-spacing"), + "array-callback-return": () => require("./array-callback-return"), + "array-element-newline": () => require("./array-element-newline"), + "arrow-body-style": () => require("./arrow-body-style"), + "arrow-parens": () => require("./arrow-parens"), + "arrow-spacing": () => require("./arrow-spacing"), + "block-scoped-var": () => require("./block-scoped-var"), + "block-spacing": () => require("./block-spacing"), + "brace-style": () => require("./brace-style"), + "callback-return": () => require("./callback-return"), + camelcase: () => require("./camelcase"), + "capitalized-comments": () => require("./capitalized-comments"), + "class-methods-use-this": () => require("./class-methods-use-this"), + "comma-dangle": () => require("./comma-dangle"), + "comma-spacing": () => require("./comma-spacing"), + "comma-style": () => require("./comma-style"), + complexity: () => require("./complexity"), + "computed-property-spacing": () => + require("./computed-property-spacing"), + "consistent-return": () => require("./consistent-return"), + "consistent-this": () => require("./consistent-this"), + "constructor-super": () => require("./constructor-super"), + curly: () => require("./curly"), + "default-case": () => require("./default-case"), + "default-case-last": () => require("./default-case-last"), + "default-param-last": () => require("./default-param-last"), + "dot-location": () => require("./dot-location"), + "dot-notation": () => require("./dot-notation"), + "eol-last": () => require("./eol-last"), + eqeqeq: () => require("./eqeqeq"), + "for-direction": () => require("./for-direction"), + "func-call-spacing": () => require("./func-call-spacing"), + "func-name-matching": () => require("./func-name-matching"), + "func-names": () => require("./func-names"), + "func-style": () => require("./func-style"), + "function-call-argument-newline": () => + require("./function-call-argument-newline"), + "function-paren-newline": () => require("./function-paren-newline"), + "generator-star-spacing": () => require("./generator-star-spacing"), + "getter-return": () => require("./getter-return"), + "global-require": () => require("./global-require"), + "grouped-accessor-pairs": () => require("./grouped-accessor-pairs"), + "guard-for-in": () => require("./guard-for-in"), + "handle-callback-err": () => require("./handle-callback-err"), + "id-blacklist": () => require("./id-blacklist"), + "id-denylist": () => require("./id-denylist"), + "id-length": () => require("./id-length"), + "id-match": () => require("./id-match"), + "implicit-arrow-linebreak": () => require("./implicit-arrow-linebreak"), + indent: () => require("./indent"), + "indent-legacy": () => require("./indent-legacy"), + "init-declarations": () => require("./init-declarations"), + "jsx-quotes": () => require("./jsx-quotes"), + "key-spacing": () => require("./key-spacing"), + "keyword-spacing": () => require("./keyword-spacing"), + "line-comment-position": () => require("./line-comment-position"), + "linebreak-style": () => require("./linebreak-style"), + "lines-around-comment": () => require("./lines-around-comment"), + "lines-around-directive": () => require("./lines-around-directive"), + "lines-between-class-members": () => + require("./lines-between-class-members"), + "logical-assignment-operators": () => + require("./logical-assignment-operators"), + "max-classes-per-file": () => require("./max-classes-per-file"), + "max-depth": () => require("./max-depth"), + "max-len": () => require("./max-len"), + "max-lines": () => require("./max-lines"), + "max-lines-per-function": () => require("./max-lines-per-function"), + "max-nested-callbacks": () => require("./max-nested-callbacks"), + "max-params": () => require("./max-params"), + "max-statements": () => require("./max-statements"), + "max-statements-per-line": () => require("./max-statements-per-line"), + "multiline-comment-style": () => require("./multiline-comment-style"), + "multiline-ternary": () => require("./multiline-ternary"), + "new-cap": () => require("./new-cap"), + "new-parens": () => require("./new-parens"), + "newline-after-var": () => require("./newline-after-var"), + "newline-before-return": () => require("./newline-before-return"), + "newline-per-chained-call": () => require("./newline-per-chained-call"), + "no-alert": () => require("./no-alert"), + "no-array-constructor": () => require("./no-array-constructor"), + "no-async-promise-executor": () => + require("./no-async-promise-executor"), + "no-await-in-loop": () => require("./no-await-in-loop"), + "no-bitwise": () => require("./no-bitwise"), + "no-buffer-constructor": () => require("./no-buffer-constructor"), + "no-caller": () => require("./no-caller"), + "no-case-declarations": () => require("./no-case-declarations"), + "no-catch-shadow": () => require("./no-catch-shadow"), + "no-class-assign": () => require("./no-class-assign"), + "no-compare-neg-zero": () => require("./no-compare-neg-zero"), + "no-cond-assign": () => require("./no-cond-assign"), + "no-confusing-arrow": () => require("./no-confusing-arrow"), + "no-console": () => require("./no-console"), + "no-const-assign": () => require("./no-const-assign"), + "no-constant-binary-expression": () => + require("./no-constant-binary-expression"), + "no-constant-condition": () => require("./no-constant-condition"), + "no-constructor-return": () => require("./no-constructor-return"), + "no-continue": () => require("./no-continue"), + "no-control-regex": () => require("./no-control-regex"), + "no-debugger": () => require("./no-debugger"), + "no-delete-var": () => require("./no-delete-var"), + "no-div-regex": () => require("./no-div-regex"), + "no-dupe-args": () => require("./no-dupe-args"), + "no-dupe-class-members": () => require("./no-dupe-class-members"), + "no-dupe-else-if": () => require("./no-dupe-else-if"), + "no-dupe-keys": () => require("./no-dupe-keys"), + "no-duplicate-case": () => require("./no-duplicate-case"), + "no-duplicate-imports": () => require("./no-duplicate-imports"), + "no-else-return": () => require("./no-else-return"), + "no-empty": () => require("./no-empty"), + "no-empty-character-class": () => require("./no-empty-character-class"), + "no-empty-function": () => require("./no-empty-function"), + "no-empty-pattern": () => require("./no-empty-pattern"), + "no-empty-static-block": () => require("./no-empty-static-block"), + "no-eq-null": () => require("./no-eq-null"), + "no-eval": () => require("./no-eval"), + "no-ex-assign": () => require("./no-ex-assign"), + "no-extend-native": () => require("./no-extend-native"), + "no-extra-bind": () => require("./no-extra-bind"), + "no-extra-boolean-cast": () => require("./no-extra-boolean-cast"), + "no-extra-label": () => require("./no-extra-label"), + "no-extra-parens": () => require("./no-extra-parens"), + "no-extra-semi": () => require("./no-extra-semi"), + "no-fallthrough": () => require("./no-fallthrough"), + "no-floating-decimal": () => require("./no-floating-decimal"), + "no-func-assign": () => require("./no-func-assign"), + "no-global-assign": () => require("./no-global-assign"), + "no-implicit-coercion": () => require("./no-implicit-coercion"), + "no-implicit-globals": () => require("./no-implicit-globals"), + "no-implied-eval": () => require("./no-implied-eval"), + "no-import-assign": () => require("./no-import-assign"), + "no-inline-comments": () => require("./no-inline-comments"), + "no-inner-declarations": () => require("./no-inner-declarations"), + "no-invalid-regexp": () => require("./no-invalid-regexp"), + "no-invalid-this": () => require("./no-invalid-this"), + "no-irregular-whitespace": () => require("./no-irregular-whitespace"), + "no-iterator": () => require("./no-iterator"), + "no-label-var": () => require("./no-label-var"), + "no-labels": () => require("./no-labels"), + "no-lone-blocks": () => require("./no-lone-blocks"), + "no-lonely-if": () => require("./no-lonely-if"), + "no-loop-func": () => require("./no-loop-func"), + "no-loss-of-precision": () => require("./no-loss-of-precision"), + "no-magic-numbers": () => require("./no-magic-numbers"), + "no-misleading-character-class": () => + require("./no-misleading-character-class"), + "no-mixed-operators": () => require("./no-mixed-operators"), + "no-mixed-requires": () => require("./no-mixed-requires"), + "no-mixed-spaces-and-tabs": () => require("./no-mixed-spaces-and-tabs"), + "no-multi-assign": () => require("./no-multi-assign"), + "no-multi-spaces": () => require("./no-multi-spaces"), + "no-multi-str": () => require("./no-multi-str"), + "no-multiple-empty-lines": () => require("./no-multiple-empty-lines"), + "no-native-reassign": () => require("./no-native-reassign"), + "no-negated-condition": () => require("./no-negated-condition"), + "no-negated-in-lhs": () => require("./no-negated-in-lhs"), + "no-nested-ternary": () => require("./no-nested-ternary"), + "no-new": () => require("./no-new"), + "no-new-func": () => require("./no-new-func"), + "no-new-native-nonconstructor": () => + require("./no-new-native-nonconstructor"), + "no-new-object": () => require("./no-new-object"), + "no-new-require": () => require("./no-new-require"), + "no-new-symbol": () => require("./no-new-symbol"), + "no-new-wrappers": () => require("./no-new-wrappers"), + "no-nonoctal-decimal-escape": () => + require("./no-nonoctal-decimal-escape"), + "no-obj-calls": () => require("./no-obj-calls"), + "no-object-constructor": () => require("./no-object-constructor"), + "no-octal": () => require("./no-octal"), + "no-octal-escape": () => require("./no-octal-escape"), + "no-param-reassign": () => require("./no-param-reassign"), + "no-path-concat": () => require("./no-path-concat"), + "no-plusplus": () => require("./no-plusplus"), + "no-process-env": () => require("./no-process-env"), + "no-process-exit": () => require("./no-process-exit"), + "no-promise-executor-return": () => + require("./no-promise-executor-return"), + "no-proto": () => require("./no-proto"), + "no-prototype-builtins": () => require("./no-prototype-builtins"), + "no-redeclare": () => require("./no-redeclare"), + "no-regex-spaces": () => require("./no-regex-spaces"), + "no-restricted-exports": () => require("./no-restricted-exports"), + "no-restricted-globals": () => require("./no-restricted-globals"), + "no-restricted-imports": () => require("./no-restricted-imports"), + "no-restricted-modules": () => require("./no-restricted-modules"), + "no-restricted-properties": () => require("./no-restricted-properties"), + "no-restricted-syntax": () => require("./no-restricted-syntax"), + "no-return-assign": () => require("./no-return-assign"), + "no-return-await": () => require("./no-return-await"), + "no-script-url": () => require("./no-script-url"), + "no-self-assign": () => require("./no-self-assign"), + "no-self-compare": () => require("./no-self-compare"), + "no-sequences": () => require("./no-sequences"), + "no-setter-return": () => require("./no-setter-return"), + "no-shadow": () => require("./no-shadow"), + "no-shadow-restricted-names": () => + require("./no-shadow-restricted-names"), + "no-spaced-func": () => require("./no-spaced-func"), + "no-sparse-arrays": () => require("./no-sparse-arrays"), + "no-sync": () => require("./no-sync"), + "no-tabs": () => require("./no-tabs"), + "no-template-curly-in-string": () => + require("./no-template-curly-in-string"), + "no-ternary": () => require("./no-ternary"), + "no-this-before-super": () => require("./no-this-before-super"), + "no-throw-literal": () => require("./no-throw-literal"), + "no-trailing-spaces": () => require("./no-trailing-spaces"), + "no-unassigned-vars": () => require("./no-unassigned-vars"), + "no-undef": () => require("./no-undef"), + "no-undef-init": () => require("./no-undef-init"), + "no-undefined": () => require("./no-undefined"), + "no-underscore-dangle": () => require("./no-underscore-dangle"), + "no-unexpected-multiline": () => require("./no-unexpected-multiline"), + "no-unmodified-loop-condition": () => + require("./no-unmodified-loop-condition"), + "no-unneeded-ternary": () => require("./no-unneeded-ternary"), + "no-unreachable": () => require("./no-unreachable"), + "no-unreachable-loop": () => require("./no-unreachable-loop"), + "no-unsafe-finally": () => require("./no-unsafe-finally"), + "no-unsafe-negation": () => require("./no-unsafe-negation"), + "no-unsafe-optional-chaining": () => + require("./no-unsafe-optional-chaining"), + "no-unused-expressions": () => require("./no-unused-expressions"), + "no-unused-labels": () => require("./no-unused-labels"), + "no-unused-private-class-members": () => + require("./no-unused-private-class-members"), + "no-unused-vars": () => require("./no-unused-vars"), + "no-use-before-define": () => require("./no-use-before-define"), + "no-useless-assignment": () => require("./no-useless-assignment"), + "no-useless-backreference": () => require("./no-useless-backreference"), + "no-useless-call": () => require("./no-useless-call"), + "no-useless-catch": () => require("./no-useless-catch"), + "no-useless-computed-key": () => require("./no-useless-computed-key"), + "no-useless-concat": () => require("./no-useless-concat"), + "no-useless-constructor": () => require("./no-useless-constructor"), + "no-useless-escape": () => require("./no-useless-escape"), + "no-useless-rename": () => require("./no-useless-rename"), + "no-useless-return": () => require("./no-useless-return"), + "no-var": () => require("./no-var"), + "no-void": () => require("./no-void"), + "no-warning-comments": () => require("./no-warning-comments"), + "no-whitespace-before-property": () => + require("./no-whitespace-before-property"), + "no-with": () => require("./no-with"), + "nonblock-statement-body-position": () => + require("./nonblock-statement-body-position"), + "object-curly-newline": () => require("./object-curly-newline"), + "object-curly-spacing": () => require("./object-curly-spacing"), + "object-property-newline": () => require("./object-property-newline"), + "object-shorthand": () => require("./object-shorthand"), + "one-var": () => require("./one-var"), + "one-var-declaration-per-line": () => + require("./one-var-declaration-per-line"), + "operator-assignment": () => require("./operator-assignment"), + "operator-linebreak": () => require("./operator-linebreak"), + "padded-blocks": () => require("./padded-blocks"), + "padding-line-between-statements": () => + require("./padding-line-between-statements"), + "prefer-arrow-callback": () => require("./prefer-arrow-callback"), + "prefer-const": () => require("./prefer-const"), + "prefer-destructuring": () => require("./prefer-destructuring"), + "prefer-exponentiation-operator": () => + require("./prefer-exponentiation-operator"), + "prefer-named-capture-group": () => + require("./prefer-named-capture-group"), + "prefer-numeric-literals": () => require("./prefer-numeric-literals"), + "prefer-object-has-own": () => require("./prefer-object-has-own"), + "prefer-object-spread": () => require("./prefer-object-spread"), + "prefer-promise-reject-errors": () => + require("./prefer-promise-reject-errors"), + "prefer-reflect": () => require("./prefer-reflect"), + "prefer-regex-literals": () => require("./prefer-regex-literals"), + "prefer-rest-params": () => require("./prefer-rest-params"), + "prefer-spread": () => require("./prefer-spread"), + "prefer-template": () => require("./prefer-template"), + "preserve-caught-error": () => require("./preserve-caught-error"), + "quote-props": () => require("./quote-props"), + quotes: () => require("./quotes"), + radix: () => require("./radix"), + "require-atomic-updates": () => require("./require-atomic-updates"), + "require-await": () => require("./require-await"), + "require-unicode-regexp": () => require("./require-unicode-regexp"), + "require-yield": () => require("./require-yield"), + "rest-spread-spacing": () => require("./rest-spread-spacing"), + semi: () => require("./semi"), + "semi-spacing": () => require("./semi-spacing"), + "semi-style": () => require("./semi-style"), + "sort-imports": () => require("./sort-imports"), + "sort-keys": () => require("./sort-keys"), + "sort-vars": () => require("./sort-vars"), + "space-before-blocks": () => require("./space-before-blocks"), + "space-before-function-paren": () => + require("./space-before-function-paren"), + "space-in-parens": () => require("./space-in-parens"), + "space-infix-ops": () => require("./space-infix-ops"), + "space-unary-ops": () => require("./space-unary-ops"), + "spaced-comment": () => require("./spaced-comment"), + strict: () => require("./strict"), + "switch-colon-spacing": () => require("./switch-colon-spacing"), + "symbol-description": () => require("./symbol-description"), + "template-curly-spacing": () => require("./template-curly-spacing"), + "template-tag-spacing": () => require("./template-tag-spacing"), + "unicode-bom": () => require("./unicode-bom"), + "use-isnan": () => require("./use-isnan"), + "valid-typeof": () => require("./valid-typeof"), + "vars-on-top": () => require("./vars-on-top"), + "wrap-iife": () => require("./wrap-iife"), + "wrap-regex": () => require("./wrap-regex"), + "yield-star-spacing": () => require("./yield-star-spacing"), + yoda: () => require("./yoda"), + }), +); diff --git a/tools/ui/node_modules/eslint/lib/rules/init-declarations.js b/tools/ui/node_modules/eslint/lib/rules/init-declarations.js new file mode 100644 index 0000000000000000000000000000000000000000..15dac379fadadfc0e81bcefddc49d11ef2be3c8a --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/init-declarations.js @@ -0,0 +1,172 @@ +/** + * @fileoverview A rule to control the style of variable initializations. + * @author Colin Ihrig + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const CONSTANT_BINDINGS = new Set(["const", "using", "await using"]); + +/** + * Checks whether or not a given node is a for loop. + * @param {ASTNode} block A node to check. + * @returns {boolean} `true` when the node is a for loop. + */ +function isForLoop(block) { + return ( + block.type === "ForInStatement" || + block.type === "ForOfStatement" || + block.type === "ForStatement" + ); +} + +/** + * Checks whether or not a given declarator node has its initializer. + * @param {ASTNode} node A declarator node to check. + * @returns {boolean} `true` when the node has its initializer. + */ +function isInitialized(node) { + const declaration = node.parent; + const block = declaration.parent; + + if (isForLoop(block)) { + if (block.type === "ForStatement") { + return block.init === declaration; + } + return block.left === declaration; + } + return Boolean(node.init); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "suggestion", + dialects: ["typescript", "javascript"], + language: "javascript", + + docs: { + description: + "Require or disallow initialization in variable declarations", + recommended: false, + frozen: true, + url: "https://eslint.org/docs/latest/rules/init-declarations", + }, + + schema: { + anyOf: [ + { + type: "array", + items: [ + { + enum: ["always"], + }, + ], + minItems: 0, + maxItems: 1, + }, + { + type: "array", + items: [ + { + enum: ["never"], + }, + { + type: "object", + properties: { + ignoreForLoopInit: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + minItems: 0, + maxItems: 2, + }, + ], + }, + messages: { + initialized: + "Variable '{{idName}}' should be initialized on declaration.", + notInitialized: + "Variable '{{idName}}' should not be initialized on declaration.", + }, + }, + + create(context) { + const MODE_ALWAYS = "always", + MODE_NEVER = "never"; + + const mode = context.options[0] || MODE_ALWAYS; + const params = context.options[1] || {}; + + // Track whether we're inside a declared namespace + let insideDeclaredNamespace = false; + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + TSModuleDeclaration(node) { + if (node.declare) { + insideDeclaredNamespace = true; + } + }, + + "TSModuleDeclaration:exit"(node) { + if (node.declare) { + insideDeclaredNamespace = false; + } + }, + + "VariableDeclaration:exit"(node) { + const kind = node.kind, + declarations = node.declarations; + + if (node.declare || insideDeclaredNamespace) { + return; + } + + for (let i = 0; i < declarations.length; ++i) { + const declaration = declarations[i], + id = declaration.id, + initialized = isInitialized(declaration), + isIgnoredForLoop = + params.ignoreForLoopInit && isForLoop(node.parent); + let messageId = ""; + + if (mode === MODE_ALWAYS && !initialized) { + messageId = "initialized"; + } else if ( + mode === MODE_NEVER && + !CONSTANT_BINDINGS.has(kind) && + initialized && + !isIgnoredForLoop + ) { + messageId = "notInitialized"; + } + + if (id.type === "Identifier" && messageId) { + context.report({ + node: declaration, + messageId, + data: { + idName: id.name, + }, + }); + } + } + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/jsx-quotes.js b/tools/ui/node_modules/eslint/lib/rules/jsx-quotes.js new file mode 100644 index 0000000000000000000000000000000000000000..f435d9cbf8c03a898350be7684a157dab178ceb6 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/jsx-quotes.js @@ -0,0 +1,128 @@ +/** + * @fileoverview A rule to ensure consistent quotes used in jsx syntax. + * @author Mathias Schreck + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Constants +//------------------------------------------------------------------------------ + +const QUOTE_SETTINGS = { + "prefer-double": { + quote: '"', + description: "singlequote", + convert(str) { + return str.replace(/'/gu, '"'); + }, + }, + "prefer-single": { + quote: "'", + description: "doublequote", + convert(str) { + return str.replace(/"/gu, "'"); + }, + }, +}; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "jsx-quotes", + url: "https://eslint.style/rules/jsx-quotes", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Enforce the consistent use of either double or single quotes in JSX attributes", + recommended: false, + url: "https://eslint.org/docs/latest/rules/jsx-quotes", + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["prefer-single", "prefer-double"], + }, + ], + messages: { + unexpected: "Unexpected usage of {{description}}.", + }, + }, + + create(context) { + const quoteOption = context.options[0] || "prefer-double", + setting = QUOTE_SETTINGS[quoteOption]; + + /** + * Checks if the given string literal node uses the expected quotes + * @param {ASTNode} node A string literal node. + * @returns {boolean} Whether or not the string literal used the expected quotes. + * @public + */ + function usesExpectedQuotes(node) { + return ( + node.value.includes(setting.quote) || + astUtils.isSurroundedBy(node.raw, setting.quote) + ); + } + + return { + JSXAttribute(node) { + const attributeValue = node.value; + + if ( + attributeValue && + astUtils.isStringLiteral(attributeValue) && + !usesExpectedQuotes(attributeValue) + ) { + context.report({ + node: attributeValue, + messageId: "unexpected", + data: { + description: setting.description, + }, + fix(fixer) { + return fixer.replaceText( + attributeValue, + setting.convert(attributeValue.raw), + ); + }, + }); + } + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/key-spacing.js b/tools/ui/node_modules/eslint/lib/rules/key-spacing.js new file mode 100644 index 0000000000000000000000000000000000000000..6ab192ec65109d2c988f6bc3de5a20eaa764de1b --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/key-spacing.js @@ -0,0 +1,822 @@ +/** + * @fileoverview Rule to specify spacing of object literal keys and values + * @author Brandon Mills + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); +const { getGraphemeCount } = require("../shared/string-utils"); + +/** + * Checks whether a string contains a line terminator as defined in + * http://www.ecma-international.org/ecma-262/5.1/#sec-7.3 + * @param {string} str String to test. + * @returns {boolean} True if str contains a line terminator. + */ +function containsLineTerminator(str) { + return astUtils.LINEBREAK_MATCHER.test(str); +} + +/** + * Gets the last element of an array. + * @param {Array} arr An array. + * @returns {any} Last element of arr. + */ +function last(arr) { + return arr.at(-1); +} + +/** + * Checks whether a node is contained on a single line. + * @param {ASTNode} node AST Node being evaluated. + * @returns {boolean} True if the node is a single line. + */ +function isSingleLine(node) { + return node.loc.end.line === node.loc.start.line; +} + +/** + * Checks whether the properties on a single line. + * @param {ASTNode[]} properties List of Property AST nodes. + * @returns {boolean} True if all properties is on a single line. + */ +function isSingleLineProperties(properties) { + const [firstProp] = properties, + lastProp = last(properties); + + return firstProp.loc.start.line === lastProp.loc.end.line; +} + +/** + * Initializes a single option property from the configuration with defaults for undefined values + * @param {Object} toOptions Object to be initialized + * @param {Object} fromOptions Object to be initialized from + * @returns {Object} The object with correctly initialized options and values + */ +function initOptionProperty(toOptions, fromOptions) { + toOptions.mode = fromOptions.mode || "strict"; + + // Set value of beforeColon + if (typeof fromOptions.beforeColon !== "undefined") { + toOptions.beforeColon = +fromOptions.beforeColon; + } else { + toOptions.beforeColon = 0; + } + + // Set value of afterColon + if (typeof fromOptions.afterColon !== "undefined") { + toOptions.afterColon = +fromOptions.afterColon; + } else { + toOptions.afterColon = 1; + } + + // Set align if exists + if (typeof fromOptions.align !== "undefined") { + if (typeof fromOptions.align === "object") { + toOptions.align = fromOptions.align; + } else { + // "string" + toOptions.align = { + on: fromOptions.align, + mode: toOptions.mode, + beforeColon: toOptions.beforeColon, + afterColon: toOptions.afterColon, + }; + } + } + + return toOptions; +} + +/** + * Initializes all the option values (singleLine, multiLine and align) from the configuration with defaults for undefined values + * @param {Object} toOptions Object to be initialized + * @param {Object} fromOptions Object to be initialized from + * @returns {Object} The object with correctly initialized options and values + */ +function initOptions(toOptions, fromOptions) { + if (typeof fromOptions.align === "object") { + // Initialize the alignment configuration + toOptions.align = initOptionProperty({}, fromOptions.align); + toOptions.align.on = fromOptions.align.on || "colon"; + toOptions.align.mode = fromOptions.align.mode || "strict"; + + toOptions.multiLine = initOptionProperty( + {}, + fromOptions.multiLine || fromOptions, + ); + toOptions.singleLine = initOptionProperty( + {}, + fromOptions.singleLine || fromOptions, + ); + } else { + // string or undefined + toOptions.multiLine = initOptionProperty( + {}, + fromOptions.multiLine || fromOptions, + ); + toOptions.singleLine = initOptionProperty( + {}, + fromOptions.singleLine || fromOptions, + ); + + // If alignment options are defined in multiLine, pull them out into the general align configuration + if (toOptions.multiLine.align) { + toOptions.align = { + on: toOptions.multiLine.align.on, + mode: + toOptions.multiLine.align.mode || toOptions.multiLine.mode, + beforeColon: toOptions.multiLine.align.beforeColon, + afterColon: toOptions.multiLine.align.afterColon, + }; + } + } + + return toOptions; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "key-spacing", + url: "https://eslint.style/rules/key-spacing", + }, + }, + ], + }, + type: "layout", + + docs: { + description: + "Enforce consistent spacing between keys and values in object literal properties", + recommended: false, + url: "https://eslint.org/docs/latest/rules/key-spacing", + }, + + fixable: "whitespace", + + schema: [ + { + anyOf: [ + { + type: "object", + properties: { + align: { + anyOf: [ + { + enum: ["colon", "value"], + }, + { + type: "object", + properties: { + mode: { + enum: ["strict", "minimum"], + }, + on: { + enum: ["colon", "value"], + }, + beforeColon: { + type: "boolean", + }, + afterColon: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + }, + mode: { + enum: ["strict", "minimum"], + }, + beforeColon: { + type: "boolean", + }, + afterColon: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + { + type: "object", + properties: { + singleLine: { + type: "object", + properties: { + mode: { + enum: ["strict", "minimum"], + }, + beforeColon: { + type: "boolean", + }, + afterColon: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + multiLine: { + type: "object", + properties: { + align: { + anyOf: [ + { + enum: ["colon", "value"], + }, + { + type: "object", + properties: { + mode: { + enum: [ + "strict", + "minimum", + ], + }, + on: { + enum: [ + "colon", + "value", + ], + }, + beforeColon: { + type: "boolean", + }, + afterColon: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + }, + mode: { + enum: ["strict", "minimum"], + }, + beforeColon: { + type: "boolean", + }, + afterColon: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + }, + additionalProperties: false, + }, + { + type: "object", + properties: { + singleLine: { + type: "object", + properties: { + mode: { + enum: ["strict", "minimum"], + }, + beforeColon: { + type: "boolean", + }, + afterColon: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + multiLine: { + type: "object", + properties: { + mode: { + enum: ["strict", "minimum"], + }, + beforeColon: { + type: "boolean", + }, + afterColon: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + align: { + type: "object", + properties: { + mode: { + enum: ["strict", "minimum"], + }, + on: { + enum: ["colon", "value"], + }, + beforeColon: { + type: "boolean", + }, + afterColon: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + }, + additionalProperties: false, + }, + ], + }, + ], + messages: { + extraKey: "Extra space after {{computed}}key '{{key}}'.", + extraValue: + "Extra space before value for {{computed}}key '{{key}}'.", + missingKey: "Missing space after {{computed}}key '{{key}}'.", + missingValue: + "Missing space before value for {{computed}}key '{{key}}'.", + }, + }, + + create(context) { + /** + * OPTIONS + * "key-spacing": [2, { + * beforeColon: false, + * afterColon: true, + * align: "colon" // Optional, or "value" + * } + */ + const options = context.options[0] || {}, + ruleOptions = initOptions({}, options), + multiLineOptions = ruleOptions.multiLine, + singleLineOptions = ruleOptions.singleLine, + alignmentOptions = ruleOptions.align || null; + + const sourceCode = context.sourceCode; + + /** + * Determines if the given property is key-value property. + * @param {ASTNode} property Property node to check. + * @returns {boolean} Whether the property is a key-value property. + */ + function isKeyValueProperty(property) { + return !( + ( + property.method || + property.shorthand || + property.kind !== "init" || + property.type !== "Property" + ) // Could be "ExperimentalSpreadProperty" or "SpreadElement" + ); + } + + /** + * Starting from the given node (a property.key node here) looks forward + * until it finds the colon punctuator and returns it. + * @param {ASTNode} node The node to start looking from. + * @returns {ASTNode} The colon punctuator. + */ + function getNextColon(node) { + return sourceCode.getTokenAfter(node, astUtils.isColonToken); + } + + /** + * Starting from the given node (a property.key node here) looks forward + * until it finds the last token before a colon punctuator and returns it. + * @param {ASTNode} node The node to start looking from. + * @returns {ASTNode} The last token before a colon punctuator. + */ + function getLastTokenBeforeColon(node) { + const colonToken = getNextColon(node); + + return sourceCode.getTokenBefore(colonToken); + } + + /** + * Starting from the given node (a property.key node here) looks forward + * until it finds the first token after a colon punctuator and returns it. + * @param {ASTNode} node The node to start looking from. + * @returns {ASTNode} The first token after a colon punctuator. + */ + function getFirstTokenAfterColon(node) { + const colonToken = getNextColon(node); + + return sourceCode.getTokenAfter(colonToken); + } + + /** + * Checks whether a property is a member of the property group it follows. + * @param {ASTNode} lastMember The last Property known to be in the group. + * @param {ASTNode} candidate The next Property that might be in the group. + * @returns {boolean} True if the candidate property is part of the group. + */ + function continuesPropertyGroup(lastMember, candidate) { + const groupEndLine = lastMember.loc.start.line, + candidateValueStartLine = ( + isKeyValueProperty(candidate) + ? getFirstTokenAfterColon(candidate.key) + : candidate + ).loc.start.line; + + if (candidateValueStartLine - groupEndLine <= 1) { + return true; + } + + /* + * Check that the first comment is adjacent to the end of the group, the + * last comment is adjacent to the candidate property, and that successive + * comments are adjacent to each other. + */ + const leadingComments = sourceCode.getCommentsBefore(candidate); + + if ( + leadingComments.length && + leadingComments[0].loc.start.line - groupEndLine <= 1 && + candidateValueStartLine - last(leadingComments).loc.end.line <= + 1 + ) { + for (let i = 1; i < leadingComments.length; i++) { + if ( + leadingComments[i].loc.start.line - + leadingComments[i - 1].loc.end.line > + 1 + ) { + return false; + } + } + return true; + } + + return false; + } + + /** + * Gets an object literal property's key as the identifier name or string value. + * @param {ASTNode} property Property node whose key to retrieve. + * @returns {string} The property's key. + */ + function getKey(property) { + const key = property.key; + + if (property.computed) { + return sourceCode.getText().slice(key.range[0], key.range[1]); + } + return astUtils.getStaticPropertyName(property); + } + + /** + * Reports an appropriately-formatted error if spacing is incorrect on one + * side of the colon. + * @param {ASTNode} property Key-value pair in an object literal. + * @param {string} side Side being verified - either "key" or "value". + * @param {string} whitespace Actual whitespace string. + * @param {number} expected Expected whitespace length. + * @param {string} mode Value of the mode as "strict" or "minimum" + * @returns {void} + */ + function report(property, side, whitespace, expected, mode) { + const diff = whitespace.length - expected; + + if ( + ((diff && mode === "strict") || + (diff < 0 && mode === "minimum") || + (diff > 0 && !expected && mode === "minimum")) && + !(expected && containsLineTerminator(whitespace)) + ) { + const nextColon = getNextColon(property.key), + tokenBeforeColon = sourceCode.getTokenBefore(nextColon, { + includeComments: true, + }), + tokenAfterColon = sourceCode.getTokenAfter(nextColon, { + includeComments: true, + }), + isKeySide = side === "key", + isExtra = diff > 0, + diffAbs = Math.abs(diff), + spaces = Array(diffAbs + 1).join(" "); + + const locStart = isKeySide + ? tokenBeforeColon.loc.end + : nextColon.loc.start; + const locEnd = isKeySide + ? nextColon.loc.start + : tokenAfterColon.loc.start; + const missingLoc = isKeySide + ? tokenBeforeColon.loc + : tokenAfterColon.loc; + const loc = isExtra + ? { start: locStart, end: locEnd } + : missingLoc; + + let fix; + + if (isExtra) { + let range; + + // Remove whitespace + if (isKeySide) { + range = [ + tokenBeforeColon.range[1], + tokenBeforeColon.range[1] + diffAbs, + ]; + } else { + range = [ + tokenAfterColon.range[0] - diffAbs, + tokenAfterColon.range[0], + ]; + } + fix = function (fixer) { + return fixer.removeRange(range); + }; + } else { + // Add whitespace + if (isKeySide) { + fix = function (fixer) { + return fixer.insertTextAfter( + tokenBeforeColon, + spaces, + ); + }; + } else { + fix = function (fixer) { + return fixer.insertTextBefore( + tokenAfterColon, + spaces, + ); + }; + } + } + + let messageId; + + if (isExtra) { + messageId = side === "key" ? "extraKey" : "extraValue"; + } else { + messageId = side === "key" ? "missingKey" : "missingValue"; + } + + context.report({ + node: property[side], + loc, + messageId, + data: { + computed: property.computed ? "computed " : "", + key: getKey(property), + }, + fix, + }); + } + } + + /** + * Gets the number of characters in a key, including quotes around string + * keys and braces around computed property keys. + * @param {ASTNode} property Property of on object literal. + * @returns {number} Width of the key. + */ + function getKeyWidth(property) { + const startToken = sourceCode.getFirstToken(property); + const endToken = getLastTokenBeforeColon(property.key); + + return getGraphemeCount( + sourceCode + .getText() + .slice(startToken.range[0], endToken.range[1]), + ); + } + + /** + * Gets the whitespace around the colon in an object literal property. + * @param {ASTNode} property Property node from an object literal. + * @returns {Object} Whitespace before and after the property's colon. + */ + function getPropertyWhitespace(property) { + const whitespace = /(\s*):(\s*)/u.exec( + sourceCode + .getText() + .slice(property.key.range[1], property.value.range[0]), + ); + + if (whitespace) { + return { + beforeColon: whitespace[1], + afterColon: whitespace[2], + }; + } + return null; + } + + /** + * Creates groups of properties. + * @param {ASTNode} node ObjectExpression node being evaluated. + * @returns {Array} Groups of property AST node lists. + */ + function createGroups(node) { + if (node.properties.length === 1) { + return [node.properties]; + } + + return node.properties.reduce( + (groups, property) => { + const currentGroup = last(groups), + prev = last(currentGroup); + + if (!prev || continuesPropertyGroup(prev, property)) { + currentGroup.push(property); + } else { + groups.push([property]); + } + + return groups; + }, + [[]], + ); + } + + /** + * Verifies correct vertical alignment of a group of properties. + * @param {ASTNode[]} properties List of Property AST nodes. + * @returns {void} + */ + function verifyGroupAlignment(properties) { + const length = properties.length, + widths = properties.map(getKeyWidth), // Width of keys, including quotes + align = alignmentOptions.on; // "value" or "colon" + let targetWidth = Math.max(...widths), + beforeColon, + afterColon, + mode; + + if (alignmentOptions && length > 1) { + // When aligning values within a group, use the alignment configuration. + beforeColon = alignmentOptions.beforeColon; + afterColon = alignmentOptions.afterColon; + mode = alignmentOptions.mode; + } else { + beforeColon = multiLineOptions.beforeColon; + afterColon = multiLineOptions.afterColon; + mode = alignmentOptions.mode; + } + + // Conditionally include one space before or after colon + targetWidth += align === "colon" ? beforeColon : afterColon; + + for (let i = 0; i < length; i++) { + const property = properties[i]; + const whitespace = getPropertyWhitespace(property); + + if (whitespace) { + // Object literal getters/setters lack a colon + const width = widths[i]; + + if (align === "value") { + report( + property, + "key", + whitespace.beforeColon, + beforeColon, + mode, + ); + report( + property, + "value", + whitespace.afterColon, + targetWidth - width, + mode, + ); + } else { + // align = "colon" + report( + property, + "key", + whitespace.beforeColon, + targetWidth - width, + mode, + ); + report( + property, + "value", + whitespace.afterColon, + afterColon, + mode, + ); + } + } + } + } + + /** + * Verifies spacing of property conforms to specified options. + * @param {ASTNode} node Property node being evaluated. + * @param {Object} lineOptions Configured singleLine or multiLine options + * @returns {void} + */ + function verifySpacing(node, lineOptions) { + const actual = getPropertyWhitespace(node); + + if (actual) { + // Object literal getters/setters lack colons + report( + node, + "key", + actual.beforeColon, + lineOptions.beforeColon, + lineOptions.mode, + ); + report( + node, + "value", + actual.afterColon, + lineOptions.afterColon, + lineOptions.mode, + ); + } + } + + /** + * Verifies spacing of each property in a list. + * @param {ASTNode[]} properties List of Property AST nodes. + * @param {Object} lineOptions Configured singleLine or multiLine options + * @returns {void} + */ + function verifyListSpacing(properties, lineOptions) { + const length = properties.length; + + for (let i = 0; i < length; i++) { + verifySpacing(properties[i], lineOptions); + } + } + + /** + * Verifies vertical alignment, taking into account groups of properties. + * @param {ASTNode} node ObjectExpression node being evaluated. + * @returns {void} + */ + function verifyAlignment(node) { + createGroups(node).forEach(group => { + const properties = group.filter(isKeyValueProperty); + + if ( + properties.length > 0 && + isSingleLineProperties(properties) + ) { + verifyListSpacing(properties, multiLineOptions); + } else { + verifyGroupAlignment(properties); + } + }); + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + if (alignmentOptions) { + // Verify vertical alignment + + return { + ObjectExpression(node) { + if (isSingleLine(node)) { + verifyListSpacing( + node.properties.filter(isKeyValueProperty), + singleLineOptions, + ); + } else { + verifyAlignment(node); + } + }, + }; + } + + // Obey beforeColon and afterColon in each property as configured + return { + Property(node) { + verifySpacing( + node, + isSingleLine(node.parent) + ? singleLineOptions + : multiLineOptions, + ); + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/keyword-spacing.js b/tools/ui/node_modules/eslint/lib/rules/keyword-spacing.js new file mode 100644 index 0000000000000000000000000000000000000000..0986b43619cd163659dc36072b05dfbdfca6bebb --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/keyword-spacing.js @@ -0,0 +1,701 @@ +/** + * @fileoverview Rule to enforce spacing before and after keywords. + * @author Toru Nagashima + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"), + keywords = require("./utils/keywords"); + +//------------------------------------------------------------------------------ +// Constants +//------------------------------------------------------------------------------ + +const PREV_TOKEN = /^[)\]}>]$/u; +const NEXT_TOKEN = /^(?:[([{<~!]|\+\+?|--?)$/u; +const PREV_TOKEN_M = /^[)\]}>*]$/u; +const NEXT_TOKEN_M = /^[{*]$/u; +const TEMPLATE_OPEN_PAREN = /\$\{$/u; +const TEMPLATE_CLOSE_PAREN = /^\}/u; +const CHECK_TYPE = + /^(?:JSXElement|RegularExpression|String|Template|PrivateIdentifier)$/u; +const KEYS = keywords.concat([ + "as", + "async", + "await", + "from", + "get", + "let", + "of", + "set", + "yield", +]); + +// check duplications. +(function () { + KEYS.sort(); + for (let i = 1; i < KEYS.length; ++i) { + if (KEYS[i] === KEYS[i - 1]) { + throw new Error( + `Duplication was found in the keyword list: ${KEYS[i]}`, + ); + } + } +})(); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether or not a given token is a "Template" token ends with "${". + * @param {Token} token A token to check. + * @returns {boolean} `true` if the token is a "Template" token ends with "${". + */ +function isOpenParenOfTemplate(token) { + return token.type === "Template" && TEMPLATE_OPEN_PAREN.test(token.value); +} + +/** + * Checks whether or not a given token is a "Template" token starts with "}". + * @param {Token} token A token to check. + * @returns {boolean} `true` if the token is a "Template" token starts with "}". + */ +function isCloseParenOfTemplate(token) { + return token.type === "Template" && TEMPLATE_CLOSE_PAREN.test(token.value); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "keyword-spacing", + url: "https://eslint.style/rules/keyword-spacing", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce consistent spacing before and after keywords", + recommended: false, + url: "https://eslint.org/docs/latest/rules/keyword-spacing", + }, + + fixable: "whitespace", + + schema: [ + { + type: "object", + properties: { + before: { type: "boolean", default: true }, + after: { type: "boolean", default: true }, + overrides: { + type: "object", + properties: KEYS.reduce((retv, key) => { + retv[key] = { + type: "object", + properties: { + before: { type: "boolean" }, + after: { type: "boolean" }, + }, + additionalProperties: false, + }; + return retv; + }, {}), + additionalProperties: false, + }, + }, + additionalProperties: false, + }, + ], + messages: { + expectedBefore: 'Expected space(s) before "{{value}}".', + expectedAfter: 'Expected space(s) after "{{value}}".', + unexpectedBefore: 'Unexpected space(s) before "{{value}}".', + unexpectedAfter: 'Unexpected space(s) after "{{value}}".', + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + const tokensToIgnore = new WeakSet(); + + /** + * Reports a given token if there are not space(s) before the token. + * @param {Token} token A token to report. + * @param {RegExp} pattern A pattern of the previous token to check. + * @returns {void} + */ + function expectSpaceBefore(token, pattern) { + const prevToken = sourceCode.getTokenBefore(token); + + if ( + prevToken && + (CHECK_TYPE.test(prevToken.type) || + pattern.test(prevToken.value)) && + !isOpenParenOfTemplate(prevToken) && + !tokensToIgnore.has(prevToken) && + astUtils.isTokenOnSameLine(prevToken, token) && + !sourceCode.isSpaceBetweenTokens(prevToken, token) + ) { + context.report({ + loc: token.loc, + messageId: "expectedBefore", + data: token, + fix(fixer) { + return fixer.insertTextBefore(token, " "); + }, + }); + } + } + + /** + * Reports a given token if there are space(s) before the token. + * @param {Token} token A token to report. + * @param {RegExp} pattern A pattern of the previous token to check. + * @returns {void} + */ + function unexpectSpaceBefore(token, pattern) { + const prevToken = sourceCode.getTokenBefore(token); + + if ( + prevToken && + (CHECK_TYPE.test(prevToken.type) || + pattern.test(prevToken.value)) && + !isOpenParenOfTemplate(prevToken) && + !tokensToIgnore.has(prevToken) && + astUtils.isTokenOnSameLine(prevToken, token) && + sourceCode.isSpaceBetweenTokens(prevToken, token) + ) { + context.report({ + loc: { start: prevToken.loc.end, end: token.loc.start }, + messageId: "unexpectedBefore", + data: token, + fix(fixer) { + return fixer.removeRange([ + prevToken.range[1], + token.range[0], + ]); + }, + }); + } + } + + /** + * Reports a given token if there are not space(s) after the token. + * @param {Token} token A token to report. + * @param {RegExp} pattern A pattern of the next token to check. + * @returns {void} + */ + function expectSpaceAfter(token, pattern) { + const nextToken = sourceCode.getTokenAfter(token); + + if ( + nextToken && + (CHECK_TYPE.test(nextToken.type) || + pattern.test(nextToken.value)) && + !isCloseParenOfTemplate(nextToken) && + !tokensToIgnore.has(nextToken) && + astUtils.isTokenOnSameLine(token, nextToken) && + !sourceCode.isSpaceBetweenTokens(token, nextToken) + ) { + context.report({ + loc: token.loc, + messageId: "expectedAfter", + data: token, + fix(fixer) { + return fixer.insertTextAfter(token, " "); + }, + }); + } + } + + /** + * Reports a given token if there are space(s) after the token. + * @param {Token} token A token to report. + * @param {RegExp} pattern A pattern of the next token to check. + * @returns {void} + */ + function unexpectSpaceAfter(token, pattern) { + const nextToken = sourceCode.getTokenAfter(token); + + if ( + nextToken && + (CHECK_TYPE.test(nextToken.type) || + pattern.test(nextToken.value)) && + !isCloseParenOfTemplate(nextToken) && + !tokensToIgnore.has(nextToken) && + astUtils.isTokenOnSameLine(token, nextToken) && + sourceCode.isSpaceBetweenTokens(token, nextToken) + ) { + context.report({ + loc: { start: token.loc.end, end: nextToken.loc.start }, + messageId: "unexpectedAfter", + data: token, + fix(fixer) { + return fixer.removeRange([ + token.range[1], + nextToken.range[0], + ]); + }, + }); + } + } + + /** + * Parses the option object and determines check methods for each keyword. + * @param {Object|undefined} options The option object to parse. + * @returns {Object} - Normalized option object. + * Keys are keywords (there are for every keyword). + * Values are instances of `{"before": function, "after": function}`. + */ + function parseOptions(options = {}) { + const before = options.before !== false; + const after = options.after !== false; + const defaultValue = { + before: before ? expectSpaceBefore : unexpectSpaceBefore, + after: after ? expectSpaceAfter : unexpectSpaceAfter, + }; + const overrides = (options && options.overrides) || {}; + const retv = Object.create(null); + + for (let i = 0; i < KEYS.length; ++i) { + const key = KEYS[i]; + const override = overrides[key]; + + if (override) { + const thisBefore = + "before" in override ? override.before : before; + const thisAfter = + "after" in override ? override.after : after; + + retv[key] = { + before: thisBefore + ? expectSpaceBefore + : unexpectSpaceBefore, + after: thisAfter + ? expectSpaceAfter + : unexpectSpaceAfter, + }; + } else { + retv[key] = defaultValue; + } + } + + return retv; + } + + const checkMethodMap = parseOptions(context.options[0]); + + /** + * Reports a given token if usage of spacing followed by the token is + * invalid. + * @param {Token} token A token to report. + * @param {RegExp} [pattern] Optional. A pattern of the previous + * token to check. + * @returns {void} + */ + function checkSpacingBefore(token, pattern) { + checkMethodMap[token.value].before(token, pattern || PREV_TOKEN); + } + + /** + * Reports a given token if usage of spacing preceded by the token is + * invalid. + * @param {Token} token A token to report. + * @param {RegExp} [pattern] Optional. A pattern of the next + * token to check. + * @returns {void} + */ + function checkSpacingAfter(token, pattern) { + checkMethodMap[token.value].after(token, pattern || NEXT_TOKEN); + } + + /** + * Reports a given token if usage of spacing around the token is invalid. + * @param {Token} token A token to report. + * @returns {void} + */ + function checkSpacingAround(token) { + checkSpacingBefore(token); + checkSpacingAfter(token); + } + + /** + * Reports the first token of a given node if the first token is a keyword + * and usage of spacing around the token is invalid. + * @param {ASTNode|null} node A node to report. + * @returns {void} + */ + function checkSpacingAroundFirstToken(node) { + const firstToken = node && sourceCode.getFirstToken(node); + + if (firstToken && firstToken.type === "Keyword") { + checkSpacingAround(firstToken); + } + } + + /** + * Reports the first token of a given node if the first token is a keyword + * and usage of spacing followed by the token is invalid. + * + * This is used for unary operators (e.g. `typeof`), `function`, and `super`. + * Other rules are handling usage of spacing preceded by those keywords. + * @param {ASTNode|null} node A node to report. + * @returns {void} + */ + function checkSpacingBeforeFirstToken(node) { + const firstToken = node && sourceCode.getFirstToken(node); + + if (firstToken && firstToken.type === "Keyword") { + checkSpacingBefore(firstToken); + } + } + + /** + * Reports the previous token of a given node if the token is a keyword and + * usage of spacing around the token is invalid. + * @param {ASTNode|null} node A node to report. + * @returns {void} + */ + function checkSpacingAroundTokenBefore(node) { + if (node) { + const token = sourceCode.getTokenBefore( + node, + astUtils.isKeywordToken, + ); + + checkSpacingAround(token); + } + } + + /** + * Reports `async` or `function` keywords of a given node if usage of + * spacing around those keywords is invalid. + * @param {ASTNode} node A node to report. + * @returns {void} + */ + function checkSpacingForFunction(node) { + const firstToken = node && sourceCode.getFirstToken(node); + + if ( + firstToken && + ((firstToken.type === "Keyword" && + firstToken.value === "function") || + firstToken.value === "async") + ) { + checkSpacingBefore(firstToken); + } + } + + /** + * Reports `class` and `extends` keywords of a given node if usage of + * spacing around those keywords is invalid. + * @param {ASTNode} node A node to report. + * @returns {void} + */ + function checkSpacingForClass(node) { + checkSpacingAroundFirstToken(node); + checkSpacingAroundTokenBefore(node.superClass); + } + + /** + * Reports `if` and `else` keywords of a given node if usage of spacing + * around those keywords is invalid. + * @param {ASTNode} node A node to report. + * @returns {void} + */ + function checkSpacingForIfStatement(node) { + checkSpacingAroundFirstToken(node); + checkSpacingAroundTokenBefore(node.alternate); + } + + /** + * Reports `try`, `catch`, and `finally` keywords of a given node if usage + * of spacing around those keywords is invalid. + * @param {ASTNode} node A node to report. + * @returns {void} + */ + function checkSpacingForTryStatement(node) { + checkSpacingAroundFirstToken(node); + checkSpacingAroundFirstToken(node.handler); + checkSpacingAroundTokenBefore(node.finalizer); + } + + /** + * Reports `do` and `while` keywords of a given node if usage of spacing + * around those keywords is invalid. + * @param {ASTNode} node A node to report. + * @returns {void} + */ + function checkSpacingForDoWhileStatement(node) { + checkSpacingAroundFirstToken(node); + checkSpacingAroundTokenBefore(node.test); + } + + /** + * Reports `for` and `in` keywords of a given node if usage of spacing + * around those keywords is invalid. + * @param {ASTNode} node A node to report. + * @returns {void} + */ + function checkSpacingForForInStatement(node) { + checkSpacingAroundFirstToken(node); + + const inToken = sourceCode.getTokenBefore( + node.right, + astUtils.isNotOpeningParenToken, + ); + const previousToken = sourceCode.getTokenBefore(inToken); + + if (previousToken.type !== "PrivateIdentifier") { + checkSpacingBefore(inToken); + } + + checkSpacingAfter(inToken); + } + + /** + * Reports `for` and `of` keywords of a given node if usage of spacing + * around those keywords is invalid. + * @param {ASTNode} node A node to report. + * @returns {void} + */ + function checkSpacingForForOfStatement(node) { + if (node.await) { + checkSpacingBefore(sourceCode.getFirstToken(node, 0)); + checkSpacingAfter(sourceCode.getFirstToken(node, 1)); + } else { + checkSpacingAroundFirstToken(node); + } + + const ofToken = sourceCode.getTokenBefore( + node.right, + astUtils.isNotOpeningParenToken, + ); + const previousToken = sourceCode.getTokenBefore(ofToken); + + if (previousToken.type !== "PrivateIdentifier") { + checkSpacingBefore(ofToken); + } + + checkSpacingAfter(ofToken); + } + + /** + * Reports `import`, `export`, `as`, and `from` keywords of a given node if + * usage of spacing around those keywords is invalid. + * + * This rule handles the `*` token in module declarations. + * + * import*as A from "./a"; /*error Expected space(s) after "import". + * error Expected space(s) before "as". + * @param {ASTNode} node A node to report. + * @returns {void} + */ + function checkSpacingForModuleDeclaration(node) { + const firstToken = sourceCode.getFirstToken(node); + + checkSpacingBefore(firstToken, PREV_TOKEN_M); + checkSpacingAfter(firstToken, NEXT_TOKEN_M); + + if (node.type === "ExportDefaultDeclaration") { + checkSpacingAround(sourceCode.getTokenAfter(firstToken)); + } + + if (node.type === "ExportAllDeclaration" && node.exported) { + const asToken = sourceCode.getTokenBefore(node.exported); + + checkSpacingBefore(asToken, PREV_TOKEN_M); + checkSpacingAfter(asToken, NEXT_TOKEN_M); + } + + if (node.source) { + const fromToken = sourceCode.getTokenBefore(node.source); + + checkSpacingBefore(fromToken, PREV_TOKEN_M); + checkSpacingAfter(fromToken, NEXT_TOKEN_M); + } + } + + /** + * Reports `as` keyword of a given node if usage of spacing around this + * keyword is invalid. + * @param {ASTNode} node An `ImportSpecifier` node to check. + * @returns {void} + */ + function checkSpacingForImportSpecifier(node) { + if (node.imported.range[0] !== node.local.range[0]) { + const asToken = sourceCode.getTokenBefore(node.local); + + checkSpacingBefore(asToken, PREV_TOKEN_M); + } + } + + /** + * Reports `as` keyword of a given node if usage of spacing around this + * keyword is invalid. + * @param {ASTNode} node An `ExportSpecifier` node to check. + * @returns {void} + */ + function checkSpacingForExportSpecifier(node) { + if (node.local.range[0] !== node.exported.range[0]) { + const asToken = sourceCode.getTokenBefore(node.exported); + + checkSpacingBefore(asToken, PREV_TOKEN_M); + checkSpacingAfter(asToken, NEXT_TOKEN_M); + } + } + + /** + * Reports `as` keyword of a given node if usage of spacing around this + * keyword is invalid. + * @param {ASTNode} node A node to report. + * @returns {void} + */ + function checkSpacingForImportNamespaceSpecifier(node) { + const asToken = sourceCode.getFirstToken(node, 1); + + checkSpacingBefore(asToken, PREV_TOKEN_M); + } + + /** + * Reports `static`, `get`, and `set` keywords of a given node if usage of + * spacing around those keywords is invalid. + * @param {ASTNode} node A node to report. + * @throws {Error} If unable to find token get, set, or async beside method name. + * @returns {void} + */ + function checkSpacingForProperty(node) { + if (node.static) { + checkSpacingAroundFirstToken(node); + } + if ( + node.kind === "get" || + node.kind === "set" || + ((node.method || node.type === "MethodDefinition") && + node.value.async) + ) { + const token = sourceCode.getTokenBefore(node.key, tok => { + switch (tok.value) { + case "get": + case "set": + case "async": + return true; + default: + return false; + } + }); + + if (!token) { + throw new Error( + "Failed to find token get, set, or async beside method name", + ); + } + + checkSpacingAround(token); + } + } + + /** + * Reports `await` keyword of a given node if usage of spacing before + * this keyword is invalid. + * @param {ASTNode} node A node to report. + * @returns {void} + */ + function checkSpacingForAwaitExpression(node) { + checkSpacingBefore(sourceCode.getFirstToken(node)); + } + + return { + // Statements + DebuggerStatement: checkSpacingAroundFirstToken, + WithStatement: checkSpacingAroundFirstToken, + + // Statements - Control flow + BreakStatement: checkSpacingAroundFirstToken, + ContinueStatement: checkSpacingAroundFirstToken, + ReturnStatement: checkSpacingAroundFirstToken, + ThrowStatement: checkSpacingAroundFirstToken, + TryStatement: checkSpacingForTryStatement, + + // Statements - Choice + IfStatement: checkSpacingForIfStatement, + SwitchStatement: checkSpacingAroundFirstToken, + SwitchCase: checkSpacingAroundFirstToken, + + // Statements - Loops + DoWhileStatement: checkSpacingForDoWhileStatement, + ForInStatement: checkSpacingForForInStatement, + ForOfStatement: checkSpacingForForOfStatement, + ForStatement: checkSpacingAroundFirstToken, + WhileStatement: checkSpacingAroundFirstToken, + + // Statements - Declarations + ClassDeclaration: checkSpacingForClass, + ExportNamedDeclaration: checkSpacingForModuleDeclaration, + ExportDefaultDeclaration: checkSpacingForModuleDeclaration, + ExportAllDeclaration: checkSpacingForModuleDeclaration, + FunctionDeclaration: checkSpacingForFunction, + ImportDeclaration: checkSpacingForModuleDeclaration, + VariableDeclaration: checkSpacingAroundFirstToken, + + // Expressions + ArrowFunctionExpression: checkSpacingForFunction, + AwaitExpression: checkSpacingForAwaitExpression, + ClassExpression: checkSpacingForClass, + FunctionExpression: checkSpacingForFunction, + NewExpression: checkSpacingBeforeFirstToken, + Super: checkSpacingBeforeFirstToken, + ThisExpression: checkSpacingBeforeFirstToken, + UnaryExpression: checkSpacingBeforeFirstToken, + YieldExpression: checkSpacingBeforeFirstToken, + + // Others + ImportSpecifier: checkSpacingForImportSpecifier, + ExportSpecifier: checkSpacingForExportSpecifier, + ImportNamespaceSpecifier: checkSpacingForImportNamespaceSpecifier, + MethodDefinition: checkSpacingForProperty, + PropertyDefinition: checkSpacingForProperty, + StaticBlock: checkSpacingAroundFirstToken, + Property: checkSpacingForProperty, + + // To avoid conflicts with `space-infix-ops`, e.g. `a > this.b` + "BinaryExpression[operator='>']"(node) { + const operatorToken = sourceCode.getTokenBefore( + node.right, + astUtils.isNotOpeningParenToken, + ); + + tokensToIgnore.add(operatorToken); + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/line-comment-position.js b/tools/ui/node_modules/eslint/lib/rules/line-comment-position.js new file mode 100644 index 0000000000000000000000000000000000000000..6c164033752351555e4acb687141c56267985940 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/line-comment-position.js @@ -0,0 +1,157 @@ +/** + * @fileoverview Rule to enforce the position of line comments + * @author Alberto Rodríguez + * @deprecated in ESLint v9.3.0 + */ +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "9.3.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "line-comment-position", + url: "https://eslint.style/rules/line-comment-position", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce position of line comments", + recommended: false, + url: "https://eslint.org/docs/latest/rules/line-comment-position", + }, + + schema: [ + { + oneOf: [ + { + enum: ["above", "beside"], + }, + { + type: "object", + properties: { + position: { + enum: ["above", "beside"], + }, + ignorePattern: { + type: "string", + }, + applyDefaultPatterns: { + type: "boolean", + }, + applyDefaultIgnorePatterns: { + type: "boolean", + }, + }, + additionalProperties: false, + }, + ], + }, + ], + messages: { + above: "Expected comment to be above code.", + beside: "Expected comment to be beside code.", + }, + }, + + create(context) { + const options = context.options[0]; + + let above, + ignorePattern, + applyDefaultIgnorePatterns = true; + + if (!options || typeof options === "string") { + above = !options || options === "above"; + } else { + above = !options.position || options.position === "above"; + ignorePattern = options.ignorePattern; + + if (Object.hasOwn(options, "applyDefaultIgnorePatterns")) { + applyDefaultIgnorePatterns = options.applyDefaultIgnorePatterns; + } else { + applyDefaultIgnorePatterns = + options.applyDefaultPatterns !== false; + } + } + + const defaultIgnoreRegExp = astUtils.COMMENTS_IGNORE_PATTERN; + const fallThroughRegExp = /^\s*falls?\s?through/u; + const customIgnoreRegExp = new RegExp(ignorePattern, "u"); + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + Program() { + const comments = sourceCode.getAllComments(); + + comments + .filter(token => token.type === "Line") + .forEach(node => { + if ( + applyDefaultIgnorePatterns && + (defaultIgnoreRegExp.test(node.value) || + fallThroughRegExp.test(node.value)) + ) { + return; + } + + if ( + ignorePattern && + customIgnoreRegExp.test(node.value) + ) { + return; + } + + const previous = sourceCode.getTokenBefore(node, { + includeComments: true, + }); + const isOnSameLine = + previous && + previous.loc.end.line === node.loc.start.line; + + if (above) { + if (isOnSameLine) { + context.report({ + node, + messageId: "above", + }); + } + } else { + if (!isOnSameLine) { + context.report({ + node, + messageId: "beside", + }); + } + } + }); + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/linebreak-style.js b/tools/ui/node_modules/eslint/lib/rules/linebreak-style.js new file mode 100644 index 0000000000000000000000000000000000000000..aea1b8ce1ddd102ae3fdca3d600abb4e04ea19cf --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/linebreak-style.js @@ -0,0 +1,135 @@ +/** + * @fileoverview Rule to enforce a single linebreak style. + * @author Erik Mueller + * @deprecated in ESLint v8.53.0 + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** + * @import { SourceRange } from "@eslint/core"; + */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "linebreak-style", + url: "https://eslint.style/rules/linebreak-style", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Enforce consistent linebreak style", + recommended: false, + url: "https://eslint.org/docs/latest/rules/linebreak-style", + }, + + fixable: "whitespace", + + schema: [ + { + enum: ["unix", "windows"], + }, + ], + messages: { + expectedLF: "Expected linebreaks to be 'LF' but found 'CRLF'.", + expectedCRLF: "Expected linebreaks to be 'CRLF' but found 'LF'.", + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Builds a fix function that replaces text at the specified range in the source text. + * @param {SourceRange} range The range to replace + * @param {string} text The text to insert. + * @returns {Function} Fixer function + * @private + */ + function createFix(range, text) { + return function (fixer) { + return fixer.replaceTextRange(range, text); + }; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + Program: function checkForLinebreakStyle(node) { + const linebreakStyle = context.options[0] || "unix", + expectedLF = linebreakStyle === "unix", + expectedLFChars = expectedLF ? "\n" : "\r\n", + source = sourceCode.getText(), + pattern = astUtils.createGlobalLinebreakMatcher(); + let match; + + let i = 0; + + while ((match = pattern.exec(source)) !== null) { + i++; + if (match[0] === expectedLFChars) { + continue; + } + + const index = match.index; + const range = [index, index + match[0].length]; + + context.report({ + node, + loc: { + start: { + line: i, + column: sourceCode.lines[i - 1].length, + }, + end: { + line: i + 1, + column: 0, + }, + }, + messageId: expectedLF ? "expectedLF" : "expectedCRLF", + fix: createFix(range, expectedLFChars), + }); + } + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/lines-around-comment.js b/tools/ui/node_modules/eslint/lib/rules/lines-around-comment.js new file mode 100644 index 0000000000000000000000000000000000000000..7b2d0ac807d16419279fc14efa160fb06c649f75 --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/lines-around-comment.js @@ -0,0 +1,581 @@ +/** + * @fileoverview Enforces empty lines around comments. + * @author Jamund Ferguson + * @deprecated in ESLint v8.53.0 + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Return an array with any line numbers that are empty. + * @param {Array} lines An array of each line of the file. + * @returns {Array} An array of line numbers. + */ +function getEmptyLineNums(lines) { + const emptyLines = lines + .map((line, i) => ({ + code: line.trim(), + num: i + 1, + })) + .filter(line => !line.code) + .map(line => line.num); + + return emptyLines; +} + +/** + * Return an array with any line numbers that contain comments. + * @param {Array} comments An array of comment tokens. + * @returns {Array} An array of line numbers. + */ +function getCommentLineNums(comments) { + const lines = []; + + comments.forEach(token => { + const start = token.loc.start.line; + const end = token.loc.end.line; + + lines.push(start, end); + }); + return lines; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + deprecated: { + message: "Formatting rules are being moved out of ESLint core.", + url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/", + deprecatedSince: "8.53.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: + "ESLint Stylistic now maintains deprecated stylistic core rules.", + url: "https://eslint.style/guide/migration", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "lines-around-comment", + url: "https://eslint.style/rules/lines-around-comment", + }, + }, + ], + }, + type: "layout", + + docs: { + description: "Require empty lines around comments", + recommended: false, + url: "https://eslint.org/docs/latest/rules/lines-around-comment", + }, + + fixable: "whitespace", + + schema: [ + { + type: "object", + properties: { + beforeBlockComment: { + type: "boolean", + default: true, + }, + afterBlockComment: { + type: "boolean", + default: false, + }, + beforeLineComment: { + type: "boolean", + default: false, + }, + afterLineComment: { + type: "boolean", + default: false, + }, + allowBlockStart: { + type: "boolean", + default: false, + }, + allowBlockEnd: { + type: "boolean", + default: false, + }, + allowClassStart: { + type: "boolean", + }, + allowClassEnd: { + type: "boolean", + }, + allowObjectStart: { + type: "boolean", + }, + allowObjectEnd: { + type: "boolean", + }, + allowArrayStart: { + type: "boolean", + }, + allowArrayEnd: { + type: "boolean", + }, + ignorePattern: { + type: "string", + }, + applyDefaultIgnorePatterns: { + type: "boolean", + }, + afterHashbangComment: { + type: "boolean", + default: false, + }, + }, + additionalProperties: false, + }, + ], + messages: { + after: "Expected line after comment.", + before: "Expected line before comment.", + }, + }, + + create(context) { + const options = Object.assign({}, context.options[0]); + const ignorePattern = options.ignorePattern; + const defaultIgnoreRegExp = astUtils.COMMENTS_IGNORE_PATTERN; + const customIgnoreRegExp = new RegExp(ignorePattern, "u"); + const applyDefaultIgnorePatterns = + options.applyDefaultIgnorePatterns !== false; + + options.beforeBlockComment = + typeof options.beforeBlockComment !== "undefined" + ? options.beforeBlockComment + : true; + + const sourceCode = context.sourceCode; + + const lines = sourceCode.lines, + numLines = lines.length + 1, + comments = sourceCode.getAllComments(), + commentLines = getCommentLineNums(comments), + emptyLines = getEmptyLineNums(lines), + commentAndEmptyLines = new Set(commentLines.concat(emptyLines)); + + /** + * Returns whether or not comments are on lines starting with or ending with code + * @param {token} token The comment token to check. + * @returns {boolean} True if the comment is not alone. + */ + function codeAroundComment(token) { + let currentToken = token; + + do { + currentToken = sourceCode.getTokenBefore(currentToken, { + includeComments: true, + }); + } while (currentToken && astUtils.isCommentToken(currentToken)); + + if ( + currentToken && + astUtils.isTokenOnSameLine(currentToken, token) + ) { + return true; + } + + currentToken = token; + do { + currentToken = sourceCode.getTokenAfter(currentToken, { + includeComments: true, + }); + } while (currentToken && astUtils.isCommentToken(currentToken)); + + if ( + currentToken && + astUtils.isTokenOnSameLine(token, currentToken) + ) { + return true; + } + + return false; + } + + /** + * Returns whether or not comments are inside a node type or not. + * @param {ASTNode} parent The Comment parent node. + * @param {string} nodeType The parent type to check against. + * @returns {boolean} True if the comment is inside nodeType. + */ + function isParentNodeType(parent, nodeType) { + return ( + parent.type === nodeType || + (parent.body && parent.body.type === nodeType) || + (parent.consequent && parent.consequent.type === nodeType) + ); + } + + /** + * Returns the parent node that contains the given token. + * @param {token} token The token to check. + * @returns {ASTNode|null} The parent node that contains the given token. + */ + function getParentNodeOfToken(token) { + const node = sourceCode.getNodeByRangeIndex(token.range[0]); + + /* + * For the purpose of this rule, the comment token is in a `StaticBlock` node only + * if it's inside the braces of that `StaticBlock` node. + * + * Example where this function returns `null`: + * + * static + * // comment + * { + * } + * + * Example where this function returns `StaticBlock` node: + * + * static + * { + * // comment + * } + * + */ + if (node && node.type === "StaticBlock") { + const openingBrace = sourceCode.getFirstToken(node, { + skip: 1, + }); // skip the `static` token + + return token.range[0] >= openingBrace.range[0] ? node : null; + } + + return node; + } + + /** + * Returns whether or not comments are at the parent start or not. + * @param {token} token The Comment token. + * @param {string} nodeType The parent type to check against. + * @returns {boolean} True if the comment is at parent start. + */ + function isCommentAtParentStart(token, nodeType) { + const parent = getParentNodeOfToken(token); + + if (parent && isParentNodeType(parent, nodeType)) { + let parentStartNodeOrToken = parent; + + if (parent.type === "StaticBlock") { + parentStartNodeOrToken = sourceCode.getFirstToken(parent, { + skip: 1, + }); // opening brace of the static block + } else if (parent.type === "SwitchStatement") { + parentStartNodeOrToken = sourceCode.getTokenAfter( + parent.discriminant, + { + filter: astUtils.isOpeningBraceToken, + }, + ); // opening brace of the switch statement + } + + return ( + token.loc.start.line - + parentStartNodeOrToken.loc.start.line === + 1 + ); + } + + return false; + } + + /** + * Returns whether or not comments are at the parent end or not. + * @param {token} token The Comment token. + * @param {string} nodeType The parent type to check against. + * @returns {boolean} True if the comment is at parent end. + */ + function isCommentAtParentEnd(token, nodeType) { + const parent = getParentNodeOfToken(token); + + return ( + !!parent && + isParentNodeType(parent, nodeType) && + parent.loc.end.line - token.loc.end.line === 1 + ); + } + + /** + * Returns whether or not comments are at the block start or not. + * @param {token} token The Comment token. + * @returns {boolean} True if the comment is at block start. + */ + function isCommentAtBlockStart(token) { + return ( + isCommentAtParentStart(token, "ClassBody") || + isCommentAtParentStart(token, "BlockStatement") || + isCommentAtParentStart(token, "StaticBlock") || + isCommentAtParentStart(token, "SwitchCase") || + isCommentAtParentStart(token, "SwitchStatement") + ); + } + + /** + * Returns whether or not comments are at the block end or not. + * @param {token} token The Comment token. + * @returns {boolean} True if the comment is at block end. + */ + function isCommentAtBlockEnd(token) { + return ( + isCommentAtParentEnd(token, "ClassBody") || + isCommentAtParentEnd(token, "BlockStatement") || + isCommentAtParentEnd(token, "StaticBlock") || + isCommentAtParentEnd(token, "SwitchCase") || + isCommentAtParentEnd(token, "SwitchStatement") + ); + } + + /** + * Returns whether or not comments are at the class start or not. + * @param {token} token The Comment token. + * @returns {boolean} True if the comment is at class start. + */ + function isCommentAtClassStart(token) { + return isCommentAtParentStart(token, "ClassBody"); + } + + /** + * Returns whether or not comments are at the class end or not. + * @param {token} token The Comment token. + * @returns {boolean} True if the comment is at class end. + */ + function isCommentAtClassEnd(token) { + return isCommentAtParentEnd(token, "ClassBody"); + } + + /** + * Returns whether or not comments are at the object start or not. + * @param {token} token The Comment token. + * @returns {boolean} True if the comment is at object start. + */ + function isCommentAtObjectStart(token) { + return ( + isCommentAtParentStart(token, "ObjectExpression") || + isCommentAtParentStart(token, "ObjectPattern") + ); + } + + /** + * Returns whether or not comments are at the object end or not. + * @param {token} token The Comment token. + * @returns {boolean} True if the comment is at object end. + */ + function isCommentAtObjectEnd(token) { + return ( + isCommentAtParentEnd(token, "ObjectExpression") || + isCommentAtParentEnd(token, "ObjectPattern") + ); + } + + /** + * Returns whether or not comments are at the array start or not. + * @param {token} token The Comment token. + * @returns {boolean} True if the comment is at array start. + */ + function isCommentAtArrayStart(token) { + return ( + isCommentAtParentStart(token, "ArrayExpression") || + isCommentAtParentStart(token, "ArrayPattern") + ); + } + + /** + * Returns whether or not comments are at the array end or not. + * @param {token} token The Comment token. + * @returns {boolean} True if the comment is at array end. + */ + function isCommentAtArrayEnd(token) { + return ( + isCommentAtParentEnd(token, "ArrayExpression") || + isCommentAtParentEnd(token, "ArrayPattern") + ); + } + + /** + * Checks if a comment token has lines around it (ignores inline comments) + * @param {token} token The Comment token. + * @param {Object} opts Options to determine the newline. + * @param {boolean} opts.after Should have a newline after this line. + * @param {boolean} opts.before Should have a newline before this line. + * @returns {void} + */ + function checkForEmptyLine(token, opts) { + if ( + applyDefaultIgnorePatterns && + defaultIgnoreRegExp.test(token.value) + ) { + return; + } + + if (ignorePattern && customIgnoreRegExp.test(token.value)) { + return; + } + + let after = opts.after, + before = opts.before; + + const prevLineNum = token.loc.start.line - 1, + nextLineNum = token.loc.end.line + 1, + commentIsNotAlone = codeAroundComment(token); + + const blockStartAllowed = + options.allowBlockStart && + isCommentAtBlockStart(token) && + !( + options.allowClassStart === false && + isCommentAtClassStart(token) + ), + blockEndAllowed = + options.allowBlockEnd && + isCommentAtBlockEnd(token) && + !( + options.allowClassEnd === false && + isCommentAtClassEnd(token) + ), + classStartAllowed = + options.allowClassStart && isCommentAtClassStart(token), + classEndAllowed = + options.allowClassEnd && isCommentAtClassEnd(token), + objectStartAllowed = + options.allowObjectStart && isCommentAtObjectStart(token), + objectEndAllowed = + options.allowObjectEnd && isCommentAtObjectEnd(token), + arrayStartAllowed = + options.allowArrayStart && isCommentAtArrayStart(token), + arrayEndAllowed = + options.allowArrayEnd && isCommentAtArrayEnd(token); + + const exceptionStartAllowed = + blockStartAllowed || + classStartAllowed || + objectStartAllowed || + arrayStartAllowed; + const exceptionEndAllowed = + blockEndAllowed || + classEndAllowed || + objectEndAllowed || + arrayEndAllowed; + + // ignore top of the file and bottom of the file + if (prevLineNum < 1) { + before = false; + } + if (nextLineNum >= numLines) { + after = false; + } + + // we ignore all inline comments + if (commentIsNotAlone) { + return; + } + + const previousTokenOrComment = sourceCode.getTokenBefore(token, { + includeComments: true, + }); + const nextTokenOrComment = sourceCode.getTokenAfter(token, { + includeComments: true, + }); + + // check for newline before + if ( + !exceptionStartAllowed && + before && + !commentAndEmptyLines.has(prevLineNum) && + !( + astUtils.isCommentToken(previousTokenOrComment) && + astUtils.isTokenOnSameLine(previousTokenOrComment, token) + ) + ) { + const lineStart = token.range[0] - token.loc.start.column; + const range = [lineStart, lineStart]; + + context.report({ + node: token, + messageId: "before", + fix(fixer) { + return fixer.insertTextBeforeRange(range, "\n"); + }, + }); + } + + // check for newline after + if ( + !exceptionEndAllowed && + after && + !commentAndEmptyLines.has(nextLineNum) && + !( + astUtils.isCommentToken(nextTokenOrComment) && + astUtils.isTokenOnSameLine(token, nextTokenOrComment) + ) + ) { + context.report({ + node: token, + messageId: "after", + fix(fixer) { + return fixer.insertTextAfter(token, "\n"); + }, + }); + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + Program() { + comments.forEach(token => { + if (token.type === "Line") { + if ( + options.beforeLineComment || + options.afterLineComment + ) { + checkForEmptyLine(token, { + after: options.afterLineComment, + before: options.beforeLineComment, + }); + } + } else if (token.type === "Block") { + if ( + options.beforeBlockComment || + options.afterBlockComment + ) { + checkForEmptyLine(token, { + after: options.afterBlockComment, + before: options.beforeBlockComment, + }); + } + } else if (token.type === "Shebang") { + if (options.afterHashbangComment) { + checkForEmptyLine(token, { + after: options.afterHashbangComment, + before: false, + }); + } + } + }); + }, + }; + }, +}; diff --git a/tools/ui/node_modules/eslint/lib/rules/lines-around-directive.js b/tools/ui/node_modules/eslint/lib/rules/lines-around-directive.js new file mode 100644 index 0000000000000000000000000000000000000000..bf57154b33ad8d9dcf97d0886723dcecc12884af --- /dev/null +++ b/tools/ui/node_modules/eslint/lib/rules/lines-around-directive.js @@ -0,0 +1,249 @@ +/** + * @fileoverview Require or disallow newlines around directives. + * @author Kai Cataldo + * @deprecated in ESLint v4.0.0 + */ + +"use strict"; + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** @type {import('../types').Rule.RuleModule} */ +module.exports = { + meta: { + type: "layout", + + docs: { + description: "Require or disallow newlines around directives", + recommended: false, + url: "https://eslint.org/docs/latest/rules/lines-around-directive", + }, + + schema: [ + { + oneOf: [ + { + enum: ["always", "never"], + }, + { + type: "object", + properties: { + before: { + enum: ["always", "never"], + }, + after: { + enum: ["always", "never"], + }, + }, + additionalProperties: false, + minProperties: 2, + }, + ], + }, + ], + + fixable: "whitespace", + messages: { + expected: 'Expected newline {{location}} "{{value}}" directive.', + unexpected: + 'Unexpected newline {{location}} "{{value}}" directive.', + }, + deprecated: { + message: "The rule was replaced with a more general rule.", + url: "https://eslint.org/blog/2017/06/eslint-v4.0.0-released/", + deprecatedSince: "4.0.0", + availableUntil: "11.0.0", + replacedBy: [ + { + message: "The new rule moved to a plugin.", + url: "https://eslint.org/docs/latest/rules/padding-line-between-statements#examples", + plugin: { + name: "@stylistic/eslint-plugin", + url: "https://eslint.style", + }, + rule: { + name: "padding-line-between-statements", + url: "https://eslint.style/rules/padding-line-between-statements", + }, + }, + ], + }, + }, + + create(context) { + const sourceCode = context.sourceCode; + const config = context.options[0] || "always"; + const expectLineBefore = + typeof config === "string" ? config : config.before; + const expectLineAfter = + typeof config === "string" ? config : config.after; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Check if node is preceded by a blank newline. + * @param {ASTNode} node Node to check. + * @returns {boolean} Whether or not the passed in node is preceded by a blank newline. + */ + function hasNewlineBefore(node) { + const tokenBefore = sourceCode.getTokenBefore(node, { + includeComments: true, + }); + const tokenLineBefore = tokenBefore ? tokenBefore.loc.end.line : 0; + + return node.loc.start.line - tokenLineBefore >= 2; + } + + /** + * Gets the last token of a node that is on the same line as the rest of the node. + * This will usually be the last token of the node, but it will be the second-to-last token if the node has a trailing + * semicolon on a different line. + * @param {ASTNode} node A directive node + * @returns {Token} The last token of the node on the line + */ + function getLastTokenOnLine(node) { + const lastToken = sourceCode.getLastToken(node); + const secondToLastToken = sourceCode.getTokenBefore(lastToken); + + return astUtils.isSemicolonToken(lastToken) && + lastToken.loc.start.line > secondToLastToken.loc.end.line + ? secondToLastToken + : lastToken; + } + + /** + * Check if node is followed by a blank newline. + * @param {ASTNode} node Node to check. + * @returns {boolean} Whether or not the passed in node is followed by a blank newline. + */ + function hasNewlineAfter(node) { + const lastToken = getLastTokenOnLine(node); + const tokenAfter = sourceCode.getTokenAfter(lastToken, { + includeComments: true, + }); + + return tokenAfter.loc.start.line - lastToken.loc.end.line >= 2; + } + + /** + * Report errors for newlines around directives. + * @param {ASTNode} node Node to check. + * @param {string} location Whether the error was found before or after the directive. + * @param {boolean} expected Whether or not a newline was expected or unexpected. + * @returns {void} + */ + function reportError(node, location, expected) { + context.report({ + node, + messageId: expected ? "expected" : "unexpected", + data: { + value: node.expression.value, + location, + }, + fix(fixer) { + const lastToken = getLastTokenOnLine(node); + + if (expected) { + return location === "before" + ? fixer.insertTextBefore(node, "\n") + : fixer.insertTextAfter(lastToken, "\n"); + } + return fixer.removeRange( + location === "before" + ? [node.range[0] - 1, node.range[0]] + : [lastToken.range[1], lastToken.range[1] + 1], + ); + }, + }); + } + + /** + * Check lines around directives in node + * @param {ASTNode} node node to check + * @returns {void} + */ + function checkDirectives(node) { + const directives = astUtils.getDirectivePrologue(node); + + if (!directives.length) { + return; + } + + const firstDirective = directives[0]; + const leadingComments = + sourceCode.getCommentsBefore(firstDirective); + + /* + * Only check before the first directive if it is preceded by a comment or if it is at the top of + * the file and expectLineBefore is set to "never". This is to not force a newline at the top of + * the file if there are no comments as well as for compatibility with padded-blocks. + */ + if (leadingComments.length) { + if ( + expectLineBefore === "always" && + !hasNewlineBefore(firstDirective) + ) { + reportError(firstDirective, "before", true); + } + + if ( + expectLineBefore === "never" && + hasNewlineBefore(firstDirective) + ) { + reportError(firstDirective, "before", false); + } + } else if ( + node.type === "Program" && + expectLineBefore === "never" && + !leadingComments.length && + hasNewlineBefore(firstDirective) + ) { + reportError(firstDirective, "before", false); + } + + const lastDirective = directives.at(-1); + const statements = + node.type === "Program" ? node.body : node.body.body; + + /* + * Do not check after the last directive if the body only + * contains a directive prologue and isn't followed by a comment to ensure + * this rule behaves well with padded-blocks. + */ + if ( + lastDirective === statements.at(-1) && + !lastDirective.trailingComments + ) { + return; + } + + if ( + expectLineAfter === "always" && + !hasNewlineAfter(lastDirective) + ) { + reportError(lastDirective, "after", true); + } + + if (expectLineAfter === "never" && hasNewlineAfter(lastDirective)) { + reportError(lastDirective, "after", false); + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + Program: checkDirectives, + FunctionDeclaration: checkDirectives, + FunctionExpression: checkDirectives, + ArrowFunctionExpression: checkDirectives, + }; + }, +};